Wednesday, 3 September 2014

Java : Call main method before JVM Call

Static blocks are also called Static initialization blocks . A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:
 
static {
// whatever code is needed for initialization goes here
}

 
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code. 
 
And dont forget, this code will be executed when JVM loads the class. JVM combines all these blocks into one single static block and then executes. Here are a couple of points I like to mention:

public class Test {

    static {
        Test.main("From static Block");
    }


    public static void main(String... args) {
        if (args.length > 0) {
            System.out.println(args[0]);
        } else {
            System.out.println("By JVM");
        }
    }
}

Monday, 1 September 2014

Java Puzzel : OutOfMemory

Try compiling and running the code below - then uncomment for loop compile and run.
Why does this program have an error when for loop is commented out?

Monday, 25 August 2014

Valid main method signature

public static void main(String[] argument)
public static void main(String argument[])
public static void main(String... args)
public static synchronized void main(String... args)
public static strictfp void main(String... args)
public static final void main(String... args)

Q: Can main method throw Exception in Java?
A: indeed main method can throw Exception both checked and unchecked.

Q: Can main method be overloaded in java?
A: Yes main method in java can be overloaded but JVM will only invoke main method with standard signature.

Q: Can main method be overridden in java?
A: Yes main method in java can be overridden and the class you passed to java command will be used to call main method.

Thursday, 7 August 2014

Difference between java.lang.NoClassDefFoundError and ClassNotFoundException in Java


Exception in thread "main" java.lang.NoClassDefFoundError

  •  ClassNotFoundException
    • Many a times we confused ourselves with java.lang.ClassNotFoundException and java.lang.NoClassDefFoundError, though both of them related to Java Classpath they are completely different to each other. 
    • ClassNotFoundException comes when JVM tries to load a class at runtime dynamically means you give the name of class at runtime and then JVM tries to load it and if that class is not found in classpath it throws java.lang.ClassNotFoundException.
  •  NoClassDefFoundError
    •  While in case of NoClassDefFoundError the problematic class was present during Compile time and that's why program was successfully compile but not available during runtime by any reason. 
    • NoClassDefFoundError is easier to solve than ClassNotFoundException in my opinion because here we know that Class was present during build time but it totally depends upon environment.
    •  If you are working in J2EE environment than you can get NoClassDefFoundError even if class is present because it may not be visible to corresponding ClassLoader. 


Thursday, 24 July 2014

What is a reasonable order of Java modifiers (abstract, final, public, static, etc.)?

It is reasonable to use the order according to the Java Virtual Machine Specification, Table 4.4
  • public           
  • protected
  • private
  • abstract
  • static
  • final
  • transient
  • volatile
  • synchronized
  • native
  • strictfp

Can you override Static Methods in Java?

  • Well... the answer is NO if you think from the perspective of how an overriden method should behave in Java. But, you don't get any compiler error if you try to override a static method. That means, if you try to override, Java doesn't stop you doing that; but you certainly don't get the same effect as you get for non-static methods.
  •  Overriding in Java simply means that the particular method would be called based on the run time type of the object and not on the compile time type of it (which is the case with overridden static methods).
  •  Okay... any guesses for the reason why do they behave strangely? Because they are class methods and hence access to them is always resolved during compile time only using the compile time type information. 
  • Accessing them using object references is just an extra liberty given by the designers of Java and we should certainly not think of stopping that practice only when they restrict it :-)

Example: let's try to see what happens if we try overriding a static method:-

class SuperClass{
......
public static void staticMethod(){
System.out.println("SuperClass: inside staticMethod");
}
......
}

public class SubClass extends SuperClass{

......
//overriding the static method
public static void staticMethod(){
System.out.println("SubClass: inside staticMethod");
}

......

public static void main(String []args){
......
SuperClass superClassWithSuperCons = new SuperClass();
SuperClass superClassWithSubCons = new SubClass();
SubClass subClassWithSubCons = new SubClass();

superClassWithSuperCons.staticMethod();

superClassWithSubCons.staticMethod();
subClassWithSubCons.staticMethod();
...
}

}


Output:-

SuperClass: inside staticMethod
SuperClass: inside staticMethod
SubClass: inside staticMethod

  • Notice the second line of the output. Had the staticMethod been overriden this line should have been identical to the third line as we're invoking the 'staticMethod()' on an object of Runtime Type as 'SubClass' and not as 'SuperClass'. 
  • This confirms that the static methods are always resolved using their compile time type information only.

Tuesday, 15 July 2014

Difference between string object and string literal

When you do this:

String str = "abc";

You are calling the intern() method on String. This method references an internal pool of 'String' objects. If the String you called intern() on already resides in the pool, then a reference to that String is assigned to str. If not, then the new String is placed in the pool, and a reference to it is then assigned to str.

Given the following code:

String str = "abc";
String str2 = "abc";
boolean identity = str == str2;

When you check for object identity by doing == (you are literally asking - do these two references point to the same object?), you get true.

However, you don't need to intern() Strings. You can force the creation on a new Object on the Heap by doing this:

String str = new String("abc");
String str2 = new String("abc");
boolean identity = str == str2;

In this instance, str and str2 are references to different Objects, neither of which have been interned so that when you test for Object identity using ==, you will get false.

In terms of good coding practice - do not use == to check for String equality, use .equals() instead.