Monday 13 February 2012

Java - Static Initializer,Constructor Initailizer and Constructor Blocks

Often when there are static initializer,constructor initializers and  constructor blocks are there , programmer finds it hard to find the flow as which block will execute first when the program is run.

I will try to look into the details of this and try to look into the reason for the same.
Here is the sample code :-

   class Parent
   { 
       static
       { 
            System.out.println("Parent Static Initializer Block");
       }
       { 
            System.out.println("Parent Constructor Initialization Block");
       }
       Parent()
       { 
           System.out.println("Parent Constructor"); 
       } 
   } 
     
   class Child extends Parent
   { 
       static
       { 
         System.out.println("Child Static Initializer Block"); 
       }
      
       { 
           System.out.println("Child Constructor Initialization Block");  
       }
      
       Child()
       { 
         System.out.println("Child Constructor"); 
       } 
   }
   class Temp
   { 
       static
       { 
         System.out.println("Temp Static Initializer Block"); 
       }
      
       { 
           System.out.println("Temp Constructor Initialization Block");  
       }
      
       Temp()
       { 
         System.out.println("Temp Constructor"); 
       } 
   }
  
   class TestJava
   { 
       static
       { 
         System.out.println("TestJava Static Initializer Block"); 
       }
      
       { 
           System.out.println("TestJava Constructor Initialization Block");  
       }
     public static void main(String[] args)
     { 
       System.out.println("Inside Main"); 
       Child c = new Child(); 
     } 
   }


Output of above program is :-
TestJava Static Initializer Block
Inside Main
Parent Static Initializer Block
Child Static Initializer Block
Parent Constructor Initialization Block
Parent Constructor
Child Constructor Initialization Block
Child Constructor

Ohh..I was expecting main will execute first then static initializer of TestJava , then Parent class constructor and then child class constructor but its not like that.


Lets look into class loading,linking and initalization part -

