Java puzzle - Set 2

In java puzzle series,I am discussing interesting and intriguing concept of java. It will include some interview questions and MCQ.
Disclaimer : I do not claim that contents available here are my own , it's compiled by me after reading various pages on internet to make others life easy. :) Happy learning!!
Question 1:  Predict the output 
public class  IntegerCacheClass {  
     public static void main(String[] arg) {
        Integer one = 123;
        Integer ONE = 123;
        Integer two = 256;
        Integer TWO = 256;
        Integer one_ = new Integer(123);
        System.out.println(one == ONE);
        System.out.println(two == TWO);    
        System.out.println(one_== ONE);
 }
}
Sample output:
  true
  false
  false
ExplanationDo you know Integer class maintains a cache of size 256 values (from -128 to 127) by default. The basic assumption is that, these small values occur much more often than other ints and therefore it makes sense to avoid the overhead of having different objects for every instance (an Integer object takes up something like 12 bytes).This cache is initialized on first usage. As per Java language specification (JLS) : the size of the cache may be controlled by the XX:AutoBoxCacheMax=<size> option. Note that it sets only high value, low value is always -128. This feature was introduced in 1.6. A side note is that the cache is contained in a static class which will not be instantiated until the first time it is needed, so if valueOf() is never called, the cache is never created. And conversely, the first time it's called, it will really create 256 objects.
In our problem, "Integer one = 123" and Integer ONE = 123, perform autoboxing and invokes the static method Integer.valueOf(). Since valueOf() method returns same object if it is in range of -128 to 127. so both are referring to same Integer object and first SOP prints true.
However,  for "Integer two= 256", new object is created so as for "Integer TWO= 256", since it is not in the range of cache.so, the second output is false.
Now see closely, new Integer(123) will create a object at heap memory location, so it is entirely different from "one", so it prints false.
Question 2 : What will be outcome of this ?
public class ForloopTrap {
    public static void main(String[] arg) {
     int count = 0;
     for (int i = 0; i < 100; i++); {
       count++;
      }
     System.out.println(count);
    }
}
Sample output: If your output is 100 then it absolutely wrong!! You did not read question carefully.(Hint: Watch-out semicolon ";" in for loop. Hope you spotted the error. Correct answer is : 1
Question 3 :  ? Do you know put and get method of HashMap ? Yes!. The try this question.
class HashMapPutGet{
    public static void main(String[] arg) {
        HashMap <Integer,String>  map = new HashMap <>();
        String value1 = map.put(1,"one");
        String value2 = map.put(2,"Two");
        String value3 = map.put(1,"AgainOne");
        String value4 = map.put(2,"AgainTwo");
        System.out.println(value1+ " " +value3);
 }
}
Sample output : null one
Explanation : As per javadoc, put(K,V) of HashMap returns the previous value associated with key, or null if there was no mapping for key. If we apply this logic here, we find that on first insert null will be returned, since map is empty just before this insert, so value1 will be null.Similarly, on third insert key value is 1 and it is already there in HashMap so corresponding value "one" will be returned and stored in value3.
Question 4 : Again, we have a HashMap problem. Predict the outcome ? 
class TryHashMap{
    public static void main(String[] args) {
         HashMap <String,String> map = new HashMap<>();
         map.put(null, "Zero");
         System.out.println(map.put(null, "Found")== null ? 
                              map.get(null): "Not Found");
    }
 }
Sample Output: Not Found
Explanation: Since map.put(null, "Found") will return "Zero" since it is already in map, so the comparison with returns false, and ternary operator returns "Not Found".
Question 5 : What will be outcome of below program unit ? 
public class LowercaseHurts {

 /**
  * devinline.com
  */
 public static void main(String[] args) {
  System.out.println(12345 + 5432l);
 }

}
Sample Output:- 17777
If you watch closely, 12345 is added to a long number 5432 not 54321.(As class name tells,lowercase hurts. Instead of l we should always use L for indicating long type of a number.(Reference : Java Puzzlers)

1 Comments

Previous Post Next Post