Java puzzle - Set 0

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!!

Class and object initialization's are the most fundamental concept in java  and every java developer must have a clear understanding of that.Here we will discuss these concepts based on questions. Please read this article for better understanding of class and object initialization.
Question 1 : what will be the output of the following sample code? 
class ClassInitSample
{
   static boolean b;
   static char c;
   static char ca = '\u0000';
   public static void main (String [] args)
   {
      System.out.println ("b = " + b);
      System.out.println ("c = " + c);
      System.out.println ("c = " + (c == ca));
   }
} 
Answer : Sample output is as follows, if you arrive at this then you can next question.
 false
  
 true
First "false" is obvious as it is default value for boolean type. Why empty place for second SOP(System.out.println()) statement ? Reason : In java  char is represented by 16 bit unicode and default value of char is '/u0000' and the most important thing is that JVM interprets '\u0000' as the nondisplayable null value that's why, SOP executes but display nothing.Third SOP will be obviously true as (c=='\u0000').
Question 2: Do you think it will give compile time error ? (Hint:ClassName tells the story)
class ForwardRefNotAllowed
{
   static int one = two + 2;
   static int two = 2;
   public static void main (String [] args)
   {
      System.out.println ("first = " + one);
   }
}
Solution: If your answer is Yes, then your are on right track.But, what makes compilation failure ? In java forward reference is not allowed. Compiler reports error( illegal forward reference) because compiler cannot decide whether default value of two (which is 0) should be used or assigned value 2 should be used.
Question 3: Do you know what is class block initializer and object block initializer. Then try this question and predict the output?
class ClassBlockInitialization
{ 
  public ClassBlockInitialization(){
  System.out.println("Creating a new instance of 
                              ClassBlockInitialization");
  }
  //I am an class block initializer
  static
   {
     System.out.println ("Loading JDBC driver.....");
   }
  //I am an object block initializer 
   {
     System.out.println("I will be available for each object");
   }
  public static void main (String [] args){
      ClassBlockInitialization t1 = new ClassBlockInitialization();
      ClassBlockInitialization t2 = new ClassBlockInitialization();   
  }
}
Solution: If you have observed carefully, comments in sample code tells whole story.Here is the sample output, check it Did you arrived at this ?
 Loading JDBC driver.....
 I will be available for each object
 Creating a new instance of ClassBlockInitialization
 I will be available for each object
 Creating a new instance of ClassBlockInitialization
The fundamental difference between class block initializer and object block initializer is that :
class block initializer is executed only once right after class is loaded in JVM or just before main() method execution if it is an "initial class".
object block initializer is executed for each object creation, before executing constructor of the class.
Now come back to our question, on class loading class block got executed and display "Loading JDBC driver....." and when first object referenced by t1 is created, first object block got executed and then its's constructor is being called, so first "I will be available for each object" displayed followed by "Creating a new instance of ClassBlockInitialization". Similarly for second object creation it;s got repeated.
Question 4: How does class initialization work in the context of a class hierarchy? Try this and predict the output. (Hint: Always show respect to your parents - parent first always)
class ParentClass
{
   static int a = 1;
   static
   {
      System.out.println ("Parent initializer and " + "a = " + a);
   }
}
class ChildClass extends ParentClass
{
   static int b = 2 + a;
   static
   {
      System.out.println ("Child initializer and" + "b = " + b);
   }
   public static void main (String [] args)
   {
   }
}
Solution: Here is the sample output, is it what you predicted.
 Parent initializer a = 1
 Child initializer b = 3
As hint in the question states parents first: when a class hierarchy is involved then at runtime, the JVM loads all hierarchy classes from top to bottom(parenet class first- it will be propagated to the parent's of all class : Object class) and execute class field /class block initializer in same fashion(First parent class field and class block initializer then child's) and it will boil down to the class where main() method is available. In this question , first ParentClass is loaded and its field and class block got initialized, after that child class field and class block is executed.(Did you notice one thing b = 2+ a,  a= 1 is available since a is part of parent class which got initialized before).Now we can reach at the sample outcome as stated at top.
Question 5: Do you understand visibility of fields in class(Declaration and initialization) and its accessibility. What will the output of this program ?
public class VisiblityOfFields {
  int localVariable;
  static double PI;
  static
  {
     PI = 3.14159;
  }
  {
     int localVariable = 1;
     System.out.println("localVariable is "+ localVariable);
     System.out.println("Class field initialized, PI is "+ PI);
  }
  public VisiblityOfFields() {
     System.out.println("Initializing object, localVariable is "+ 
                                                 localVariable);
     System.out.println("Class field initialized, PI is "+ PI);
  }
  public static void main (String [] args){
          VisiblityOfFields vof = new VisiblityOfFields ();
  }
}
Solution: Here is the sample output:
 localVariable is 1
 Class field initialized, PI is 3.14159
 Initializing object, localVariable is 0
 Class field initialized, PI is 3.14159
Here we have to recall two fundamental's of class and object initialization discussed earlier :
First, Once class is loaded by class loader in JVM, before main() method execution class block gets executed and PI is initialized with 3.14159.
Second, for each object, the object block initializer executes before the constructor.Now once new object is created control reaches to object block section where localVariable is declared and initialized with value 1 (Please pay attention: declared and initialized not just initialized) and its SOP's displays as expected. Now, when constructor of VisiblityOfFields class is executed object field "localVariable" is initialized with default value  of 0(default value for int is 0) while PI remains unaffected (It is class fields), that's why in constructor SOP's we get 0 for localVariable and 3.14159 for PI.
One important take away from this question is : Any variable that you declare in a class block/object block initializer is local to that block.
This is all about fundamental of class and object initialization and hope after reading got insight of the same.
                        ==============End of article============

Happy learning,
Nikhil

1 Comments

Previous Post Next Post