Tuesday, February 5, 2019

How to deal with “java.lang.OutOfMemoryError: Java heap space” error?


Run Java with the command-line option -Xmx, which sets the maximum size of the heap.

how to increase java heap memory permanently?


I have one problem with java heap memory. I developed one client server application in java which is run as a windows service it requires more than 512MB of memory. I have 2GB of RAM but when I run my application it throws an exception

Out of memory error:java heap space

but I have already set heap size (maximum 512MB) in the java control panel and I still get the same error. I can't set heap size through the command line because my application runs as a windows service so how can I increase the default heap size?

Answer : - 
The Java Virtual Machine takes two command line arguments which set the initial and maximum heap sizes: -Xms and -Xmx. You can add a system environment variable named _JAVA_OPTIONS, and set the heap size values there.
For example if you want a 512Mb initial and 1024Mb maximum heap size you could use:
under Windows:
SET _JAVA_OPTIONS = -Xms512m -Xmx1024m
under Linux:
export _JAVA_OPTIONS="-Xms512m -Xmx1024m"
It is possible to read the default JVM heap size programmatically by using totalMemory() method of Runtime class. Use following code to read JVM heap size.
public class GetHeapSize {
    public static void main(String[]args){

        //Get the jvm heap size.
        long heapSize = Runtime.getRuntime().totalMemory();

        //Print the jvm heap size.
        System.out.println("Heap Size = " + heapSize);
    }
}

 

I am wondering if I have 2 servers, one that is "main" server and the other one is just there(Both are using the same back-end code). How should I handle if main server crash and I want my clients to user the other server, making it so they don't have to restart their program or anything like that?

Here are some alternatives that might be much more robust:
ADDENDUM:

java.lang.StackOverflowError – How to solve StackOverflowError

  • The simplest solution is to carefully inspect the stack trace and detect the repeating pattern of line numbers. These line numbers indicate the code being recursively called. Once you detect these lines, you must carefully inspect your code and understand why the recursion never terminates.
  • If you have verified that the recursion is implemented correctly, you can increase the stack’s size, in order to allow a larger number of invocations. Depending on the Java Virtual Machine (JVM) installed, the default thread stack size may equal to either 512KB, or 1MB. You can increase the thread stack size using the -Xss flag. This flag can be specified either via the project’s configuration, or via the command line. The format of the -Xss argument is:
    -Xss<size>[g|G|m|M|k|K]

How to handle StackOverflowError in Java?

public class Example {
    public static void endless() {
        endless();
    }

    public static void main(String args[]) {
        try {
            endless();
        } catch(StackOverflowError t) {
            // more general: catch(Error t)
            // anything: catch(Throwable t)
            System.out.println("Caught "+t);
            t.printStackTrace();
        }
        System.out.println("After the error...");
    }
}

Where does class, object, reference variable get stored in java. IN heap or stack? Where is heap or stack located?

Runtime data area in JVM can be divided as below,
  1. Method Area : Storage area for compiled class files. (One per JVM instance)
  2. Heap : Storage area for Objects. (One per JVM instance)
  3. Java stack: Storage area for local variables, results of intermediate operations. (One per thread)
  4. PC Register : Stores the address of the next instruction to be executed if the next instruction is native method then the value in pc register will be undefined. (One per thread)
  5. Native method stacks : Helps in executing native methods (methods written in languages other than Java). (One per thread)

What is the purpose of rethrowing the same exception in Java?


Explanation of “ClassCastException” in Java?

So, for example, when one tries to cast an Integer to a String, String is not an subclass of Integer, so a ClassCastException will be thrown.
Object i = Integer.valueOf(42);
String s = (String)i;  

Rethrowing exceptions in Java without losing the stack trace?

catch (WhateverException e) {
    throw e;
}
will simply rethrow the exception you've caught (obviously the surrounding method has to permit this via its signature etc.). The exception will maintain the original stack trace.

Difference between java.lang.RuntimeException and java.lang.Exception