"The Java virtual machine starts execution by invoking the main method of specified class and passing it a single argument, which is an array of strings.
This causes the specified class to be loaded , linked to other types that it uses, and initialized .
The method main must be declared public, static, and void. "
Ref (http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#19075)


Loading :- Loading involves the process of finding the binary form of a class , constructing object to represent this class from this binary form.ClassLoader and its subclasses performs loading operations.

Linking :- A class is loaded before it is linked. Linking is the process of combining binary form of a class to runtime environment of virtual machine.

Initialization :- Initialization involves executing static initializers and field initializers.
Static initializers are executed only once when class is initialized and field initializers executed
everytime new instance of class is created.

If we go back to our example, class TestJava is loaded first as it has main methods which makes entry point for JVM.Once it is loaded it will get linked and then initialized.
Upon initialization of class TestJava , static intializers will be executed so "TestJava Static Initializer Block" is printed.

No other static initializer blocks , so main method will print "Inside Main" .

Line Child c = new Child(); makes class loader to load Child class but since ClassLoader uses delegation model , Parent class will get loaded before Child class.

Once Parent class is laoded it's static initializer block will execute first so "Parent Static Initializer Block" gets printed.
 
In the same fashion Child class gets loaded and its static initializer block will execute which makes "Child Static Initializer Block" printed.

Constructor of Child class is invoked which in turn invokes parent class constructor.
But since constructor initialization blocks included in constructor at runtime it will execute first , so"Parent Constructor Initialization Block" will get printed followed by "Parent Constructor".

Once constructor of parent class is invoked, child class constructor will be invoked.So the order will be same as for Parent class "Child Constructor Initialization Block" followed by "Child Constructor".

Monday 30 January 2012

Java - Is Object class implicitly inherited ?

Java API includes description of Object class as "Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class."

So the question comes Is Object class implicitly inherited ? 
API docs didn't say anything on this, documentation says the Object class is the root of the class hierarchy and every class has Object as a superclass .
It doesn't mean that Object class is inherited by every class , instead the behaviour is provided by compiler to make every class is a child of Object class.

Lets understand through code sample - source code A.java
class A {
    public String toString(){
        return "class A";
    }
}
class B extends A {
     public String toString() {
            return "class B";
        }
}
class C extends B {
     public String toString(){
            return "class C";
        }
}
Here I haven't extended Object class and still override toString() method of Object class.So does it mean compiler makes Object class inherited by class A and put it in byte code? Ahh...Need to dig into byte code.
No worry , will find out that too.

Here is the byte code - A.class
class A {
  // Stack: 1, Locals: 1
  A();
    0  aload_0 [this]
    1  invokespecial java.lang.Object() [8]
   .........................


   ..........................  
public java.lang.String toString();
    0  ldc <String "class A"> [16]
    2  areturn
      Line numbers:
        [pc: 0, line: 3]
      Local variable table:
        [pc: 0, pc: 3] local: this index: 0 type: A
}


B.Class

class B extends A {
 
  // Method descriptor #6 ()V
  // Stack: 1, Locals: 1
  B();
    0  aload_0 [this]
    1  invokespecial A() [8]
...............................
...............................
...............................

C.class
class C extends B {
 
  // Method descriptor #6 ()V
  // Stack: 1, Locals: 1
  C();
    0  aload_0 [this]
    1  invokespecial B() [8]
..................................................
..................................................
Here , Compiler puts no-arg constructor by itself though I haven't included in source code. And there is no extends keyword in top most class A which says A extends Object , although there is a call to java.lang.Object() in A.class's byte code but it is a call to super class's constructor. very similar to what you can see in Class B and Class C    1  invokespecial A() [8] 
so the result is  compiler won't add extends Object for any class and hence technically Object class is not inherited automatcially on the other hand since Object class's non private members are available to child classes(which is by definition inheriting already developed behaviour from parent class ) it is quite evident  that Object class is inherited in Child class.

Does Object class break multiple inheritance ?
e.g. class A{ } class B extends A{ } , does it mean class B extends A , Object
No, reason Object class is the superclass in class hierarchy e.g. Object->A->B and not the direct superclass of all the classes.
So if Class A extends Object and Class B extends A , implicitly class B inheriting Class Object also.

Sunday 29 January 2012

What does System.out.println mean ?

What does System.out.println mean ? or How it is possible to say Class.object.method ?  


System: System is a class which provides facilities like standard input,output and error stream.Apart from this System is final so can't be inherited.Constructor of System class is private, so System class can't be instantiated.


public final class System {
   /** Don't let anyone instantiate this class */
    private System() {
    }
}


out : represents standard output stream which is already open to display output data.
out is an instance of PrintStream class defined as static member of System class.
Syntax is like :
public final class System {
public final static PrintStream out = nullPrintStream();
}


since PrintStream's instance is static member of class System , you can directly write System.out.


There is another way where you dont even have to write System.out.println instead you can write out.println,to know more please refer this link.


println : print the message and then terminate the line.
System.out.println("Hello");

Is static import automatic for java.lang package ?

java.lang package is imported automatically  in every java program but are static members of classes belong to the package java.lang is automatic ?
No, static import is not automatic and programmer has to provide explicit class and its member name in import statement.
e.g. 
public class JavaImportTest
{
public static void main(String ar[])
{
out.println("Hello");//compile time error , cannot be resolved
}

}   


import static java.lang.System.out;

public class JavaImportTest
{
public static void main(String ar[])
{
out.println("Hello");//compile and print Hello
}
}

Java - class import , package import and static import

Classes present in java.lang package like String,System,Exception etc. are automatically imported in java program so that Programmer don't need to mention explicit class path in program like java.lang.System.out.println("Hello") and compiler can resolve the class name from the specified packages and compile the source code.


Some of the facts about java imports are -
1.java.lang package imported automatically(though not statically) i.e. programmer don't need to write java.lang.System.out.println("Hello") in order to print message instead s/he can write System.out.println("Hello").


2.Classes belong to the same package doesn't require explicit import.


3.Compiler resolves the class name at compile time , so error like "cannot resolved to a type" ,"Cannot find a symbol" you will get at compile time when classes you are using are not imported in your program.


4.You can import individual class , or all classes belong to the package or static members of class in single import statement.
e.g.
import java.util.ArrayList;
import java.util.*;
import static java.lang.System.out;


5.import statement are in the form of package.subpackage.class or  package.subpackage.* or static package.subpackage.class.member.
e.g.java.util.List; //here java is package,util is subpackage and List is the class name


Now the question comes as what is the difference between import and static import ?
import statements imports class or classes within a package while static import which is a new feature in java 5 allows to import static members and functions of the class.


static import allows you to write less code and used when constants declared in another class need to be included in your program and where your class require to access static members of classes which can't be inherited or which are final.
e.g. Math class in java.lang package , Math class is final so you cannot inherit it , but static members can be imported using this new feature


import static java.lang.Math.PI;
public class JavaStaticImportTest
{
public static void main(String ar[])
{
System.out.println(getPiValue());
}
public static double getPiValue()
{
return PI;
}
}

Too much use of static import can pollute the source code and harmful for readability.


Does enmass class import impacts performance ?
Actually No , because classes are resolved at compile time , so it hardly matters when either one class or multiple classes compiled at compile time.However it improves readabilty and maintainability.
This again depends on individual developers perception, as for some java.util.List makes code more readable and for some java.util.* is much more readable.

Wednesday 25 January 2012

Java Primitives and Uncommon Behaviour

You are writing Java program and using primitives in it and suddenly got error like can not covert,type mismatch,out of range etc.This happen because sometimes primitives doesn't work in the way we assume and have their own set of rules as well as predefined limitations.Lets look into the details of each primitive types and understand the limitation  :-

1.byte : 1 byte, range -128 to 127(inclusive) , default value is 0.


2.short : 2 byte, range -32,768 to 32,767(inclusive) , default value is 0.

3. int : 4 byte , range -2,147,483,648 to 2,147,483,647 (inclusive) , default value is 0. int is a default data type for all operations like(+,-,/,*) , passing arguments to methods,Printing in system out.

4.long: 8 byte, range -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (inclusive) , default value is 0.


5. float: 4 byte , range 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative), default 0.0f.

6. double : 8 byte , range from 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative) , default  0.0d
7.char : 2 byte, 0 to 65,535 , default is '\u0000'
 
8. boolean : true or false , default is false.

Primitives behaviour :-


1. Unless specified any non decimal value in case of statements like assignment,method parameters and switch is considered as int datatype.
e.g.  byte b1=-128;short s=32767;long l=1234567890;

byte b3=10;
byteTest(b3+1); //Error , The method byteTest(byte) is not applicable for the argument int.
public void byteTest(byte x)
{

}
public void byteTest(int x)
{

}
//No Error.


2. Implicit type casting is performed only when there is assignment operation is involved.
    
    byte b1=-129; //Error , Type mismatch : cannot convert from int to byte
    Reason : byte can hold values in the range -128 to 127



   short s2=32768; //Error , Type mismatch : cannot convert from int to short
   Reason : short can hold values in the range -32,768 to 32,767

   short s3=-32768;  //No Error

   long l= 12345678901;//Error , though long can accomodate this value.
   Reason : int is out of range.



3. Arithmetic operators always returns an int, unless one of the operands is a long, float, double.   
     
    byte b9=10; //No Error , Implicitly int is typecasted to byte and 10 is in byte limit(-128 to 127)
    
    byte b10=20;
    byte b11=10+20; //No Error , Results an int , but implicit typecasting is done
    
    byte b12=(byte)(b9+b10);//Error , if not typecaseted explicitly.


    So what happened above , its fine when you say 10+20 and error when you say b10+b11 ?  
    Actually, when there are variables involved no implicit typecasting is performed. 
      
     long b9=10L;
     byte b10=20;

     byte b11=2L/2; //Error, Results a long , no implicit typecasting
     If there are two different data types in arithmetic operation , result will be the type of highest datatype among the operands.    


     b11=b9/b10;    //Error ,Results a long , explicit typecasting is required


4.Explicit type casting is required when passing int , float , long , double values to their lowest data types respectively.


values can be implicitly assigned in this fashion.
byte ->short -> int -> long -> float ->double





Saturday 21 January 2012

Why only java.lang package imported automatically?

Java.lang package provides classes that are fundamentally required by the Java programming language.Object,Class,Wrapper Classes,System classes,Runtime classes,String,Exception classes are imported automatically to perform basic behavior of Java Language.

Object class is the root of the class hierarchy, and Class, instances of which represent classes at run time.

It is required at run time that primitives be acted as Objects , so wrapper classes are included in it.

String and StringBuffer classes provide commonly used operations on character strings.


Classes ClassLoader, System, Process, Runtime provides "system operations" that manage the dynamic loading of classes, creation of external processes, host environment,garbage collection.

Exception and Error classes which are the child of Class Throwable represents objects which are thrown during error condition.


So, basic programming can be done using classes present in java.lang packages, that's why it is imported autmatically.

Reference : http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/package-summary.html