Consonant
The word consonant is also used to refer to a letter of an alphabet that denotes a consonant sound. The 21 consonant letters in the English alphabet are B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, X, Z, and usually W and Y

Vowels
a,e,i,o,u, y is Special Vowel

Bicycle
Pretty
Why

In the above words y is spelled like i

Noun is person, place, animal, thing e.g. book,park,umbrella, elephant, dcotor, orange

Use of Articles in Front of Vowels
A Banana
An Apple(Apple starts with vowel A)
A Cat
A Boy
An Egg
The Cat(Particular Cat)

Singular & Plural Noun
Singular Noun
A ring
A Dog
A Teacher
An Apple
An Egg

Plural Noun and their Singular
Two Rings – A Ring
Three Dogs – A Dog
Four Teachers – A Teacher
Five Apples – An Apple
Six Eggs – An Egg

To make plural we use s (or) es
A Bus – Two Buses
A Box – Two Boxes
A Watch – Two Watches

How to Decide s or es
If the noun ends with ch,sh,x,ss we should put es
Church – Churches
Brush – Brushes
Fox – Foxes
Dress – Dresses

Special Noun for Noun
Potato – Potatoes
Tomato – Tomatoes
Volcano – Volcanoes

where as
Photo – Photos

Pronoun (or) Subjective Pronoun
I,He,She, It, You,We,They

Jenny Sings – She Sings
Jack Sings – He Sings
Jenny and Jack Sings – They Sings
The Cat Runs – It Runs
The Dog and Cat Runs – They Runs
My Students Study – They Study
John is Handsome – He is Handsome
Pizza is Delicious – It is Delicious

“Be” verbs indicate a state of being.
Am, is, are

Pronoun + Be VerbContractions
I am – I’m
He is – He’s
She is – She’s
It is – It’s
You are – You’re
We are – We’re
They are – They’re

A Contraction is common way to tell Subjective Pronoun and Be Verb

I’m a Student [Don’t miss a in middle]
It’s a Dog [Don’t miss a in middle]

We’re Students [Many Student so no a In between]
They’re Students [Many Student so no a In between]

Pronouns + Be Verb + Not
I’m not a Student
He’s not a Student
You’re not Students [Note : a is missing in front of Student]
They’re not Students [Note : a is missing in front of Student]

BE verbs comes in front of a question
Am I a teacher

BE verbs follows pronoun in answer
I am not a teacher

Question Singular and Plural
What is it?
It is a box

If there is single box it would be it

What are they?
They are boxes

If there are multiple boxes it would be they

Examples
What is it?
It is a cat.

What are they?
They are Cats

Singular – is – Only one thing
Plural – are – Group of thing

This and That
We use this to point to one noun that is close

I.E.
This is flower

We use that to point to one noun that is away

I.E.
That is flower

This and That in Question
Example
Is this a Flower?
Is that a Flower?

These and Those
These are Flowers(Closer)
Those are Flowers(Away)

These and Those in Questions
Are these Flowers?(Closer) No they aren’t.
Are those Flowers?(Away) No they aren’t.

Close Far
This That
These Those

Possessive Adjective
Used to tell something belongs to me or Someone else

Subjective Pronoun Possessive Adjective
I My
He His
She Her
It Its
You Your
We Our
They Their

Possessive Adjective
Its and It’s are different
Your and You’re are different
Their and They’re are different

Possessive Pronoun
Something belongs to us (or) something owned by us. Possessive pronoun and possessive adjectives are almost same. In possessive pronoun you don’t stretch much on noun.

Possessive Adjective Possessive Pronoun
This is his Hat This is his
This is her dress This is hers
This is their house This is theirs
This is their books These are theirs

A/An/The

a/an the
anyone thing specific thing
first time second time
article to be used in front of noun One and Only

Examples
A banana is Delicious [All banana is delicious]
The banana is Old[Particular banana is old]

I watched a movie [First Time]
I watched the Movie.[Second Time]

The Sun[One and Only]
The Moon[One and Only]

More Examples
A lion is Dangerous Animal[All lions are dangerous]
It’s a Dog[Talking first time]
The Dog is Cute[Talking Second Time]
It’s an ant[Starts with vowel]
The ant is small[Particular ant]
It’s the moon.The moon is round[One and only moon]

Prepositions
a word governing, and usually preceding, a noun or pronoun and expressing a relation to another word or element in the clause, as in ‘the man on the platform’, ‘she arrived after dinner’, ‘what did you do it for ?’.

In/On/Under
Prepositions to tell where something is

The cat is in the Box
The Cat is on the Chair
The Cat under the Chair

Adjectives
Tells the attribute of a noun, such as sweet, red, or technical.
Size, Shape, Color. Adjectives comes before noun

Examples
Its a Black Marker
Its a Blue Bird
Its an ugly ant
They are Red Apples

Have/Has
Both are used to show possessions
Have is used with some pronouns and plural nouns

I.E.
I have
You have
We have
They have

Examples
I have a great English teacher.
You have toothpaste on your chin.
We have a meeting at 12.
Nurses have a difficult job.

Has is used with the third person singular

I.E.
He has
She has
It has

Examples
She has a great personality.
He has a new haircut.
The washing machine has a leak in it.
It has a hole near the door.

Sentence Replaced with Subjective pronoun
The girl has long hair She has long hair
The Boys have caps They have caps
My mother and I have a Car We have a car

