Wednesday 3 September 2014

Java : Externalizable vs Serializable

  • Externalizable is an interface that enables you to define custom rules and your own mechanism for serialization. Serializable defines standard protocol and provides out of the box serialization capabilities.
  • Externalizable extends Serializable.
  • Implement writeExternal and readExternal methods of the Externalizable interface and create your own contract / protocol for serialization.
  • Saving the state of the supertypes is responsibility of the implementing class.
  • You might have seen in my previouse article on how to customize the default implementation of Serializable. These two methods readExternal and writeExternal (Externalizable) supersedes this customized implementation of readObject and writeObject.
  • In object de-serialization (reconsturction) the public no-argument constructor is used to reconstruct the object. In case of Serializable, instead of using constructor, the object is re-consturcted using data read from ObjectInputStream.
  • The above point subsequently mandates that the Externalizable object must have a public no-argument constructor. In the case of Seriablizable it is not mandatory.
  • Behaviour of writeReplace and readResolve methods are same for both Serializable and Externalizable objects. writeReplace allows to nominate a replacement object to be written to the stream. readResolve method allows to designate a replacement object for the object just read from the stream.
  • In most real time scenarios, you can use Serializable and write your own custom implementation for serialization by providing readObject and writeObject.
You may need Externalizable,
  1. If you are not happy with the way java writes/reads objects from stream.
  2. Special handling for supertypes on object construction during serialization.

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.

Saturday 14 June 2014