Generally RuntimeExceptions are exceptions that can be prevented programmatically. E.g NullPointerException, ArrayIndexOutOfBoundException. If you check for null before calling any method, NullPointerException would never occur. Similarly ArrayIndexOutOfBoundException would never occur if you check the index first. RuntimeException are not checked by the compiler, so it is clean code.
EDIT : These days people favor RuntimeException because the clean code it produces. It is totally a personal choice.

Keep getting java.lang.NoClassDefFoundError in Spring

The reason for this is, inside your jar you have only your classes without any dependencies.

Java string.split - by multiple character delimiter?

String.split takes a regular expression, in this case, you want non-word characters (regex \W) to be the split, so it's simply:
String input = "Hi,X How-how are:any you?";
String[] parts = input.split("[\\W]");

How to split a string in Java?

String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556

How do I convert a String to an int in Java?

For example, here are two ways:
Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);
There is a slight difference between these methods:
  • valueOf returns a new or cached instance of java.lang.Integer
  • parseInt returns primitive int.

What is the difference between Path and ClassPath in Java?

1).Path is an environment variable which is used by the operating system to find the executables.

Classpath is an environment variable which is used by the Java compiler to find the path, of classes.ie in J2EE we give the path of jar files.


2).PATH is nothing but setting up an environment for operating system. Operating System will look in this PATH for executables.

Classpath is nothing but setting up the environment for Java. Java will use to find compiled classes

3).Path refers to the system while classpath refers to the Developing Envornment.

Why can't the compiler detect this error regarding Serializable declaration at compile time?

Answer: 

Monday, February 4, 2019

Why doesn't the Object already implement Serializable? Members that we wouldn't want to be serializable may be made as transient. Why prevent the default Serializability?

1. Serializable is marker interface, which is empty, but when a class is marked Serializable that means its objects are Serializable.

Extending class with private constructor in Serializable class

The document says that a non-serializable supertype needs a no-arg constructor. It does not say it should be private. On the contrary it says this constructor should be accessible. What the documentation means about runtime is this
class A {
    A() {   <-- accessible only in current package
    }
}

public class B extends A implements Serializable {
    public B() {
    }
}

Why can't I serialize an object without a no-arg constructor even though it implements Serializable?

Answer : A Serializable class doesn't need a no-args constructor. Its nearest non-serializable base class does

Friday, January 18, 2019

If there are 20 people in a tournament and each match the loser will leave the tournament then how many total matches should be played to decide the winner

Implementing a queue with stack as the internal data-structure?

An algorithm to sort an array of integers which has only tow values 0 and 1 without using second loop and with best possible time complexity.

Wednesday, January 9, 2019

Method overloading and null error in Java?

public class Test
{
    // Overloaded methods
    public void fun(Integer i)
    {
        System.out.println("fun(Integer ) ");
    }
    public void fun(String name)
    {
        System.out.println("fun(String ) ");
    }

    // Driver code
    public static void main(String [] args)
    {
        Test mv = new Test();

        // This line causes error
        mv.fun(null);
    }
}

Here the method arguments Integer and String both are not primitive data types in Java. That means they accept null values. When we pass a null value to the method1 the compiler gets confused which method it has to select, as both are accepting the null.

public class Test
{
    // Overloaded methods
    public void fun(Integer i)
    {
        System.out.println("fun(Integer ) ");
    }
    public void fun(String name)
    {
        System.out.println("fun(String ) ");
    }

    // Driver code
    public static void main(String [] args)
    {
        Test mv = new Test();
       
        Integer arg = null;

        // No compiler error
        mv.fun(arg);
    }
}

Here we wouldn’t get compile time error because we are specifying that the argument is of type Integer, hence the compiler selects the method1(Integer i) and will execute the code inside that.

Sometimes unexpected errors can result when overloading a method that takes a variable length argument?