I have a Friend
He has an Umbrella
The dog has a bone
It has a bone

In negative sentence we use always have not has.The only thing which needed to be taken care is doesn’t or dont

  1. I don’t have
  2. He doesn’t have
  3. She doesn’t have
  4. It doesn’t have
  5. You don’t have
  6. We don’t have
  7. They don’t have

Do/Does + Have
Does should be followed by he,she,it
Do should be followed by you,we,they

Does he have a friend?
Does she have a friend?
Does it have a friend?

Do you have a friend?
Do we have a friend?
Do they have a friend?

Can I/Could I/May I

  • All are used for getting permission
  • May I is more polite than other two

E.G.
May I help you?
Can I help you again?
Could I Call you Later?
Could I borrow some money?
Can I go?
May I speak to Mr.Kim?
May I go to the bathroom?

Can I and Could I are almost similar
May I is more polite while speaking to someone who is more authoritative or superior than you

May I help you (Mostly heard from shop keepers)

Borrow/Lend Me
Use lend when you are giving money or items to someone.Use borrow when you are taking money or items from someone

You borrow something from somebody. In other words, you take something from someone for a limited time.

You lend something to somebody. In other words, you give something to someone for a limited time.

Wrong
Can I borrow Me your pencil?
Can I borrow your pencil?

Right
Can you lend me your pencil? (or)
Is it ok if I borrow your book?
Can I borrow your umbrella?
May I borrow some money?
Please lend me a pen?
I Lent my baking tin to Emily ages ago and I still haven’t got it back.

If you ask someone to give something or if you give someone – Lend or Lent
If you ask to get something to someone – borrow

An obsolete reference is one that is kept around but will never be used, preventing the object it refers to from being eligible for garbage collection, thus causing a memory leak.

Manually Setting to NULL
Nulling out a reference to remove obsolete references to an object is good, but one must not overdo it. The best way to eliminate an obsolete reference is to reuse the variable in which it was contained or to let it fall out of scope.

Lets take a Simple Stack implementation as in effective Java

public Object pop() {
    if (size == 0)
        throw new EmptyStackException();
    Object result = elements[--size];
    elements[size] = null; // Eliminate obsolete reference
    return result;
}

In the above code you can see that the stack size is shrinked when ever a pop operation is carried out and is set to null allowing the garbage collector to access the unused space to reclaim

Using WeakHashMap
WeakHashMap is an implementation of the Map interface. WeakHashMap is almost same as HashMap except in case of WeakHashMap, if object is specified as key doesn’t contain any references- it is eligible for garbage collection even though it is associated with WeakHashMap. i.e Garbage Collector dominates over WeakHashMap.

How HashMap Works

// Java program to illustrate 
// Hashmap 
import java.util.*;
class HashMapDemo
{
    public static void main(String args[])throws Exception
    {
        HashMap m = new HashMap();
        Demo d = new Demo();
         
        // puts an entry into HashMap
        m.put(d," Hi "); 
         
        System.out.println(m); 
        d = null;
         
        // garbage collector is called
        System.gc();
         
        //thread sleeps for 4 sec
        Thread.sleep(4000); 
         
        System.out.println(m);
        }
    }
    class Demo
    {
        public String toString()
        {
            return "demo";
        }
         
        // finalize method
        public void finalize()
        {
            System.out.println("Finalize method is called");
        }
}

Output

{demo=Hi}
{demo=Hi}

How WeakHashMap Works

// Java program to illustrate 
// WeakHashmap 
import java.util.*;
class WeakHashMapDemo
{
    public static void main(String args[])throws Exception
    {
        WeakHashMap m = new WeakHashMap();
        Demo d = new Demo();
         
        // puts an entry into WeakHashMap
        m.put(d," Hi "); 
        System.out.println(m);
         
        d = null;
         
        // garbage collector is called
        System.gc(); 
         
        // thread sleeps for 4 sec
        Thread.sleep(4000); .
         
        System.out.println(m);
    }
}
 
class Demo
{
    public String toString()
    {
        return "demo";
    }
     
    // finalize method
    public void finalize()
    {
        System.out.println("finalize method is called");
    }
}

Output

{demo = Hi}
finalize method is called
{ }

When Memory Leaks happen in Java

Objects inaccessible by running code but still stored in memory

Class allocates a large chunk of memory (e.g. new byte[1000000]), stores a strong reference to it in a static field, and then stores a reference to itself in a ThreadLocal. Allocating the extra memory is optional (leaking the Class instance is enough), but it will make the leak work that much faster.

Static field holding object reference

class MemorableClass 
{
    static final ArrayList list = new ArrayList(100);
}

Calling String.intern() on lengthy String

String str=readString(); // read lengthy string any source db,textbox/jsp etc..
// This will place the string in memory pool from which you can't remove
str.intern();

Unclosed open streams ( file , network etc… )

try {
    BufferedReader br = new BufferedReader(new FileReader(inputFile));
    ...
    ...
} catch (Exception e) {
    e.printStacktrace();
}

Unclosed connections

try {
    Connection conn = ConnectionFactory.getConnection();
    ...
    ...
} catch (Exception e) {
    e.printStacktrace();
}

The thread clears all references to the custom class or the ClassLoader it was loaded from.

There could not be any class which conform to both Same type comparison and Mixed type comparison

