Thursday, 9 March 2017

JAVA : Island of isolation

JAVA : Island of isolation






Now, both the objects are eligible for garbage collection as there is no way we can call them. This is popularly known as Island of Isolation.


JAVA : WITH OUT MAIN METHOD

JAVA : WITH OUT MAIN METHOD


public class Foo {
    static {
         System.out.println("Message");
         System.exit(0);
    }
}

Use a static initializer block to print the message. This way, as soon as your class is loaded the message will be printed. The trick then becomes using another program to load your class.

Of course, you can run the program as java Foo and you will see the message; however, the command will also fail with a message stating:

Exception in thread "main" java.lang.NoSuchMethodError: main

The System.exit(0) lets the program exit before the JVM is looking for the main method, otherwise the following error will be thrown:

JAVA : Algorithms : BinaryTree implementation

JAVA : Algorithms : BinaryTree implementation



Add method


Search method


JAVA : HashSet -> Equals and hashCode

JAVA : HashSet -> Equals and hashCode


1. In HashSet(value) -> if we are adding string or int as then no need of equals and hascode override, If we are using object (Eg : Employee) as then we need to override equals and hashcode method.

Below screen shot, since we are going to use Employee object in HashSet, If we dont override hashCode method how HashSet behaves.

WithOut hashCode override:




With hashCode override:


Ref: https://www.youtube.com/watch?v=IwUwIrz9Ge8

JAVA : HashMap -> Equals and HashCode

JAVA : HashMap -> Equals and HashCode


1. In HashMap (key, value) -> if we are adding string or int as key then no need of equals and hascode override, If we are using object (Eg : Employee) as a key then we need to override equals and hashcode method.

Below screen shot, since we are going to use Employee object as a key in HashMap, If we dont override hashCode method how HashMap behaves.

WithOut hashCode override:




With hashCode override:

Ref : https://www.youtube.com/watch?v=IwUwIrz9Ge8


Remember : (HashMap internally uses your hashCode to locate the index and your equals to verify the object is same) -  shown in below image.


hasCode - is used to piston the emp object in the particular index of hashmap imlementation. (when you do get(e4) - 1st it checks in which index obj is there, so we must override hasCode() -

equals() - once it finds the index when we do get(e4) -> then it try to find the exact object located in that index using equals() method

What could happen if I only override equals?

  • Suppose you only override equals but not hashCode
  • This means that hashCode is inherited from Object
  • Object.hashCode always tries to return different hash codes for different objects (regardless if they are equal or not)
  • This means that you may end up with different hash codes for two objects that you consider to be equal
  • This in turn causes these two equal objects to end up in different buckets in hash based collections such as HashSet
  • This causes such collections to break

What could happen if I only override hashCode?

This will not break the code as above, but may degrade performance.
  • Suppose you only override hashCode but not equals
  • This means that you may return the same hash code for two non-equal objects
    • Object.hashCode might do so too, but it does an as good job as possible to avoid it
  • This in turn means that two non-equal objects end up in the same bucket in a hash based collection such as HashSet
  • This degrades performance since objects are not distributed as evenly as possible among the buckets
  • Put differently: If you don’t override equals any two objects will be considered non-equal. Since Object.hashCodeensures that all objects are distributed as evenly as possible in a hash based collection Object.hashCode is optimal, and overriding it with anything else will worsen the performance.


V

JAVA : RUN TIME STACK and Default Exception Handling

JAVA : RUN TIME STACK and Default Exception Handling



Default Exception Handling


The method in which exception is raised is responsible to create "Exception object"
by including following information:

1. Name of exception :
2. Description of exception :
3. Location at which exception occurs [Stack trance]

After creating exception object method handover to JVM

JVM will check whether method contains any Exception handling code or not.

If not then it destroy the method and remove entry from stack and handover the object to "Default exception handler"

"Default exception handler" simply prints the exception.

JAVA : FINAL keyword

JAVA : FINAL keyword


The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:
  1. variable
  2. method
  3. class



JAVA : COLLECTION : LINKED LIST

JAVA : COLLECTION : LINKED LIST


Underline data structure for Linked List is -> Doubly linked list.

If we search for 10000 th element -> it takes 10000 secs, bez it always searches from 1st, because 10000 element address is with 9999, 9999 element address is with 9998 .......... 2nd element address is with 1st element.


  • Internally its Doubly linked list
  • Insertion order is preserved
  • Duplicates are allowed
  • Hetrogeneous elements are allowed (In collection exept TreeSet and TreeMap all collection it is allwoed)
  • Null is allowed
  • Not implement RandomAccess, but it implements Serializable and Clonable interfaces.



Linked List is mainly used to develop Stack and Queue

If you see in Stack and Queue since it is LIFO or FIFO not like in between element will be searched, and pop or add will be done sequentially, these objects are implemented using LinkedList.



https://www.youtube.com/watch?v=ZqDT9xg4TGE&t=1100s

JAVA : COLLECTION : ARRAYLIST VS VECTOR

JAVA : COLLECTION : ARRAYLIST VS VECTOR


JAVA : COLLECTION : VECTOR

JAVA : COLLECTION : VECTOR


Under line data structure is "Resizable array or Growable array"

ArrayList and Vector implements "RandomAccess", which is extra than other collection objects.

ArrayList and Vectors are perfectly same other than most of Vector methods are Thread safe.






JAVA : COLLECTION : ARRAYLIST

JAVA : COLLECTION : ARRAYLIST


All collection objects are implemented based on some standard data structure.

ArralyList is implemented based on data structure is "Resizable or Growable array".















Wednesday, 8 March 2017

JAVA : COLLECTION : ARRAY

JAVA : COLLECTION : ARRAY




Its always recommended that If we know the fixed size then go with Array for better performance


Because since collections has grow able nature, once collection reaches its max size automatically below things happen.



Wednesday, 1 March 2017

JAVA : EXCEPTION : Custom Exception

JAVA : EXCEPTION : Custom Exception



public class MyException extends Exception
{
    public MyException(String mymsg)
    {
        super(mymsg);
    }

}



class MyException extends Exception{
    String str1;
    MyException(String str2) {
       str1=str2;
    }
    public String toString(){
       return ("Output String = "+str1) ;
    }

}



good design/practice

Raising custom exceptions also allows you to treat exceptions in a more precise manner; for instance, if you have defined FooException inheriting IOException, then you can have a special treatment for it:


try { ... }
catch (FooException e) { ... } // Catch it _before_ IOException!
catch (IOException e) { ... }










JAVA : VOLATILE variable

JAVA : VOLATILE variable

Volatile - easily evaporated from cpu cache

By declaring the counter variable volatile all writes to the counter variable will be written back to main memory immediately.

The volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory

Instead of synchronized variable in Java, you can have java volatile variable, which will instruct JVM threads to read value of volatile variable from main memory and don't cache it locally. If a variable is not shared between multiple threads no need to use volatile keyword with that variable


public class SharedObject {

    public int counter = 0;

}

public class SharedObject {

    public volatile int counter = 0;

}

JAVA : STACK Reverse

JAVA : STACK Reverse


1.   public static void main(String[] args){
2.             Stack<Integer> stack = new Stack<Integer>();
3.             stack.push(1);
4.             stack.push(2);
5.             stack.push(3);
6.            
7.             stack = reverseStack(stack);

8.   }

1.   public static Stack<Integer> reverseStack(Stack stack){
2.             Stack<Integer> reverse = new Stack<Integer>();
3.             while(!stack.empty()){
4.                      reverse.push(stack.pop());
5.             }
6.             return reverse;
7.   }