public class Why {

  public static void test() {
    System.out.println("Passed");
  }

  public static void main(String[] args) {
    Why NULL = null;
    NULL.test();
  }
}

test() is a static method. A static member belongs to the type, and do not require an instance to access.

A static member should ONLY be accessed via a type expression. That is, you should’ve written it as follows:

Why.test(); // always invoke static method on the type it belongs to!

Java does allow you to access a static member via an object reference expression, but this is VERY misleading, since this is NOT the actual semantics of a static member access.

Why aNull = null; 
aNull.test(); // DO NOT EVER DO THIS!
// invokes Why.test(), does NOT throw NullPointerException

When accessing a static member through an object reference expression, only the declared type of the reference matters. This means that:

  1. It doesn’t matter if the reference is actually null, since no instance is required
  2. If the reference is not null, it doesn’t matter what the runtime type of the object is, there is no dynamic dispatch!!!

What is Serialization?
Serialization is the conversion of an object to a series of bytes, so that the object can be easily saved to persistent storage or streamed across a communication link.The byte stream can then be deserialized – converted into a replica of the original object.In Java, the serialization mechanism is built into the platform, but you need to implement the Serializable interface to make an object serializable.

You can also prevent some data in your object from being serialized by marking the attribute as transient.

Finally you can override the default mechanism, and provide your own; this may be suitable in some special cases.

private void writeObject(ObjectOutputStream out) throws IOException;
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;

This way you can create your own custom serialization to make it more “whatever” (safe, fast, rare, easy etc. )

It is important to notice that what gets serialized is the “value” of the object, or the contents, and not the class definition.

import java.util.*;

// This class implements "Serializable" to let the system know
// it's ok to do it. You as programmer are aware of that.
public class SerializationSample implements Serializable {

    // These attributes conform the "value" of the object.

    // These two will be serialized;
    private String aString = "The value of that string";
    private int    someInteger = 0;

    // But this won't since it is marked as transient.
    private transient List<File> unInterestingLongLongList;

    // Main method to test.
    public static void main( String [] args ) throws IOException  { 

        // Create a sample object, that contains the default values.
        SerializationSample instance = new SerializationSample();

        // The "ObjectOutputStream" class have the default 
        // definition to serialize an object.
        ObjectOutputStream oos = new ObjectOutputStream( 
                               // By using "FileOutputStream" we will 
                               // Write it to a File in the file system
                               // It could have been a Socket to another 
                               // machine, a database, an in memory array, etc.
                               new FileOutputStream(new File("o.ser")));

        // do the magic  
        oos.writeObject( instance );
        // close the writing.
        oos.close();
    }
}

Real World Example
ATM: When the account holder tries to withdraw money from the server through ATM, the account holder information like withdrawl details will be serialized and sent to server where the details are deserialized and used to perform operations.

How serialization is performed in java.

  1. Implement “java.io.Serializable” interface.(marker interface so no method to implement)
  2. Persist the object : Use java.io.ObjectOutputStream class, a filter stream which is a wrapper around a lower-level byte stream. (to write Object to file systems or transfer a flattened object across a network wire and rebuilt on the other side.)
    1. writeObject(<>) – to write an object
    2. readObject() – to read an serialized Object

When you serialize an object, only the object’s state will be saved, not the object’s class file or methods.

What are the Steps when object is serialized and de-serialized?

  1. First writes the serialization stream magic data
  2. Then it writes out the metadata of the class associated with an instance.( length of the class, the name of the class, serialVersionUID)
  3. Then it recursively writes out the metadata of the superclass until it finds java.lang.object.
  4. Then starts with the actual data associated with the instance.
  5. Finally writes the data of objects associated with the instance starting from metadata to actual content.

How not to serialize any field in class.
Use transient keyword

When child class is serialized does parent class get serialized?
No, Only meta data of parents get serialized till object class.

When parent is serialized does child class get serialized?
Yes, by default child class also get serialized.

How to avoid child class from getting serialized?
Override writeObject and readObject method and throw NotSerializableException exception.also you can mark all fields transient in child class.

Some system-level classes such as Thread, OutputStream, and its subclasses, and Socket are not serializable.