Same-Type Comparison
With such an implementation of equals() you can store an Employee(“Hanni Hanuta”) and a Student(“Hanni Hanuta”) into the same HashSet , but retrieval from the collection will not work as expected. You will not find any of these two contained objects when you ask the HashSet whether it contains a Person(“Hanni Hanuta”) , because all three object are unequal to each other.

Mixed-Type Comparison
In a class hierarchy, where Employee and Student are subclasses of a Person , representing roles of a person, it may make sense to compare an Employee to a Student to see whether they are the same Person . With an implementation of equals() that only allows same-type comparison an Employee and a Student would not be comparable.So mixed type comparison allows comparison between parent and child object.With this type of equals() implementation you will have problems storing an Employee(“Hanni Hanuta”) and a Student(“Hanni Hanuta”) in the same HashSet . The HashSet will reject the second add() operation, because the collection already contains an element that compares equal to the new element.

Lets see an example of Mixed-Type comparison

class BaseClass {
    private int field1 = 0;

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof BaseClass) {
            return field1 == ((BaseClass) obj).field1;
        }
        return false;
    }
}

class BadSubClass extends BaseClass {
    private int field2 = 0;

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof BadSubClass) {
            return super.equals(obj) 
                    && field2 == ((BadSubClass) obj).field2;
        }
        return false;
    }
}
BaseClass baseClass = new BaseClass();
BadSubClass subClass = new BadSubClass();

System.out.println(baseClass.equals(subClass)); // prints 'true'
System.out.println(subClass.equals(baseClass)); // prints 'false'

Now the above implementation does not comply to symmetric property of equals
x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

The work around for this is

class BaseClass {
    private int field1 = 0;

    @Override
    public boolean equals(Object obj) {
        if (obj != null && obj.getClass() == getClass()) {
            return field1 == ((BaseClass) obj).field1;
        }
        return false;
    }
}

class GoodSubClass extends BaseClass {
    private int field2 = 0;

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof GoodSubClass) {
            return super.equals(obj) && field2 == ((GoodSubClass) obj).field2;
        }
        return false;
    }
}

When the clone method is invoked upon an array, it returns a reference to a new array which contains (or references) the same elements as the source array.

So in your example, int[] a is a separate object instance created on the heap and int[] b is a separate object instance created on the heap. (Remember all arrays are objects).

    int[] a = {1,2,3};
    int[] b = a.clone();

    System.out.println(a == b ? "Same Instance":"Different Instance");
    //Outputs different instance

If were to modify int[] b the changes would not be reflected on int[] a since the two are separate object instances.

b[0] = 5;
    System.out.println(a[0]);
    System.out.println(b[0]);
    //Outputs: 1
    //         5

This becomes slightly more complicated when the source array contains objects. The clone method will return a reference to a new array, which references the same objects as the source array.

class Dog{

        private String name;

        public Dog(String name) {
            super();
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

    }

Lets create and populate an array of type Dog

Dog[] myDogs = new Dog[4];

    myDogs[0] = new Dog("Wolf");
    myDogs[1] = new Dog("Pepper");
    myDogs[2] = new Dog("Bullet");
    myDogs[3] = new Dog("Sadie");

Clone dog

    Dog[] myDogsClone = myDogs.clone();


System.out.println(myDogs[0] == myDogsClone[0] ? "Same":"Different");
    System.out.println(myDogs[1] == myDogsClone[1] ? "Same":"Different");
    System.out.println(myDogs[2] == myDogsClone[2] ? "Same":"Different");
    System.out.println(myDogs[3] == myDogsClone[3] ? "Same":"Different");

This means if we modify an object accessed through the cloned array, the changes will be reflected when we access the same object in the source array, since they point to the same reference.

myDogsClone[0].setName("Ruff"); 
    System.out.println(myDogs[0].getName());
    //Outputs Ruff

changes to the array itself will only affect that array.

myDogsClone[1] = new Dog("Spot");
    System.out.println(myDogsClone[1].getName());
    System.out.println(myDogs[1].getName());
    //Outputs Spot
    //Pepper

As you see above the change in the child by assigning a new Dog does not have any impact on the parent because the reference itself is changed instead of change in the reference value.

Object cloning refers to creation of shallow copy of an object.

Why we Need Clone?

// Java program to demonstrate that assignment
// operator only creates a new reference to same
// object.
import java.io.*;
 
// A test class whose objects are cloned
class Test
{
    int x, y;
    Test()
    {
        x = 10;
        y = 20;
    }
}
 
// Driver Class
class Main
{
    public static void main(String[] args)
    {
         Test ob1 = new Test();
 
         System.out.println(ob1.x + " " + ob1.y);
 
         // Creating a new reference variable ob2
         // pointing to same address as ob1
         Test ob2 = ob1;
 
         // Any change made in ob2 will be reflected
         // in ob1
         ob2.x = 100;
 
         System.out.println(ob1.x+" "+ob1.y);
         System.out.println(ob2.x+" "+ob2.y);
    }
}

output

10 20
100 20
100 20

In Java, we can create only copy of reference variable and not the object.

How to Use Clone?

