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

Is Java Platform Independent or Platform Dependent?

Platform independence means compile once run anywhere or Program compiled in Windows Platform can run in Unix,Solaris without making any changes to the program.

Java has both compiler and interpreter implemented by javac and java respectively.

javac compiles the java program and generate the .class file which is in byte code.
Windows:-
Test.java -> javac ->  Test.class file(byte code)

java interprets the byte code and execute it, byte code can be generated in any of the platform.
Unix:-
Test.class-> java -> Hello World

JVMs are different for different platforms but they contain the same algorithm to interpret the byte code and provide the same result across all the platforms. 



Wednesday, 18 January 2012

Why Java ?

When there are number of languages available and when technology changes every other day the question arise why we are still stick to Java ?

For me following points makes Java preferred One :-

1.In built memory management : The mysterious Garbage Collector takes care of all those memory management stuffs where as in other programming language Programmer has to write code for this.

2.Stack of APIs : APIs like Collections,Threads,File IO,Swing,etc are provided to minimize cumbersome tasks developer has to go through while developing an application.

3.Portability : Program written and compiled in Windows can be executed in Unix.

4.Multithreading Support.

5.Web based support : Servlet,JSP,Applet.

6.Distributed Applications : Socket Communications,RMI,EJB.

  
For you what makes you to write Java Programs ?

Why there is public static void main(String[] ar) ?


Lets look at what each of these keywords implies :-

public : main method can be accessed outside of the class TestMain
static  : main method can be accessed without creating instance of the class.
void   : main method doesn't return any value.
main   : entry point for Java Interpreter.



Now Lets look into the variant of main methods and how java respond to these :

1. Very simple main method , all valid signature
public class TestMain 
{
    public static void main(String[] args)
    {
        System.out.println("Test");
    }
}   
Result : Compiled and Run Sunccessfully






2. Java 5 Var Args method Signature

public static void main(String ...args)  {

}

Result : Compiled and Run Sunccessfully

3.Method argument name change
public class TestMain 
{
    public static void main(String[] str)
    {
        System.out.println("Test");
    }
}
Result : Compile and Run Successfully , Its not mandatory to follow same naming conventions as String[] args

4.Change in the name of main method to Main
public class TestMain 
{
    public static void Main(String[] str)
    {
        System.out.println("Test");
    }
}
Result :
Compile but Error at Run time- Exception in thread "main" java.lang.NoSuchMethodError: main
Remember Java is case sensitive.

5.Access specifies is changed from public to private
public class TestMain 
{
    private static void main(String[] str)
    {
        System.out.println("Test");
    }
}
Result: Compile but Error at Run time - Main method not public.

6.Static is removed from method signature
public class TestMain 
{
    public void main(String[] str)
    {
        System.out.println("Test");
    }
}
Result : Compile but Error at Run time- Exception in thread "main" java.lang.NoSuchMethodError: main
 
7.Return type is changed from void to int
public class TestMain 
{
    public static int main(String[] str)
    {
        System.out.println("Test");
        return 0;
    }
}
Result : Compile but Error at Run time- Exception in thread "main" java.lang.NoSuchMethodError: main

8.Method arguments are removed
public class TestMain 
{
    public static void main()
    {
        System.out.println("Test");
    }
}
Result : Compile but Error at Run time- Exception in thread "main" java.lang.NoSuchMethodError: main

9.main method and overloaded Main methods
public class TestMain 
{
    public static void main(String ar[])
    {
        System.out.println("Test main : main(entry) method");
        String str[]={"Hello"};
        TestMain.Main(ar);
        TestMain tm=new TestMain();
        tm.Main();
    }
    public static void Main(String ar[])
    {
        System.out.println("Test Main :Main(class) method");
    }
    public void Main()
    {
        System.out.println("Test Main:Main(Instance) method");
    }
}
Result :Compile and Run Successfully
Output :
Test main : main(entry) method
Test Main : Main(class) method
Test Main : Main(Instance) method
 
10. Class without main method
public class TestMain 
{
   
}
Result :Compile but Error at Run time - Exception in thread "main" java.lang.NoSuchMethodError: main

By looking into above variants its quite evident that Java wants the programmer to define one entry point (main method) with specified signatures , so that run time environment can load the class and then instantiate the Class after that.

Tuesday, 17 January 2012

Is Java Pure Object Oriented Language ?

Languages which support OOPS principle(Polymorphism,Inheritance,Encapsulation) and where all operations are performed with the help of Objects are considered to be a Pure OO Language.

Java Supports following :-

1.Polymorphism(Compile Time,Run Time).

2.Inheritance(Single,Multilevel,Multiple Interface Inheritance).

3.Encapsulation/Data Hiding.

4.Primitive Wrappers.

5.Abstraction.

Although above points make it to a good candidate to Pure Object Oriented Programming Language ,  Multiple Class Inheritance(Not supported in java) , Primitives (int,char,short,long etc) prevents it to become pure OO programming language.

How does Java find and load classes ?

Classes are loaded in java using the order defined below :-

1.Bootstrap class loader - Java platform specific classes like Object,System,String etc which are defined in rt.jar(inside jre/lib folder) are loaded first.
Bootstrap classes are found using the value of the bootstrap class path which is stored in the sun.boot.class.path system property.

2.Extension class loader - BootStrap class loader uses delegation model to load Extension Classes that use the Java Extension mechanism.
These are bundled as .jar files located in the extensions directory (jre/lib/ext).Extension class loader makes custom APIs available to all applications running on the Java platform.

3.Application class loader - application specfic classes developed by programmers and which do not take advantage of extension class loader are defined in Classpath.
Java Run time environment looks into classpath and loads the classes defined in it.

In order to find out how java finds classes and how does class loader work , lets look into the below cases :-

1. rt.jar is removed from jre/lib directory

Result :
Compile,but error at run time.
Error occurred during initialization of VM
java/lang/NoClassDefFoundError: java/lang/Object

public class TestClassLoading
{
    public static void main(String[] args)
    {
        String str="Hello";
        System.out.println(str);
       
    }
}

Observation : Java Run time environment tried to load the Object class first as it is a Top class of all classes , and since rt.jar is not present
in bootstrap path , we get the error in run time.



2. String Class is removed from jre/lib/rt.jar java.lang package
Result :
Compile,but error at run time.
Error occurred during initialization of VM
java/lang/NoClassDefFoundError: java/lang/String

public class TestClassLoading
{
    public static void main(String[] args)
    {
        String str="Hello";
        System.out.println(str);
       
    }
}
Observation : Java Run time environment has loaded the Object class and then tried to load the classes present in the Program , String class is referneced in main method
so though rt.jar is present in bootstrap path , it does not have String class, so we get the error at run time.


3.
A.ext folder is removed from jre/lib directory

Result :
Compiletime error.
sun.text.resources.FormatData_ar_AE can not be resolved.

B.ext folder is placed in jre/lib directory
Result :
Compiled ,and executed successfully

import sun.text.resources.FormatData_ar_AE;
public class TestClassLoading
{
    public static void main(String[] args)
    {
        String str="Hello";
        System.out.println(str);
       
    }
}
Observation : javac and java both follow the same path in order to find the class.