When initialization occurs in an interface?


    • According to Java language specification, initialization of an interface consists of executing the initializers for fields declared in the interface. Before a class is initialized, its direct superclass must be initialized.
    • But interfaces implemented by the class need not be initialized. Similarly, the superinterfaces of an interface need not be initialized before the interface is initialized. Initialization of an interface does not, of itself, cause initialization of any of its superinterfaces.
    • Following is example for this :
    • The reference to J.i is to a field that is a compile-time constant; therefore, it does not cause I to be initialized. The reference to K.j is a reference to a field actually declared in interface J that is not a compile-time constant; this causes initialization of the fields of interface J, but not those of its superinterface I, nor those of interface K. Despite the fact that the name K is used to refer to field j of interface J, interface K is not initialized.
    • System.out.println(J.i); // The i variable is inherited from I but since it is a constant - you don't have to go through the whole process of initializing I, just reference it and get on with things.
    • System.out.println(K.j); // now this is more complicated. Since the variable holds something other than a constant, the first thing that we have to do is initialize J so that we can figure out what to DO to come up with the value of j.
    • Initializing interface J causes variable j to be initialized first: executing Test.out("j",3) which prints j=3, and setting the variable j to 3 (note the return type on the method). Now jj is initialized executing Test.out("jj",4) which prints jj=4 and sets the variable jj to 4.
    • Now that initialization is done we can evaluate and execute the println for K.j which prints the current value of j which is 3.

      An Array of Characters is Not a String

      • In the Java programming language, unlike C, an array of char is not a String, and neither a String nor an array of char is terminated by '\u0000' (the NULL character)
      • A String object is immutable, that is, its contents never change, while an array of char has mutable elements.
      • The method toCharArray in class String returns an array of characters containing the same character sequence as a String. The class StringBuffer implements useful methods on mutable arrays of characters.

      Array Store Exception

      For an array whose type is A[], where A is a reference type, an assignment to a component of the array is checked at run time to ensure that the value being assigned is assignable to the component.

      If the type of the value being assigned is not assignment-compatible with the component type, an ArrayStoreException is thrown.



      • The variable pa has type Point[] and the variable cpa has as its value a reference to an object of type ColoredPoint[]. 
      • A ColoredPoint can be assigned to a Point; therefore, the value of cpa can be assigned to pa.
      • A reference to this array pa, for example, testing whether pa[1] is null, will not result in a run-time type error. 
      • This is because the element of the array of type ColoredPoint[] is a ColoredPoint, and every ColoredPoint can stand in for a Point, since Point is the superclass of ColoredPoint.
      • On the other hand, an assignment to the array pa can result in a run-time error. At compile time, an assignment to an element of pa is checked to make sure that the value assigned is a Point. 
      • But since pa holds a reference to an array of ColoredPoint, the assignment is valid only if the type of the value assigned at run time is, more specifically, a ColoredPoint. 
      • The Java Virtual Machine checks for such a situation at run time to ensure that the assignment is valid; if not, an ArrayStoreException is thrown.

      Friday 30 May 2014

      Initialization of Fields in Interfaces

      Every declarator in a field declaration of an interface must have a variable initializer, or a compile-time error occurs.

      The initializer need not be a constant expression. It is a compile-time error if the initializer of an interface field uses the simple name of the same field or another field whose declaration occurs textually later in the same interface.

      It is a compile-time error if the keyword this or the keyword super  occurs in the initializer of an interface field, unless the occurrence is within the body of an anonymous class. At run time, the initializer is evaluated and the field assignment performed exactly once, when the interface is initialized.

      Note that interface fields that are constant variables  are initialized before other interface fields. This also applies to static fields that are constant variables in classes . Such fields will never be observed to have their default initial values , even by devious programs.

      Example : Forward Reference to a Field
      interface Test {
          float f = j;
           int j = 1;
           int k = k + 1;
      }

      This program causes two compile-time errors, because j is referred to in the initialization of f before j is declared, and because the initialization of k refers to k itself.

      Ambiguous Inherited Fields With Interface

      If two fields with the same name are inherited by an interface because, for example, two of its direct superinterfaces declare fields with that name, then a single ambiguous member results. Any use of this ambiguous member will result in a compile-time error. In the program:

      interface BaseColors {
           int RED = 1, GREEN = 2, BLUE = 4;
      }
      interface RainbowColors extends BaseColors {
          int YELLOW = 3, ORANGE = 5, INDIGO = 6, VIOLET = 7;
      }
      interface PrintColors extends BaseColors {
           int YELLOW = 8, CYAN = 16, MAGENTA = 32;
      }
      interface LotsOfColors extends RainbowColors, PrintColors {
           int FUCHSIA = 17, VERMILION = 43, CHARTREUSE = RED+90;
      }
      public class Test implements LotsOfColors {
          public static void main()
         {
             System.out.println(YELLOW); // OOPSS..!!....Got Error here
             System.out.println(RED); // Shock....!!....Run Successfully...
         }
      }

      the interface LotsOfColors inherits two fields named YELLOW. This is all right as long as the interface does not contain any reference by simple name to the field YELLOW. (Such a reference could occur within a variable initializer for a field.)

      Even if interface PrintColors were to give the value 3 to YELLOW rather than the value 8, a reference to field YELLOW within interface LotsOfColors would still be considered ambiguous.

      For RED Shock :: Why Run Successfully...

      If a single field is inherited multiple times from the same interface because, for example, both this interface and one of this interface's direct superinterfaces extend the interface that declares the field, then only a single member results. This situation does not in itself cause a compile-time error.

      In the previous example, the fields RED, GREEN, and BLUE are inherited by interface LotsOfColors in more than one way, through interface RainbowColors and also through interface PrintColors, but the reference to field RED in interface LotsOfColors is not considered ambiguous because only one actual declaration of the field RED is involved.

      Tuesday 27 May 2014

      Why the return value is 0 instead of 100?

      public class FinallyReturnVariableAlter
      {
         public static void main(String[] args)
        {
           System.out.println(test());
        }

        public static int test()
       {
          int i=0;
          try
         {
            return i;
         }
         finally
        {
          i+=100;
        }
        }
      }

       Answer By Lokesh Gupta :
      • Every function call in java leads to creation of extra memory space created where return value is stored for reference after function execution completes and execution return to caller function back.
      • At that time, that special memory address where return value is stored, if referenced back as return value of function.
      • Here, trick is, the memory slot store the value of returned value, not its reference. So, once any return statement is encountered its value is copied in memory slot. That’s why if you change the value of “i” in finally, return value does not change because its already copied to memory slot.
      • We any other return statement is encountered (e.g. in finally block), its value will be overwritten again. So, it you want to return 100, use return statement in finally also.;

      Monday 26 May 2014

      Java tricks. Extending enumerations

      Goal: 1) to have a type that represents a static set of constant values, so we can benefit from the compile-time check… or in less words, an Enum type, 2) to be able to extend the pre-defined set of values in the client class that extends a base client class… ideally, NewEnum extends BaseEnum.
      Unfortunately, it’s not possible to extend enum type in Java, because of the enum nature: enum is an ordinal type, which makes it possible to be used in switch operator.
      So the solution I’ve come up with is to introduce an interface. Let’s see how it works with the following example.
      public interface State {
          String name(); // will be implemeted by java.lang.Enum class
      }public class Entity {
          private State state = ObjectState.CREATED;
          public void setState(State state) { this.state = state; }
          public State getState() { return state; }
          public enum ObjectState implements State {
              CREATED, ACTIVE, DELETED
          }
      }
      public class Order extends Entity {
          public enum OrderState implements State {
              ACCEPTED, DELIVERED, CANCELLED
          }
      }
      public class EntityController {
          public void create(Entity entity) { entity.setState(ObjectState.CREATED); }
          public void delete(Entity entity) { entity.setState(ObjectState.DELETED); }
          public void activate(Entity entity) { entity.setState(ObjectState.ACTIVE); }
      }
      public class OrderController extends EntityController {
          public void accept(Order order) { order.setState(OrderState.ACCEPTED); }
          public void deliver(Order order) { order.setState(OrderState.DELIVERED); }
          public void cancel(Order order) { order.setState(OrderState.CANCELLED); }
      }
      Pros: both goals achieved, namely we’ve got static constant values and we are not limited by a pre-defined set of values, we can extend it for future use cases.
      Cons: there’s no real extensibility of base enum, so we should be aware of the existing base enum before ‘extending’ it, so we don’t repeat values from it.

      Why is super.super.method(); not allowed in Java? (Child To Grandfather...LOL)


      I have 3 classes they inherit from each other as follows:
      A

      B

      C
      Inside each class I have the following method:
      protected void foo() {
      ...
      }
      Inside class C I want to call foo from class A without calling foo in B:
      protected void foo() {
      // This doesn't work, I get the following compile time error:
      // Constructor call must be the first statement in a constructor
      super().super().foo();
      }

      It violates encapsulation. You shouldn't be able to bypass the parent class's behaviour. It makes sense to sometimes be able to bypass your own class's behaviour (particularly from within the same method) but not your parent's. For example, suppose we have a base "collection of items", a subclass representing "a collection of red items" and a subclass of that representing "a collection of big red items". It makes sense to have:
      public class Items
      {
      public void add(Item item) { ... }
      }

      public class RedItems extends Items
      {
      @Override
      public void add(Item item)
      {
      if (!item.isRed())
      {
      throw new NotRedItemException();
      }
      super.add(item);
      }
      }

      public class BigRedItems extends RedItems
      {
      @Override
      public void add(Item item)
      {
      if (!item.isBig())
      {
      throw new NotBigItemException();
      }
      super.add(item);
      }
      }
      That's fine - RedItems can always be confident that the items it contains are all red. Now suppose we were able to call super.super.add():
      public class NaughtyItems extends RedItems
      {
      @Override
      public void add(Item item)
      {
      // I don't care if it's red or not. Take that, RedItems!
      super.super.add(item);
      }
      }
      Now we could add whatever we like, and the invariant in RedItems is broken.
      Does that make sense?


      You can't even use reflection. Something like

      Class superSuperClass = this.getClass().getSuperclass().getSuperclass();
      superSuperClass
      .getMethod("foo").invoke(this);
       
      would lead to an InvocationTargetException, because even if you call the foo-Method on the superSuperClass, it will still use C.foo() when you specify "this" in invoke. This is a consequence from the fact that all Java methods are virtual methods.

      Finally we have only one way: Child To Papa... And Papa To Grand Papa... 

      Saturday 24 May 2014

      When should we implement Serializable interface?

      1. From What's this "serialization" thing all about?:
        It lets you take an object or group of objects, put them on a disk or send them through a wire or wireless transport mechanism, then later, perhaps on another computer, reverse the process: resurrect the original object(s).
        The basic mechanisms are to flatten object(s) into a one-dimensional stream of bits, and to turn that stream of bits back into the original object(s).
        Like the Transporter on Star Trek, it's all about taking something complicated and turning it into a flat sequence of 1s and 0s, then taking that sequence of 1s and 0s (possibly at another place, possibly at another time) and reconstructing the original complicated "something."
        So, implement the Serializable interface when you need to store a copy of the object, send them it to another process on the same system or over the network.
      2. Because you want to store or send an object.
      3. It makes storing and sending objects easy. It has nothing to do with security.

      Friday 23 May 2014

      Static synchronization

      Today my mood is to play with thread...let's start:
      If you make any static method as synchronized, the lock will be on the class not on object.
      static synchronization

      Problem without static synchronization

      Suppose there are two objects of a shared class(e.g. Table) named object1 and object2.In case of synchronized method and synchronized block there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lock.But there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lock.I want no interference between t1 and t3 or t2 and t4.Static synchronization solves this problem.

      Example of static synchronization

      In this example we are applying synchronized keyword on the static method to perform static synchronization.
      1. class Table{  
      2.   
      3.  synchronized static void printTable(int n){  
      4.    for(int i=1;i<=10;i++){  
      5.      System.out.println(n*i);  
      6.      try{  
      7.        Thread.sleep(400);  
      8.      }catch(Exception e){}  
      9.    }  
      10.  }  
      11. }  
      12.   
      13. class MyThread1 extends Thread{  
      14. public void run(){  
      15. Table.printTable(1);  
      16. }  
      17. }  
      18.   
      19. class MyThread2 extends Thread{  
      20. public void run(){  
      21. Table.printTable(10);  
      22. }  
      23. }  
      24.   
      25. class MyThread3 extends Thread{  
      26. public void run(){  
      27. Table.printTable(100);  
      28. }  
      29. }  
      30.   
      31.   
      32.   
      33.   
      34. class MyThread4 extends Thread{  
      35. public void run(){  
      36. Table.printTable(1000);  
      37. }  
      38. }  
      39.   
      40. class Use{  
      41. public static void main(String t[]){  
      42. MyThread1 t1=new MyThread1();  
      43. MyThread2 t2=new MyThread2();  
      44. MyThread3 t3=new MyThread3();  
      45. MyThread4 t4=new MyThread4();  
      46. t1.start();  
      47. t2.start();  
      48. t3.start();  
      49. t4.start();  
      50. }  
      51. }  
      Output:1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      10
      20
      30
      40
      50
      60
      70
      80
      90
      100
      100
      200
      300
      400
      500
      600
      700
      800
      900
      1000
      1000
      2000
      3000
      4000
      5000
      6000
      7000
      8000
      9000
      10000

      Thursday 22 May 2014

      Java's return value in try-catch-finally mechanism

      Hello friends again question with try,catch and finally..i like it ...lol..

      Here sample code is :

      public class J2 extends J1 {

          public static int function() {
              try {
                  return 1; // We think after return function complete here ...?
              } catch (Exception e) {
                  return 2;
              } finally {
                  return 3;      // But actually  this block execute successfully
          }
       }

          public static void main(String[] args) {
              System.out.println(function());
          }
      }


      I have no idea how the JVM implements it, but the simplest way to look at it (at least conceptually) would be:
      1. the return value in the "try" is pushed onto the stack,
      2. then the "finally" block is executed,
      3. the new return value is pushed onto the stack
      4. the function exits, and the return value is popped from the stack, thus ignoring the first one.


      What I found in the Java language specification at least defines that your code snippet should return 3. Of course, it does not mention how the JVM should implement this, and what possible optimizations one could do.
      Section 14.20.2 defines that
      If execution of the try block completes abruptly for any other reason R, then the finally block is executed. Then there is a choice:
      1. If the finally block completes normally, then the try statement completes abruptly for reason R.
      2. If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
      And the start of chapter14 (section 14.1 to be more precise) specifies what a normal and abrupt completion is. For example a return with a given value is an abrupt completion.
      Hence in this case, the finally block completes abruptly (reason: return with a given value), so the try will complete abruptly for the same reason (and return 3). This is confirmed in section 14.17 about the return statement as well
      If evaluation of the Expression completes normally, producing a value V, then the return statement completes abruptly, the reason being a return with value V.



      About finally block ...


      Hello friends my Today's question is :

      Here is sample code :

              File file = new File("d:/asd.txt"); //Assume this path is not available
              FileInputStream fileInputStream = null;
              try {
                  fileInputStream = new FileInputStream(file);
              } catch (FileNotFoundException e) { // So Exception catch Here
                             e.printStackTrace();
              }
        // So now finally block must execute 
           finally {
                  try {
                      fileInputStream.close();  // but here again exception comes here
                  } catch (IOException e) {
                      e.printStackTrace();   // So Exception catch Here
                  }finally {
                      System.out.println("inner finally");  // This statement executed
                  }
                  System.out.println("finally"); // Why this statement is not execute .. ?
              }
      Provide your Comments and feedback ...Thanks is advance..!!!!