  1. class that implements clone() should call super.clone() to obtain the cloned object reference
  2. the class must also implement java.lang.Cloneable interface whose object clone we want to create otherwise it will throw CloneNotSupportedException when clone method is called on that class’s object.
  3.   protected Object clone() throws CloneNotSupportedException
    
// A Java program to demonstrate shallow copy
// using clone()
import java.util.ArrayList;
 
// An object reference of this class is
// contained by Test2
class Test
{
    int x, y;
}
 
// Contains a reference of Test and implements
// clone with shallow copy.
class Test2 implements Cloneable
{
    int a;
    int b;
    Test c = new Test();
    public Object clone() throws
                   CloneNotSupportedException
    {
        return super.clone();
    }
}
 
// Driver class
public class Main
{
    public static void main(String args[]) throws
                          CloneNotSupportedException
    {
       Test2 t1 = new Test2();
       t1.a = 10;
       t1.b = 20;
       t1.c.x = 30;
       t1.c.y = 40;
 
       Test2 t2 = (Test2)t1.clone();
 
       // Creating a copy of object t1 and passing
       //  it to t2
       t2.a = 100;
 
       // Change in primitive type of t2 will not
       // be reflected in t1 field
       t2.c.x = 300;
 
       // Change in object type field will be
       // reflected in both t2 and t1(shallow copy)
       System.out.println(t1.a + " " + t1.b + " " +
                          t1.c.x + " " + t1.c.y);
       System.out.println(t2.a + " " + t2.b + " " +
                          t2.c.x + " " + t2.c.y);
    }
}

output

10 20 300 40
100 20 300 40

How to Achieve Deep Copy

// A Java program to demonstrate deep copy
// using clone()
import java.util.ArrayList;
 
// An object reference of this class is
// contained by Test2
class Test
{
    int x, y;
}
 
 
// Contains a reference of Test and implements
// clone with deep copy.
class Test2 implements Cloneable
{
    int a, b;
 
    Test c = new Test();
 
    public Object clone() throws
                CloneNotSupportedException
    {
        // Assign the shallow copy to new refernce variable t
        Test2 t = (Test2)super.clone();
 
        t.c = new Test();
 
        // Create a new object for the field c
        // and assign it to shallow copy obtained,
        // to make it a deep copy
        return t;
    }
}
 
public class Main
{
    public static void main(String args[]) throws
                             CloneNotSupportedException
    {
       Test2 t1 = new Test2();
       t1.a = 10;
       t1.b = 20;
       t1.c.x = 30;
       t1.c.y = 40;
 
       Test2 t3 = (Test2)t1.clone();
       t3.a = 100;
 
       // Change in primitive type of t2 will not
       // be reflected in t1 field
       t3.c.x = 300;
 
       // Change in object type field of t2 will not
       // be reflected in t1(deep copy)
       System.out.println(t1.a + " " + t1.b + " " +
                          t1.c.x + " " + t1.c.y);
       System.out.println(t3.a + " " + t3.b + " " +
                          t3.c.x + " " + t3.c.y);
    }
}

output

10 20 30 40
100 20 300 0

When to use Clone?

  1. We should use clone to copy arrays because that’s generally the fastest way to do it.

Disadvantages of Clone Method

  1. Cloneable interface lacks the clone() method. Actually, Cloneable is a marker interface and doesn’t have any methods in it, and we still need to implement it just to tell the JVM that we can perform clone() on our object.
  2. Object.clone() is protected, so we have to provide our own clone() and indirectly call Object.clone() from it.
  3. If we are writing a clone method in a child class, e.g. Person, then all of its superclasses should define the clone() method in them or inherit it from another parent class. Otherwise, the super.clone() chain will fail.
  4. We can not manipulate final fields in Object.clone() because final fields can only be changed through constructors. In our case, if we want every Person object to be unique by id, we will get the duplicate object if we use Object.clone() because Object.clone() will not call the constructor, and final id field can’t be modified from Person.clone().

There are two effective ways to create copy of object

  1. Copy Constructor – Refer here
  2. Serialization- Refer Here

Even copy constructor has its disadvantage since working with the internal object(Child Objects) may make it inconsistent and fragile

Reusing Immutable Object

 
              //Dont Use this
              String strName = new String("Mugil");

              //Use this
              String strName = "Mugil";
         

The Best Example of Immutable Object Reuse is Integer Caching in Java.Lets take the following Example

public class Scratch
{
   public static void main(String[] args)
    {
        Integer a = 1000, b = 1000;  //1
        System.out.println(a == b);

        Integer c = 100, d = 100;  //2
        System.out.println(c == d);
   }
}

Output

false
true

Integer class keeps a cache of Integer instances in the range of -128 to 127, and all autoboxing, literals and uses of Integer.valueOf() will return instances from that cache for the range it covers.

Note that the cache only works if you use auto-boxing or the static method Integer.valueOf(). Calling the constructor will always result in a new instance of integer, even if the value of that instance is in the -128 to 127 range. Integer.valueOf(int). It will return the same Integer object for inputs less than 256.

Reusing Mutable Object

package com.mugil.org.ej;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Item5 
{
	public static void main(String[] args) throws ParseException 
	{
		Person objPerson = new Person();
		objPerson.initializeDates();
		
		
		SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy");
		String endDate = "31-03-2019";
		Date financialYrEndDate = sdf.parse(endDate);
		
		if(financialYrEndDate.after(objPerson.getFinancialYrStartDate()))
		{
			System.out.println("Valid End Date");
		}
	}
}


class Person
{
	private Date financialYrStartDate;	
	
	public void initializeDates() throws ParseException
	{
		SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy");
		String dateInString = "01-04-2018";
		financialYrStartDate = sdf.parse(dateInString);
	}

	public Date getFinancialYrStartDate() {
		return financialYrStartDate;
	}