// Java program to illustrate Varargs and ambiguity
class Test
{
    // A method that takes varargs(here integers).
    static void fun(int ... a)
    {
        System.out.print("fun(int ...): " +
                "Number of args: " + a.length +
                " Contents: ");
       
        // using for each loop to display contents of a
        for(int x : a)
            System.out.print(x + " ");
       
        System.out.println();
    }
   
    // A method that takes varargs(here booleans).
    static void fun(boolean ... a)
    {
        System.out.print("fun(boolean ...) " +
                "Number of args: " + a.length +
                " Contents: ");
       
        // using for each loop to display contents of a
        for(boolean x : a)
            System.out.print(x + " ");
       
        System.out.println();
    }
   
    public static void main(String args[])
    {
        // Calling overloaded fun() with different parameter
        fun(1, 2); //OK
        fun(true, false, false); //OK
        //fun(); // Error: Ambiguous!
    }
}


In above program, the overloading of fun( ) is perfectly correct. However, this program will not compile because of the following call:
fun(); // Error: Ambiguous!
According to (JLS 15.2.2), there are 3 phases used in overload resolution: First phase performs overload resolution without permitting boxing or unboxing conversion, Second phase performs overload resolution while allowing boxing and unboxing and Third phase allows overloading to be combined with variable arity methods, boxing, and unboxing. If no applicable method is found during these phases, then ambiguity occurs.

Methods with Varargs alongwith other parameters?

Hare Java uses both the number of arguments and the type of the arguments to determine which method to call.

Example :-
// Java program to demonstrate Varargs
// and overloading.
class Test
{
    // A method that takes varargs(here integers).
    static void fun(int ... a)
    {
        System.out.print("fun(int ...): " +
                "Number of args: " + a.length +
                " Contents: ");
      
        // using for each loop to display contents of a
        for(int x : a)
            System.out.print(x + " ");
      
        System.out.println();
    }
   
    // A method that takes varargs(here booleans).
    static void fun(boolean ... a)
    {
        System.out.print("fun(boolean ...) " +
                "Number of args: " + a.length +
                " Contents: ");
      
        // using for each loop to display contents of a
        for(boolean x : a)
            System.out.print(x + " ");
      
        System.out.println();
    }
   
    // A method takes string as a argument followed by varargs(here integers).
    static void fun(String msg, int ... a)
    {
        System.out.print("fun(String, int ...): " +
                msg + a.length +
                " Contents: ");
      
        // using for each loop to display contents of a
        for(int x : a)
            System.out.print(x + " ");
      
        System.out.println();
    }
   
    public static void main(String args[])
    {
        // Calling overloaded fun() with different parameter
        fun(1, 2, 3);
        fun("Testing: ", 10, 20);
        fun(true, false, false);
    }

Method Overloading and Ambiguity in Varargs in Java

Java uses the type difference to determine which overloaded method to call. If one method signature is strictly more specific than the other, then Java chooses it without an error.

Example :-

//Java program to illustrate
//method overloading in varargs
public class varargsDemo
{
    public static void main(String[] args)
    {
        fun();
    }

    //varargs method with float datatype
    static void fun(float... x)
    {
        System.out.println("float varargs");
    }
   
    //varargs method with int datatype
    static void fun(int... x)
    {
        System.out.println("int varargs");
    }
   
    //varargs method with double datatype
    static void fun(double... x)
    {
        System.out.println("double varargs");
    }
}

Output:
int varargs 
 
 The rule that the most specific method is chosen according to type promotion
 
  • double > float
  • float > long
  • long > int
  • int > char
  • int > short
  • short > byte
 

Difference between abstraction and encapsulation?

Encapsulation is hiding the implementation details which may or may not be for generic or specialized behavior(s).
Abstraction is providing a generalization (say, over a set of behaviors).

Is inheritance necessary for encapsulation, abstraction and polymorphism?