If you have a child class which implements serializable and parent class is not serializable then parent class will be reset to the values they were given during the original construction of the object

 
class Cat
{ 
 public String name = "Cat";
} 

class Tiger extends Cat implements Serializable 
{ 
 public int weight; 

 Tiger(int pWeight, String pName)
 {
   name   = pName;
   weight = pWeight;
 }
} 

class SerialTest
{
 public static void main(String args[])
 {
   Tiger  objTiger = new Tiger(150, "Bengal");
   sysout("Before Serialization : Weight -"+ objTiger.getWeight + " Name -"+ objTiger.getName); 
 }
 
}

Output

 Before Serialization : Weight - 150 Name - Bengal 
 After Serialization : Weight - 150  Name - Cat

After serialization the Parent class Cat Name would be set to Original name which is Cat.This is because non-serializable class constructor will run.

 class Animal implements Serializable
 { 
   transient String swims = "Y";
 }

When the Animal has deserialized the value of swims would be set to null since it is marked as transient.

If you serialize a collection(ArrayList, LinkedList) or an array, every element must be Serializable. If any element in the collection is non-serializable then serialization fails. Collection interfaces are non serializable(List,Map) whereas concrete collection classes are serializable(ArrayList, LinkedList)

Static Variables are not serializable
Static variables are not saved as part of object state because they do not belong to object they belong to Class

What are serializable and not serializable

  1. Instance Variables: These variables are serialized, so during deserialization we will get back the serialized state.
  2. Static Variables: These variables are not serialized, So during deserialization static variable value will loaded from the class.(Current value will be loaded.)
  3. transient Variables: transient variables are not serialized, so during deserialization those variables will be initialized with corresponding default values (ex: for objects null, int 0).
  4. Super class variables: If super class also implemented Serializable interface then those variables will be serialized, otherwise it won’t serialize the super class variables. and while deserializing, JVM will run default constructor in super class and populates the default values. Same thing will happen for all superclasses.

The most basic difference is the association
Listener is associated with Event Source (Ex: key board)
Handler is associated with an Event (Ex: keydown)

A listener watches for an event to be fired. For example, a KeyListener waits for KeyEvents, a MessageListener waits for messages to arrive on a queue and so on.The handler is responsible for dealing with the event.

Fibonacci(without using recursion)

public class Test
{
  public static void main(String[] args)
  {
     int a=0 , b=0 , c=1;
     System.out.println(a);
     System.out.println(b);

     for(int i=0;i<15;i++)
     {
        a=b;
        b=c;
        c=a+b;
        System.out.println(c);
     }
   }
}

Fibonacci(using recursion)

7

Reverse array without Temp Array

public static int[] reverseArrayWithoutTempArray(int[] array) 
{
    int i = 0, j = array.length - 1;
 
    for (i = 0; i < array.length / 2; i++, j--) 
    {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}

Iterate random integer array and print the values greater than the current value

class Main 
{
 static void printNGE(int arr[]) 
 {
  int highestVal = 0, i, j;

  for (i = 0; i < arr.length; i++) 
  {
       if (arr[i] > highestVal) 
       {
        System.out.println(arr[i]);
        highestVal = arr[i];
       }
  }
 }

 public static void main(String args[]) 
 {
  int arr[]= {11, 13, 21, 3, 45};
  printNGE(arr);
 }
}

Inheritance program with Class and Interface.Find and print the Area and Perimeter for Rectangle,Square and Circle

  1. Interface Shape
  2. Rectangle class implements Shape
  3. Circle class extends Rectangle
interface Shape 
{
 void input();
 void area();
}

class Circle implements Shape 
{
 int r = 0;
 double pi = 3.14, ar = 0;
 
 @Override
 public void input() 
 {
  r = 5;
 }
 
 @Override
 public void area() 
 {
  ar = pi * r * r;
  System.out.println("Area of circle:" + ar);
 }
}

class Rectangle extends Circle 
{
 int l = 0, b = 0;
 double ar;

 public void input() 
 {
  super.input();
  l = 6;
  b = 4;
 }

 public void area() 
 {
  super.area();
  ar = l * b;
  System.out.println("Area of rectangle:" + ar);
 }
}

public class Demo 
{
 public static void main(String[] args) 
 {
  Rectangle obj = new Rectangle();
  obj.input();
  obj.area();
 }
}
Area of circle:78.5
Area of rectangle:24.0

Why not use for(int i=0; i< v.size();i++){}?

For loops are expensive to the processor when the collection reaches large sizes, as many operations are done just to compute the first line:

For Loop

  1. int i = 0 is an assignment and creation (2 operations)
  2. i get size, check value of i, and compare (3 operations)
  3. i++ gets i then adds 1 to it [++i is only 2 operations] this one (3 operations)
  4. 7/8 operations in total, each time the loop runs through

While Loop

  1. where an enumeration or iterator uses a while(){}
  2. while(v.hasNext()) has next true or false (1 operation)
  3. while(v.hasMoreElements()) has more true or false (1 operation)
  4. Only one operation per repeat of this loop

Final Example]

  1. Final is used to apply restrictions on class, method and variable. Final class can’t be inherited, final method can’t be overridden and final variable value can’t be changed.
  2. Final is a keyword.