	public void setFinancialYrStartDate(Date financialYrStartDate) {
		this.financialYrStartDate = financialYrStartDate;
	}	
}

In the above example I know for Sure that the Financial Year End Date should be after Start Date and the Start Date is going to be same for Every Year

package com.mugil.org.ej;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Item5 
{
	public static void main(String[] args) throws ParseException 
	{			
		SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy");
		String endDate = "31-03-2019";
		Date financialYrEndDate = sdf.parse(endDate);
		
		if(financialYrEndDate.after(Person.financialYrStartDate ))
		{
			System.out.println("Valid End Date");
		}
	}
}


class Person
{
	static Date financialYrStartDate;
	
	static
	{	
		SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy");
		String dateInString = "01-04-2018";		
		try {
			financialYrStartDate = sdf.parse(dateInString);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}		
}

Since financialYrStartDate is going to be same it is made as Class Variable which helps to prevent unnecessary Object Creation.

Use Primitives instead of Wrapper Class

public static void main(String[] args) {
    Long sum = 0L; // uses Long, not long
    for (long i = 0; i <= Integer.MAX_VALUE; i++) {
        sum += i;
    }
    System.out.println(sum);
}

It takes 43 seconds to run as Long and long primitive brings it down to 6.8 seconds.

Noninstantiable classes are those which can be invoked using object creation.We prefer classes to be Noninstantiable if you want the class to be Utility class with static methods and variables in it.

public final class Useless {
    private Useless() {}
}

A private constructor is the normal object-oriented solution. However, it would still be possible to instantiate such a class using reflection, like this:

Constructor<Useless> con = Useless.class.getDeclaredConstructor();
con.setAccessible(true); // bypass "private"
Useless object = con.newInstance();

To prevent even reflection from working, throw an exception from the constructor:

public final class Useless {
    private Useless() {
        throw new UnsupportedOperationException();
    }
}

Dont Use absract class for NonInstantiable classes

Attempting to enforce noninstantiability by making a class abstract does not work. The class can be subclassed and the subclass instantiated. Furthermore, it misleads the user into thinking the class was designed for inheritance

When Singleton should be used?
Singleton should be used incase creation of Object is costly or heavy I.E. DBConnection. It should not be used if the Object is mutable.

  1. Eager initialization
  2. Lazy initialization
  3. Static block initialization
  4. Using Synchronized method
  5. Using Synchronized block
  6. Double Checked Locking
  7. Enum Singleton
  8. Initialization on demand holder idiom

3 Things are common across all singleton implementation

private constructor
public static getInstance Method
private static instance field

Eager initialization
An instance of Singleton Class is created at the time of class loading

EagerInitialized.java

package com.mugil.singleton;

public class EagerInitialized {
	
	private static final EagerInitialized instance = new EagerInitialized();
	
	//Private Constructor
	private EagerInitialized()
	{
	}
	
	public static EagerInitialized getInstance()
	{
         return instance;
        }	
}

Lazy Initialization
With lazy initialization you crate instance only when its needed and not when the class is loaded

LazyInitialized.java

package com.mugil.singleton;

public class LazyInitialized 
{
	public static  LazyInitialized instance = null; 
	
	private LazyInitialized()
	{
		
	}
	
	public static LazyInitialized getInstance(){
        if(instance == null){
            instance = new LazyInitialized();
        }
        return instance;
    }
}

Static Block Initialization
Static block initialization is similar to eager initialization, except that an instance of class is created in the static block that provides an option for exception handling.

StaticBlockInitialized.java

package com.mugil.singleton;

public class StaticBlockInitialized {

	private static StaticBlockInitialized instance;

	private StaticBlockInitialized() {
	}

	// Static block initialization for exception handling
	static {
		try {
			instance = new StaticBlockInitialized();
		} catch (Exception e) {
			throw new RuntimeException("Exception occurred in creating singleton instance");
		}
	}

	public static StaticBlockInitialized getInstance() {
		return instance;
	}
}

Using Synchronized Method
The easier way to create a thread-safe singleton class is to make the access method synchronized, so that only one thread can execute this method at a time.

ThreadSafeSing.java

package com.mugil.singleton;

public class ThreadSafeSing {

    private static ThreadSafeSinginstance;
    
    private ThreadSafeSing(){}
    
    public static synchronized ThreadSafeSing getInstance(){
        if(instance == null){
            instance = new ThreadSafeSing();
        }
        return instance;
    }    
}

Using Synchronized Block
The easier way to create a thread-safe singleton class is to make the access method synchronized, so that only one thread can execute this method at a time. Refer the link for the same Link

ThreadSafeSing.java

package com.mugil.singleton;

public class ThreadSafeSing {
    private static ThreadSafeSinginstance;
    
    private ThreadSafeSing(){}
    
    public static ThreadSafeSing getInstance(){
        Synchronized(ThreadSafeSing.class){ 
          if(instance == null){
            instance = new ThreadSafeSing();
          }
        }
        return instance;
    }    
}

Double Checked Locking Singleton
Above Implementation of Singleton provides thread safety buy has a hit over performance. The performance hit happens when two threads try to get the instance of object in getInstance() method but only one is allowed within Synchronized block while the other needs to wait until the first is done checking irrespective of the instance is already created or not.

In the Below method of Implementing Singleton, we again use Synchronized Block but we do the check for the availability of the object instance even before taking lock.

DCCSingleton.java

package com.mugil.singleton;

public class DCCSingleton{

    private static DCCSingletoninstance;
    