  • Is Encapsulation possible without inheritance?
Yes, because Encapsulation is the ability to hide a class properties from the outside world by means of access methods.
  • Is Abstraction possible without inheritance?
Well, abstraction can refer to many things, but talking about OOP: No, an abstract class cannot be used directly, you can only instantiate inherited classes.
  • Is Polymorphism possible without inheritance?
Yes, polymorphism is the construction of a single interface to several types of objects, for instance, a single function call that can receive different classes or data types as arguments. They can be inherited or not.

Is polymorphism possible without inheritance?

Types of Polymorphism

Cardelli defines several types of polymorphism in this article:
  • Universal
    • parametric
    • inclusion
  • Ad-hoc
    • overloading
    • coercion 
    [ This subtyping feature in Java is achieved, through the inheritance of classes and interfaces. Although the subtyping features of Java may not be evident in terms of inheritance all the time.
Cases of polymorphism :-

1.) Cases of covariance and contravariance with generics.
2.) Arrays are Serializable and Cloneable although this is not evident anywhere in the type hierarchy.
3.) Concatenation of strings and numbers or of a string plus some other object. Consider also the cases of boxing and unboxing of primitives.
4.) cases of polymorphism (coercion and overloading) are not at all related to inheritance.

 Examples

Inclusion
 
List<Integer> myInts = new ArrayList<Integer>();


And in other cases, the relationships are not even evident in the API
Cloneable clone = new int[10];
Serializable obj = new Object[10]
 

Parametric

The same algorithm can be used to filter all kinds of lists with all kinds of predicates without having to repeat a single line of code for every possible type of list. 

double sum = 1 + 2.0;
Integer and floating-point arithmetic are totally different. Applying the plus operator to two operands of different types here is impossible without some form of coercion.

The best explanation on the subject that I've ever read is an article by Luca Cardelli, a renown type theorist. The article is named On Understanding Types, Data Abstraction, and Polymorphism.

Types of Polymorphism

Cardelli defines several types of polymorphism in this article:
  • Universal
    • parametric
    • inclusion
  • Ad-hoc
    • overloading
    • coercion
The kind of polymorphism related to inheritance is classified as inclusion polymorphism or subtype polymorphism.
Wikipedia provides a good definition:
In object-oriented programming, subtype polymorphism or inclusion polymorphism is a concept in type theory wherein a name may denote instances of many different classes as long as they are related by some common super class. Inclusion polymorphism is generally supported through subtyping, i.e., objects of different types are entirely substitutable for objects of another type (their base type(s)) and thus can be handled via a common interface. Alternatively, inclusion polymorphism may be achieved through type coercion, also known as type casting.
Another Wikipedia article called Polymorphism in object-oriented programming seems to answer your questions as well.

In Java

This subtyping feature in Java is achieved, among other means, through the inheritance of classes and interfaces. Although the subtyping features of Java may not be evident in terms of inheritance all the time. Take for example the cases of covariance and contravariance with generics. Also, arrays are Serializable and Cloneable although this is not evident anywhere in the type hierarchy. It can also be said that through primitive widening conversion the numeric operators in Java are polymorphic, in certain cases even accepting totally unrelated operands (i.e. concatenation of strings and numbers or of a string plus some other object). Consider also the cases of boxing and unboxing of primitives. These latter cases of polymorphism (coercion and overloading) are not at all related to inheritance.

Examples