class FinalEg
{
   public static void main(String[] args) 
   {
      final int x = 600;
      x = 400;// Compile Time Error
    }
}

Finally Example

  1. Finally is used to place important code, it will be executed whether exception is handled or not.
  2. Finally is a block.
class FinallyEg
{
	public static void main(String[] args) 
	{
		try {
			int x = 500;
		} catch (Exception e) {
			System.out.println(e);
		} finally {
			System.out.println("finally block is executed");
		}
	}
}

Finalize Example

  1. Finalize is used to perform clean up processing just before object is garbage collected.
  2. Finalize is a method.
class FinalizeEg 
{
	public void finalize() 
        {
	   System.out.println("finalize called");
	}

	public static void main(String[] args) 
        {
		FinalizeExample f1 = new FinalizeExample();
		FinalizeExample f2 = new FinalizeExample();
		f1 = null;
		f2 = null;
		System.gc();
	}
}

Difference between throw and throws in Java

void doCalc() throws ArithmeticException
{  
   .
   .
   throw new ArithmeticException("sorry");  
}  

throw

  1. Java throw keyword is used to explicitly throw an exception.
  2. Checked exception cannot be propagated using throw only.
  3. Throw is followed by an instance.
  4. Throw is used within the method.
  5. You cannot throw multiple exceptions.

throws

  1. Java throws keyword is used to declare an exception.
  2. Checked exception can be propagated with throws.
  3. Throws is followed by class.
  4. Throws is used with the method signature.
  5. You can declare multiple exceptions e.g.
    public void method()throws IOException,SQLException.

What would be the Output

public class Main 
{	
  static
  {
    System.out.println("My Name is Mugil");
  }
}

OP: My Name is Mugil
followed by exception in Main

public class Main 
{	
  static
  {
    System.out.println("My Name is Mugil");
  }
	
  public static void main(String args[])
  {
    {
      System.out.println("What is your Name");	 
    }
  }
}

OP: My Name is Mugil
What is your Name

public class Main 
{	
  public static void main(String args[])
  {
    {
      System.out.println("What is your Name");
    }
   }
}

OP: What is your Name

4.What is the order they are processed

public class Main 
{	
 public static void main(String args[])
 {
   {
     ClassA objA = new ClassA();
     System.out.println("What is your Name"); 
   }
 }
}

class ClassA 
{
  static
  {
    System.out.println("I am in ClassA Static");
  }
	
  ClassA()
  {
    System.out.println("I am in ClassA Constrctor");  
  }

  {
    System.out.println("I am in ClassA");
  }
}

OP:I am in ClassA Static
I am in ClassA
I am in ClassA Constrctor
What is your Name

Static blocks are initiated at first followed by Constructor followed by classA and content in empty class.

5.How to Use Object to invoke function in Class

public class Main2
{
 public static void main(String args[])
 {	
   new A().showName();
 }
}

class A 
{
  public void showName()
  {
    System.out.println("Hi there");
  }
}

OP : Hi there

6.How to Find Class of object

  public class Main3 
  {
   public static void main(String[] args) 
   {
     ClasB objB = new ClasB();
     
     if(objB instanceof ClasB)
     {
       System.out.println(objB.getClass().getName());	
     }		
    }
  }

  class ClasB
  {	
  }