    private DCCSingleton(){}
    
   public static DCCSingleton getInstanceUsingDoubleLocking()
   {
    if(instance == null){
        synchronized (DCCSingleton.class) {
            if(instance == null){
                instance = new DCCSingleton();
            }
        }
    }
    return instance;
  }    
}

Refer the Link for how Double Checked Locking works

ENUM Singleton
enum fields are compile time constants, but they are instances of their enum type. And, they’re constructed when the enum type is referenced for the first time.
ENUMSingleton.java
Simple Singleton using enum for DBConnection

public enum EnumSingleton
{
    INSTANCE;

    // instance vars, constructor
    private final Connection connection;

    private Singleton()
    {
        //Initialize the connection
        connection = DB.getConnection();
    }

    public Connection getConnection(){
       return connection;
    }

    // Static getter
    public static Singleton getInstance()
    {
        return INSTANCE;
    }
}

The way it works we can either use getInstance() method or directly call EnumSingleton.INSTANCE to access connection Object.

The Connection can be created using the Below Code

  Connection Conn = Singleton.getInstance().getConnection();

Minimal Implementation using ENUM

public enum MySingleton {
  INSTANCE;   
}

In the above code we may get a doubt how the object is created as we have a empty private constructor which is never invoked?.

The above code gets converted as one below. Above code has an implicit empty constructor. Lets make it explicit instead,

public enum MySingleton {
    INSTANCE;
    private MySingleton() {
        System.out.println("Here");
    }
}

Now when we make a call as below the private constructor is invoked and object gets created

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

Output

Here
INSTANCE

Initialization on demand holder idiom
How it works?

  1. The Below implementation is a lazy loading and thread safe method of creating Singleton
  2. On calling the getInstance() method the lazySingletonClass would be initialized which in turn makes the INSTANCE to be initialized.
  3. Class initialization is inherently thread-safe and if you can have an object initialized on class initialization the object creation too are thread-safe.
  4. Singleton instance variable will never be created and or initialized until getInstance() is invoked. And again since class initialization is thread-safe the instance variable of IntiailizationOnDemandClassholder will be loaded safely, once and is visible to all threads.
public class Singleton {
    private Singleton(){}

    public static class lazySingletonClass{
      private static final Singleton INSTANCE = new Singleton();
    }

    public Singleton getInstance(){
        return lazySingletonClass.INSTANCE;
    }
}
When Object is Created Thread Safe Performance Comments
Eager Initialization Object Gets Created once the Class is Loaded Yes Bad Object is created everytime when the class is accessed
Lazy Initialization Object is Created once required No In lazy initialization you give a public API to get the instance. In multi-threaded environment it poses challenges to avoid unnecessary object creation
Static Block Initialization Object is Created once Static Block is loaded Yes Bad Not a good idea to load resources from static block as it causes performance hit during app startup
Synchronized Method Object is Created once getInstance is called Yes Bad Thread safety is guaranteed.Slow performance because of whole method locking is done
Synchronized Block Object is Created once getInstance is called No Two singleton instances may be created when context switching happens after checking instance is null
Double Checked Locking Object is Created once getInstance is called Yes Good Instance check is done twice
Enum Implementation Object Created using enum is referenced Yes Good
Initialization on demand holder idiom Object Created when static class is initiazlied by calling getInstance method Yes Good Class initialization is inherently thread-safe and if you can have an object initialized on class initialization the object creation too are thread-safe

Note
Dont be confused between Class Loading and Initialization. In the Initialization on demand holder method of singleton you can easily get confused as the static inner class wont be loaded when the outer class loads. The implementation relies on the fact that during initialization phase of execution within the Java Virtual Machine (JVM) as specified by the Java Language Specification (JLS) When the class Singleton is loaded by the JVM, the class goes through initialization. Since the class does not have any static variables to initialize, the initialization completes trivially. The static class definition lazySingletonClasswithin it is not initialized until the JVM determines that lazySingletonClassmust be executed. The static class lazySingletonClassis only executed when the static method getInstance is invoked on the class

The static class lazySingletonClass is only executed when the static method getInstance is invoked on the class Singleton , and the first time this happens the JVM will load and initialize the lazySingletonClass class. The initialization of the lazySingletonClassclass results in static variable INSTANCE being initialized by executing the (private) constructor for the outer class Something. Since the class initialization phase is guaranteed by the JLS to be sequential, i.e., non-concurrent, no further synchronization is required in the static getInstance method during loading and initialization

31.How will you make a HashMap of Unique Objects(Object with same Attributes should not be added more than once) or Mutable class does not allow override of HashCode and Equals?

If two objects are same then they must return same value in hashcode() and equals() method whenever invoked.It is not necessary that two different object must have different hashcode values. it might be possible that they share common hash bucket.

JVM assigns unique hashcode value to each object when they are created in memory and if developers don’t override the hashcode method then there is no way the two object returns same hashcode value.

Without HashCode

package com.mugil.org.qs;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Question31 
{
	public static void main(String[] args) 
	{
		Map hmStudents = new HashMap();
		
		Student objStudent1 = new Student();
		objStudent1.setName("Abdul");
		objStudent1.setAge(23);
		
		hmStudents.put(objStudent1, "Playboy");
		
		Student objStudent2 = new Student();
		objStudent2.setName("Joseph");
		objStudent2.setAge(23);
		
		hmStudents.put(objStudent2, "Upcoming Playboy");
		
		
		Student objStudent4 = new Student();
		objStudent4.setName("Joseph");
		objStudent4.setAge(23);
		
		hmStudents.put(objStudent4, "Playboy");
		
		
		Iterator it = hmStudents.entrySet().iterator();
		
	    while (it.hasNext()) 
	    {
	        Map.Entry pair = (Map.Entry)it.next();
	        System.out.println(((Student)pair.getKey()).getName() + " = " + pair.getValue());
	        
	    }
	}
}

class Student
{
	String Name;
	Integer Age;
	