Inclusion
List<Integer> myInts = new ArrayList<Integer>();
This is the case to which your question seems to refer i.e. when there is an inheritance or implementation relationship between the types, as in this case where ArrayList implements List.
As I mentioned, though, when you introduce Java generics, some time the rules of subtyping get fuzzy:
List<? super Number> myObjs = new ArrayList<Object>();
List<? extends Number> myNumbers = new LinkedList<Integer>();
And in other cases, the relationships are not even evident in the API
Cloneable clone = new int[10];
Serializable obj = new Object[10]
Even so, all these, according to Cardelli, are forms of universal polymorphism.
Parametric
public <T> List<T> filter(Predicate<T> predicate, List<T> source) {
  List<T> result = new ArrayList<>();
  for(T item : source) {
    if(predicate.evaluate(item)){
         result.add(item);
    }
   return result;
  }
}
The same algorithm can be used to filter all kinds of lists with all kinds of predicates without having to repeat a single line of code for every possible type of list. The type of the actual list and the type of predicate are parametric. See this example with lambda expressions available in JDK 8 Preview (for the brevity of predicate implementation).
filter(x -> x % 2 == 0, asList(1,2,3,4,5,6)); //filters even integers
filter(x -> x % 2 != 0, asList(1L,2L,3L,4L,5L,6L)); //filters odd longs
filter(x -> x >= 0.0, asList(-1.0, 1.0)); //filters positive doubles
According to Cardelli, this is a form of universal polymorphism.
Coercion
double sum = 1 + 2.0;
Integer and floating-point arithmetic are totally different. Applying the plus operator to two operands of different types here is impossible without some form of coercion.
In this example, the types integer and double, are automatically coerced (converted) to type double without an explicit cast. The entire expression is promoted to double. This is so because in Java we have primitive widening conversions.
According to Cardelli, this form of automatic coercion is a form of ad-hoc polymorphism provided for the plus operator.
There are languages in which you could not even sum an integer and a floating-point number without an explicit cast (i.e. AFAIK, SML, in which, by the way, parametric polymorphism is key to overcome this kind of problems).
Overloading
double sum = 2.0 + 3.0;
String text = "The sum is" + sum;
The plus operator here means two different things depending on the arguments used. Evidently, the operator has been overloaded. This implies it has different implementations depending on the types of operands. According to Cardelli, this is a form of ad-hoc polymorphism provided for the plus operator.

 



What is the purpose of polymorphism?

Polymorphism. Generally, the ability to appear in many forms. In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes.
 

IMPORTANT POINTS ABOUT POLYMORPHISM

  •  A functionality can behave differently for different instances
  • The behavior depends on the type of data used in the operation
  • Polymorphism is used for implementing inheritance.

ADVANTAGES OF POLYMORPHISM

  • It helps programmers reuse the code and classes once written, tested and implemented. They can be reused in many ways.
  • Single variable name can be used to store variables of multiple data types(Float, double, Long, Int etc).
  • Polymorphism helps in reducing the coupling between different functionalities.
 [ A car is polymorphic because you can send commonly understood messages to ANY car (start(), accelerate(), turnLeft(), turnRight(), etc) without knowing WHO built the car. A light switch is polymorphic because you can send the message turnOn() and turnOff() to any light switch without knowing who manufactured it. ]


Type Conversion of data Type

Assigning a value of one type to a variable of another type is known as Type Casting. If the data types are compatible, then Java will perform the conversion automatically known as Automatic Type Conversion and if not then they need to be casted or converted explicitly.
Example :
int x = 10;
byte y = (byte)x;
In Java, type casting is classified into two types,
  • Widening Casting(Implicit)
  • widening-type-conversion
  • Narrowing Casting(Explicitly done)
  • narrowing-type-conversion 


Widening or Automatic type converion

Automatic Type casting take place when,
  • the two types are compatible
  • the target type is larger than the source type
Example :
public class Test
{
    public static void main(String[] args)
    {
      int i = 100;
      long l = i; //no explicit type casting required
      float f = l; //no explicit type casting required
      System.out.println("Int value "+i);
      System.out.println("Long value "+l);
      System.out.println("Float value "+f);
    }

}
 
O/P :- 
Int value 100 
Long value 100 
Float value 100.0 


Narrowing or Explicit type conversion

When you are assigning a larger type value to a variable of smaller type, then you need to perform explicit type casting.
Example :
public class Test
{
    public static void main(String[] args)
    {
      double d = 100.04;
      long l = (long)d;  //explicit type casting required
      int i = (int)l; //explicit type casting required

      System.out.println("Double value "+d);
      System.out.println("Long value "+l);
      System.out.println("Int value "+i);
    }

}
 
O/P : 
Double value 100.04 
Long value 100 
Int value 100

