Monday, November 30, 2015

Internal representation of valueOf() in Java

                                        Internal representation of valueOf() in Java

public class ValueOf {

     public static void main(String[] args) {
           /*Integer i1 = 127;
           Integer i2 = 127; Equivalent to
           */
          Integer i1 = Integer.valueOf(127);
           Integer i2 = Integer.valueOf(127);
           System.out.println(i1 == i2);
           /*Integer i3 = 128;
           Integer i4 = 128; Equivalent to
           */
           Integer i3 = Integer.valueOf(128);
           Integer i4 = Integer.valueOf(128);

           System.out.println(i3 == i4);
     }
}
Output:

true
false

Integer.ValueOf() method creates the java.lang.Integer object by passing the specified ‘int‘ value. Actually, it doesn’t create the new objects for all the values you pass. This method is implemented such that the frequently used values are cached. I.e. internally it maintains an array of Integer objects where Integer objects for frequently requested values are created and stored at the time of VM initialization itself.

By default, these values will be from -128 to 127. So, for any number you pass between -128 and 127 (inclusive), it doesn’t create the new Integer object. Instead it returns already cached object from the array. If you pass the number beyond this range, then only it creates a new Integer object. Below is the source code ofInteger.valueOf() method.




public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

From the above code, it is clear that Integer.valueOf() method doesn’t create new Integer objects for the values between IntegerCache.low and IntegerCache.high. Instead it returns the already cached object representing that value from IntegerCache.cache array. By default, IntegerCache.low = -128and  IntegerCache.high = 127. If you pass the values beyond this range, then only it creates new Integer object.
IntegerCache Class :

IntegerCache
 is the private static inner class of java.lang.Integer class. This is the class which handles the caching of all frequently requested values. Have a look at the source code of IntegerCache class.



private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];

    static {
        // high value may be configured by property
        int h = 127;
        String integerCacheHighPropValue =
            sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            try {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
            } catch( NumberFormatException nfe) {
                // If the property cannot be parsed into an int, ignore it.
            }
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);

        // range [-128, 127] must be interned (JLS7 5.1.7)
        assert IntegerCache.high >= 127;
    }

    private IntegerCache() {}
}


You can notice that low is always set to -128 (Line 2). high gets the value from the property set in sun.misc.VM class (Line 10). That means you can change the upper limit of the range. 
If it is not set it gets the default value 127 (Line 21). cache is an Integer array where all the cached objects are stored. You observe from line 23 to line 26, it is where all Integer objects are created for the values from low to high and stored in cache array.

Java Tricky Output Questions and Concepts

Java Tricky Output Questions and Concepts:

1) Static Method

public class Test {
       public static void show() {
              System.out.println("Static method called");
       }
       public static void main(String[] args) {
              Test obj = null;
              obj.show();
       }
}
Output:

Static method called

We can call static methods using reference variable which is pointing to null because static methods are class level so we can either call using class name and reference variable which is pointing to null.

2) Static block

public class Test {               
               static int a = 1111;
               {  
                      a = a-- - --a;
               }
               {
                      a = a++ + ++a;
               }
               
               public static void main(String[] args)  {
                          System.out.println(a);    
                  }
              }

Output:
2

Static block initializes and change a to 2. Simple block scope won’t affect the value of a

3) Compilers not able to understand which overloaded method to call...

public class Test {
       public static void main(String[] args) {
              Integer i = new Integer(null);
              String s = new String(null);
       }
}

public class Test {
           public static void main(String[] args) {
            System.out.println(null);
           }
}

Output :
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
 The constructor String(String) is ambiguous

 at com.staticMethod.Test.main(Test.java:15)

Explanation :

Suppose you have two overloaded methods, like this:
public void method(Object o) {
    // ...
}

public void method(String s) {
    // ...
}

When you call method(null), both these methods apply. Java chooses the most specific one, which is in this case the second method, that takes a String - because String is a more specific type than Object.
However, sometimes the most specific constructor or method cannot be determined. If we look at the constructors of class String that take one argument:

String(byte[] bytes)
String(char[] value)
String(String original)
String(StringBuffer buffer)
String(StringBuilder builder)
Note that there is no hierarchy between the types byte[]char[]StringStringBuffer and StringBuilder, so it's not possible to say that one of these constructors is more specific than the others. So, the Java compiler doesn't know which constructor to choose and will give you an error.

4) Wrapper Class

public class StringEquals {
         
          private Integer integer;
          public static void main(String[] args) {
                   StringEquals st = new StringEquals();
                   System.out.println(st.getInteger());
          }

          public int getInteger() {
                   return integer;
          }
}


Output :

Exception in thread "main" java.lang.NullPointerException

          at com.tutorials.string.StringEquals.getInteger(StringEquals.java:12)

Static(Class) Methods & Instance(Non-static) methods

Following are some important points for method overriding and static methods in Java.

1) For class (or static) methods, the method according to the type of reference is called, not according to the object being referred, which means method call is decided at compile time.

class A
{
    public static void  X()
  {
          Y();
  }
  public static void Y()
  {
        System.out.println("parent");
  }
}

public class B extends A
{
        public static void Y()
        {
                System.out.println("Child");
        }
        public static void main(String[] args) {
                new A().Y();
           }
}

Output:
parent


2) For instance (or non-static) methods, the method is called according to the type of object being referred, not according to the type of reference, which means method calls is decided at run time.

3) An instance method cannot override a static method, and a static method cannot hide an instance method.

4) In a subclass (or Derived Class), we can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass methods — they are new methods, unique to the subclass.

2) Can we override static methods in java? What is method hiding in Java? What is the output of below program?
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Parent{
 public static void print(){
  System.out.println("I am Parent");
 }
}

class Child extends Parent{
 public static void print(){
  System.out.println("I am Child");
 }
}

public class MainClass {
 public static void main(String args[]) {
  Parent parent = new Parent();
  parent.print();
   
  parent = new Child();
  parent.print();
   
  Child child = new Child();
  child.print();
 }
}

Output : 
I am Parent 
I am Parent 
I am Child

Explanation:

No. Static methods cannot be overridden. 

Static methods are not polymorphic and don’t take part in runtime or dynamic polymorphism and the decision as to which method will be called is resolved at compile-time based on the type alone.

We can declare static methods with the same signature in the subclass, but it is not considered as overriding because there won’t be any run-time or dynamic polymorphism.
If a derived class defines a static method with the same signature as a static method in base class, the method in the derived class hides the method in the base class.

 
even if caller writes like,  
Parent parent = new Parent();  
parent.print(); 

Compiler at compile time will change above line to Parent.print() because static methods need to be called in a static way and is not associated with any instance.

Parent parent = new Child();  
parent.print();

Above line would have printed "I am Child" if static methods are polymorphic.
So internally what it does is, Compiler checks whether print() method is static, if yes, then it replace the instance to instance type.
the parent object is of type Parent, so it replaces it to,
Parent.print();