	public String getName() {
		return Name;
	}
	public void setName(String name) {
		Name = name;
	}
	public Integer getAge() {
		return Age;
	}
	public void setAge(Integer age) {
		Age = age;
	}	
}

Output
Joseph = Playboy
Abdul = Playboy
Joseph = Upcoming Playboy

With HashCode Object with same value gets replaced

class Student
{
	String Name;
	Integer Age;
	
	public String getName() {
		return Name;
	}
	public void setName(String name) {
		Name = name;
	}
	public Integer getAge() {
		return Age;
	}
	public void setAge(Integer age) {
		Age = age;
	}
	
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((Age == null) ? 0 : Age.hashCode());
		result = prime * result + ((Name == null) ? 0 : Name.hashCode());
		return result;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (Age == null) {
			if (other.Age != null)
				return false;
		} else if (!Age.equals(other.Age))
			return false;
		if (Name == null) {
			if (other.Name != null)
				return false;
		} else if (!Name.equals(other.Name))
			return false;
		return true;
	}	
}

Output
Joseph = Playboy
Abdul = Playboy

32.Why List<Parent> is not same as List<Child> ?
Let’s say we allow a List to be a subtype of List.Consider the following example:We allow a List to be a subtype of List. Consider the following example:

   List<String> stringList = new ArrayList<String>;
   List<Object> objectList = stringList; //this does compile only if List<String> where subtypes of List<Object>
   objectList.add(new Object());
   String s = stringList.get(0);// attempt to assign an Object to a String and the Java compiler has to prevent these cases.

In the above code you can see adding Parent and Child class within the same List may result in scenario where you wont be
able to guess whether its a Parent or Child.

If Foo is a subtype (subclass or subinterface) of Bar, and G is some generic type declaration, it is not the case that G is a subtype of G.

It’s useful to make comparison to arrays.
List is not subclass of List But Dog[] is subclass of Animal[]
Arrays are reifiable and covariant. Reifiable means their type information is fully available at runtime. Therefore arrays provide runtime type safety but not compile-time type
safety.

   // All compiles but throws ArrayStoreException at runtime at last line
    Dog[] dogs = new Dog[10];
    Animal[] animals = dogs; // compiles
    animals[0] = new Cat(); // throws ArrayStoreException at runtime

It’s vice versa for generics:Generics are erased and invariant. Therefore generics can’t provide runtime type safety, but they provide compile-time type safety.
In the code below if generics were covariant it will be possible to make heap pollution at line 3.

    List<Dog> dogs = new ArrayList<>();
    List<Animal> animals = dogs; // compile-time error, otherwise heap pollution
    animals.add(new Cat());

 

33.What is the difference between instanceof and getclass()
instanceof tests whether the object reference on the left-hand side (LHS) is an instance of the type on the right-hand side (RHS) or some subtype.
getClass() == … tests whether the types are identical.

34.What are different reference types in java

  1. Strong References : We can create an object and then assign it to a reference. Note that if the object has a strong reference, this object is never be garbage collected.
    MyClass obj = new MyClass ();  
    
  2. Weak References :This type of reference is used in WeakHashMap to reference the entry objects.If JVM detects an object with only weak references (i.e. no strong or soft references linked to any object object), this object will be marked for garbage collection.
  3. Soft References :even if the object is free for garbage collection then also its not garbage collected, until JVM is in need of memory badly.The objects gets cleared from the memory when JVM runs out of memory
  4. Phantom References :A special reference which says that the object was already finalized, and the garbage collector is ready to reclaim its memory.Before removing them from the memory, JVM puts them in a queue called ‘reference queue’ . They are put in a reference queue after calling finalize() method on them

35.Difference betwen connection timeout and socket timeout?
A connection timeout is the maximum amount of time that the program is willing to wait to setup a connection to another process.A connection timeout occurs only upon starting the TCP connection. This usually happens if the remote machine does not answer. This means that the server has been shut down, you used the wrong IP/DNS name or the network connection to the server is down.
A socket timeout is the timeout when waiting for individual packets. A socket timeout is dedicated to monitor the continuous incoming data flow. If the data flow is interrupted for the specified timeout the connection is regarded as stalled/broken. if you have a socket timeout of 1 second, and a response comprised of 3 IP packets, where each response packet takes 0.9 seconds to arrive, for a total response time of 2.7 seconds, then there will be no timeout.

36.Why we need to do serialization when the same can be done by using file streams?
Serialized objects maintain state in space, they can be transferred over the network, file system, etc
you could save your data to a text file on the computer, then have a program that reads that info, and based on the file, you could have your
program respond differently. if you use Serializable then you can easily load your Object graph to memory. For example you have a Student class
which have a Deportment. So if you serialize your Student then the Department also be saved.

Serializing on the other hand, puts things directly into computer language. It’s like you’re telling a Spanish computer something in Spanish, rather than telling it something in French, forcing it to learn French, then save things into its native Spanish by translating everything.
Serialization is also faster, because in Java, objects are handled on the heap, and take much longer than if they were represented as primitives on the stack.

37.What is Functional Interface?
Functional interfaces have a single functionality to exhibit. For example, a Comparable interface with a single method compareTo is used for comparison purpose
Functional Interface is an interface which has one and only one abstract method. Apart from abstract method it can have any number of default and static methods which have an implementation and are not abstract and overriden method from Object.These interfaces are also called Single Abstract Method Interfaces. Few Functional Interfaces are Comparable, Runnable etc.More details here

38.What are marker interfaces?
Marker Interface in java is an interface with no fields or methods within it. It is used to convey to the JVM that the class implementing an interface of this category will have some special behavior.

Few Marker interface are as below