Tuesday, January 8, 2019

Can be call this() and supper() togther in same method and constructure ?

There is a difference between super() and this().
super()- calls the base class constructor whereas
this()- calls current class constructor.
Both this() and super() are constructor calls.
Constructor call must always be the first statement. So we can not have two statements as first statement, hence either we can call super() or we can call this() from the constructor, but not both.
 Example :-
class TempB {
    TempB() // default constructor
    {
        System.out.println("default constructor");
    }

    TempB(int x) // one parameter constructor
    {
        System.out.println("value of x is" + x);
    }
}

class C extends TempA {
    C() // default constructor
    {
        super();
        this(10);
        System.out.println("default constructor");
    }

    C(int x) // one parameter constructor
    {
        this(10, 20);
        System.out.println("value of x is" + x);
    }

    C(int x, int y) // two parameter constructor
    {
        System.out.println("Add result is" + (x + y));
    }

    public static void main(String[] args) {
        new C();
    }


In above example first statement is correct whare use supper() but after use this. It is not correct because it break the contract of calling first statement.
 

Difference Between Constructor Overloading and Constructor Chaining?

Constructor Overloading
Constructor Chaining
1. Constructor overloading allows a class to have more than one constructor that have the same name as that of the class but differ only in terms of number or type of parameters. 1. Constructor chaining is a process of calling the one constructor from another constructor with respect to current object.
2. Constructor overloading is done to construct object in different ways. 2. Constructor chaining is done to call one constructor from another constructor.
3. Constructor overloading is achieved by declaring more than one constructor with same name but different parameters in a same class. 3. Constructor chaining is achieved by this() method.
4. Constructor overloading is flexible which allows us to create object in different way. 4. Constructor chaining is useful when we have many constructors in the class and want to reuse that constructor.

What is the need of Constructor chaining in java?

  • Calling a constructor from another constructor , is known as constructor chaining.If we want to access the properties of any constructor then we have to use constructor chaining.
  • We know that constructor is neither static nor non static. So we can’t inherit the constructor.But using constructor chaining we can acquire the properties of another constructor.
  • There is two ways to achieve the constructor chaining:-
1.) super() (call to super) is used to call the super class constructor. That mean sub class is able to access the properties of constructor which are present in super class. For accessing the super class constructor properties inheritance is must.
2.) this() (call to this) is used to call the same class constructor. That mean we can achieve the properties of constructor which are present in the same class. For using this() constructor overloading is necessary. Without constructor overloading we can’t get the properties of same class.

Examples :-

Step 1.)

class Temp
{
  Temp()  //default constructor
  {
    this(10);
    System.out.println("default constructor");
  }
  Temp(int x)  //one parameter constructor
  {
    this(10,20);
    System.out.println("value of x is" +x);
  }
  Temp(int x,int y)  //two parameter constructor
  {
    System.out.println("Add result is" +(x+y));
  }
  public static void main(String[] args)
  {
    new Temp();
  }
}
 
Explanation of Program:
  • The class Temp contains three constructors: default constructor, one parameter constructor and two parameter constructor.
  • The statement : new Temp(); calls a default constructor. Here it calls the one parameter constructor with the help of this(10);
  • Then control goes to two parameter constructor with the help of first statement in constructor this(10,20),
  • In two parameter constructor the first statement will be executed which prints the “add result is 30”
  • Then control goes to one parameter constructor and it executes the second statement which prints “value of x is 10”
  • Then control goes to default constructor and it also execute the second statement that prints “default constructor”

 Important Points to Remember About Constructor Chaining:

  • Whenever you are achieving a constructor chaining using a this() method then it must be the first line in any constructor.
  • Whenever we are achieving a constructor chaining using a this() method then there must be atleast one constructor which is not having a this() method as a first line.
  • Constructor chaining can be achieved in any order.
  • Whenever you want to provide the certain common resources to each object of a class rather than putting the code of each resource in a single constructor, make a separate constructor for each resource and then create their chain.