Monday, 21 January 2013

Equalizing Two Object

        Even though two object’s property field values are same, those two objects are not same.

        If we want equalize two objects based on property field values, then we need to override equal and hash code methods.



Sample Program


package com.javalearning.crazy;

public class Student {

      public String rNo;

      public String sName;

      public Student(String rNo, String sName) {

            this.rNo = rNo;

            this.sName = sName;

      }

      @Override

      public boolean equals(Object compareObj) {

            // The argument is not equality == operator to check if the argument is

            // the reference to this object, if yes. return true

            if (this == compareObj)

                  return true;

            // The argument is not null

            if (compareObj == null)

                  return false;

            // Cast the method argument to the correct type.

            // Again, the correct type may not be the same class.

            if (!(compareObj instanceof Student))

                  return false;

            Student compareStudent = (Student) compareObj;

            // Convert the object to a Student

            return this.rNo.equals(compareStudent.rNo);

            // Equal based on the property field value?

      }

      @Override

      public int hashCode() {

            int primeNo = 13;

            return primeNo + this.rNo.hashCode();

      }

      public static void main(String[] args) {

            Student studObj1 = new Student("1001", "Murugan");

            Student studObj2 = new Student("1002", "Murugan");

            boolean areEqual = studObj1.equals(studObj2);

            System.out.println(areEqual);

      }

}

 

Equals Overriding Condition


           If you override the equals(), you MUST also override hashCode(). Otherwise a violation of the general contract for Object.hashCode will occur, which can have unexpected impact when your class uses hash-based collections.

Example


           If only equals is overriden, then when you call put method in HashMap, first will hash to some bucket and when you call put method again it will hash to some other bucket. So, although they are equal, as they don't hash to the same bucket (different hashCode) the map can't realize it and both of them stay in the map.

Wednesday, 9 January 2013

Initializing Library Files even Before Static Block

 private static Method


              The static initialize block will be called on loading of the class, and will have no access to instance variables or methods.



Sample Program


package com.javalearning.basic;

public class StaticInitialize {

      private static boolean a = getInitialize();

      static

      {

            System.out.println("I am inside the static block");

      }

      public static void main(String[] args) {

            if(a)

            {

                  System.out.println("Your Libraries initizalized properly");

            }

      }

      private static boolean getInitialize() {

            int a =5,b=3;

            System.out.println("Initialize libraries prior to static block and can be reused");

            if(a>b)

            return true;

            else

                  return false;

      }

}

Reason Behind


          Static variable initialized prior to static block.

final static Method


    private static boolean a = getInitialize();

      

   private final static boolean getInitialize(){

        // initialization code goes here

    }

}

Advantage


Both can be reused later if you need to re-initialize the class variable. But calling non-final methods from final static method during instance initialization can cause problems.

Sunday, 6 January 2013

Run a Java Program without the Main Method


STEP 1: Create a class ProgramWithoutMain in any location in your system.

public class ProgramWithoutMain {
 static
{
    String str = "Crazy Blog";   
    System.out.println("I am running without Main method:- "+str);     
    System.exit(0);
   
}
}


STEP 2: Set Java Path and Class path as below.



STEP 3: Now Compile and Run the program as below



Reason Behind

        "Static blocks" declared in any Java class are always called before the main () method.

         Here, as soon as the control reaches static block’s closing brace, it tries to search for main () method. To stop my program from looking for main () method, I would simply call System.exit(0); and terminate the entire Java program.