  1. Searilizable interface
  2. Cloneable interface
  3. Remote interface used for RMI
  4. ThreadSafe interface

Marker interface in Java e.g. Serializable, Clonnable, and Remote are used to indicate something to compiler or JVM that the class implementing any of these would have some special behavior. Hence, if the JVM sees a Class is implementing the Serializable interface it does some special operation on it and writes the state of the object into object stream. This object stream is then available to be read by another JVM. Similarly, if JVM finds that a class is implementing Cloneable interface, it performs some special operation in order to support cloning.

39.What is the Difference between String Literal and String Object?How it is stored in memory?

String s1 = "abc"; 
String s2 = "123";
String obj1 = new String("abc");
String obj2 = new String("def");
String obj3 = new String("456);

JVM allocates some memory specially meant for string literals. This part of the heap memory is called string constants pool.String literals s1 and s2 will go to string constant pool, objects obj1, obj2, obj3 to the heap. All of them, will be referenced from the Stack.”abc” will appear in heap and in string constant pool. Why is String s1 = “abc” and String obj1 = new String(“abc”) will be created this way? It’s because String obj1 = new String(“abc”) explicitly creates a new and referentially distinct instance of a String object and String s1 = “abc” may reuse an instance from the string constant pool if one is available.

40.What are ways of object creation in Java?

  1. Using new Keyword

    Employee objEmp = new Employee(); 
    
  2. Using newInstance

    Class cls = Class.forName("Employee"); 
    Employee obj =  (Employee) cls.newInstance(); 
    
  3. Using clone() method

    public class Employee implements Cloneable 
    { 
        @Override
        protected Object clone() throws CloneNotSupportedException 
        { 
            return super.clone(); 
        }     
      
        public static void main(String[] args) 
        { 
            Employee obj1 = new Employee(); 
            try
            { 
                Employee obj2 = (Employee) obj1.clone();       
            } 
            catch (CloneNotSupportedException e) 
            { 
                e.printStackTrace(); 
            } 
        } 
    } 
    
  4. Using deserialization
    Refere Here
  5. Using newInstance() method of Constructor class(Reflection)

    Constructor<Employee> constructor = Employee.class.getDeclaredConstructor();
    Employeer = constructor.newInstance();
    r.setName("GeeksForGeeks");
    System.out.println(r.name);
    

41.When overriding a method, why can I increase access but not decrease it?
It’s a fundamental principle in OOP: the child class is a fully-fledged instance of the parent class, and must, therefore, present at least the same interface as the parent class. Making protected/public things less visible would violate this idea; you could make child classes unusable as instances of the parent class. Lets take the below code

class Person{
 public void display(){
      //some operation
    }
 }

class Employee extends Person{
   private void display(){
       //some operation
   }
 }

Calling Overridden method

Person p=new Employee();

Here p is the object reference with type Person(superclass) when we are calling p.display(). As the access modifier is more restrictive, the object reference p cannot access child object of type Employee

42.What if the same method is there in Abstract class and in interface?

public interface Intr {
    public void add();
}

public abstract class Abs {
    public void add() {
        System.out.println("Abs.m1()");
    }
    // public abstract void m1();
}

public class A extends Abs implements Intr {

    @Override
    public void add() {
        // which method am I overriding, well it is Abs.m1() but why?
        // if method implemented is Abs.add(), then why I am not getting error for Intr.add() not implemented.
    }
}

In the above implementation at the sametime, we are fulfilling the abstract class requirements and the interface requirements.it might make sense to move the implements Intr up to the abstract class definition. Though the abstract class method would be overridden first.

43.When you add a date Field to Immutable class despite it being declared as final it is modifiable as in below code, How will you create an immutable class with date field in it?

date = getDate();
date.setYear(2010); // allowed!

In the below code we have used defensive copying by sending the values of the date field and sending a copy of the date for accessing its value.

Solution

public Date getDate() {
    // Not correct.
    return this.date; // This will make your class mutable.

    // Instead use, 
    return new Date(this.date.getTime()); // This will make sure your date field cannot be changed.
}

44.What is Defensive Copying?
Lets take the code as below

class Point {
  final int x;
  final int y;

  Point(int x, int y) {
    this.x = x;
    this.y = y;
  }

  Point(Point p) {
    this(p.x, p.y);
  }
}
  1. In the above code note how the constructor Point(Point p) takes a Point and makes a copy of it – that’s a copy constructor.
  2. This is a defensive copy because the original Point is protected from change by taking a copy of it
// A simple point.
Point p1 = new Point(3,42);
// A new point at the same place as p1 but a completely different object.
Point p2 = new Point(p1);

Using the above code you never have two references to the same object by accident