Abstract Factory Pattern
The Abstract Factory Pattern consists of an AbstractFactory, ConcreteFactory, AbstractProduct, ConcreteProduct and Client. We code against AbstractFactory and AbstractProduct and let the implementation to others to define ConcreteFactory and ConcreteProduct

Why Abstract Factory Introduced?
Another layer of abstraction over factory pattern. Abstract Factory patterns work around a super-factory which creates other factories. Factory pattern deals with creating objects of a single type(AppleFactory manufactures Iphones), while the Abstract Factory pattern deals with creating objects of related types(MobileFactory manufactures Mobiles). Abstract Factory pattern is more robust and consistent and uses composition to delegate responsibility of object creation.

When to use Abstract Factory?
When higher level of Abstraction is required.Provides an interface for creating families of related objects

MobileManufactureFactory.java

public interface MobileManufactureFactory {
    public Mobiles getManufacturerDetails();
}

Mobiles.java

public interface Mobiles {
    public void getMobileModels();
}

AppleFactory.java

public class AppleFactory implements MobileManufactureFactory {
    @Override
    public Mobiles getManufacturerDetails() {
        return new Iphone();
    }
}

GoogleFactory.java

public class GoogleFactory implements MobileManufactureFactory {
    @Override
    public Mobiles getManufacturerDetails() {
        return new Android();
    }
}

MicrosoftFactory.java

public class MicrosoftFactory implements MobileManufactureFactory {
    @Override
    public Mobiles getManufacturerDetails() {
        return new Windows();
    }
}

IphoneMobiles.java

public class IphoneMobiles implements Mobiles {
    @Override
    public void getMobileModels() {
        System.out.println("Iphone 13,14 and 15");
    }
}

AndroidMobiles.java

public class AndroidMobiles implements Mobiles {
    @Override
    public void getMobileModels() {
        System.out.println("Oneplus, Realme, Samsung");
    }
}

WindowsMobile.java

public class WindowsMobile implements Mobiles {
    @Override
    public void getMobileModels() {
        System.out.println("Samsung Focus, Nokia Lumia, Pocket PC");
    }
}

MobileFactory.java

public class MobileFactory {
    private MobileFactory(){
    }

    public static MobileManufactureFactory getMobilesBasedOnManufacturer(MobileCompany manufacturerName){
        if(manufacturerName.equals(MobileCompany.APPLE)){
            return new AppleFactory();
        }else if(manufacturerName.equals(MobileCompany.MICROSOFT)){
            return new MicrosoftFactory();
        }else if(manufacturerName.equals(MobileCompany.GOOGLE)){
            return new GoogleFactory();
        }
        return null;
    }
}

MobileCompany.java

public enum MobileCompany {
    APPLE, MICROSOFT, GOOGLE
}

Client.java

public class Client {
    public static void main(String[] args) {
        MobileManufactureFactory objMobileManufa = MobileFactory.getMobilesBasedOnManufacturer(MobileCompany.APPLE);
        Mobiles objMobile = objMobileManufa.getManufacturerDetails();
        objMobile.getMobileModels();
    }
}

Output

 Iphone 13,14 and 15

Class Loaders
Let’s take two simple Java Files as below

Helper.java

package com.mugil.org;
public class Helper {
	public String getMessage()
	{
		return "Helper Method";
	}
}

TestHelper.java

package com.mugil.org;
public class TestHelper {
	public static void main(String[] args) {
		Helper objHelper = new Helper();
		System.out.println(objHelper.getMessage());
	}
}

How to Compile class in Command Prompt
Normally when you compile Java class the class files would be created in bin folder with
the folder structure same as package name bin->com->mugil->org.
When you want the .class to be created in a specific folder then use the below command

D:\java\ClassLoaders>javac -d classes -sourcepath src src\com\mugil\org\Helper.java

Classes folder should be created manually or it’s going to throw
javac: directory not found: classes

Before Running the code the Classpath needs to be set which could be done either globally
by adding to the System classPath or locally at the application level

To Set globally the following should be run in Command Prompt

D:\java\ClassLoaders>set CLASSPATH=classes

After this, the Java code can be run as below

D:\java\ClassLoaders>java com.mugil.org.TestHelper
Helper Method

Setting Globally is not a good idea as other applications Classpath would be affected.If you
have set classpath globally chances are you may end up running wrong JAR file in the Classpath
The Better option is to set classpath while running the application itself

D:\java\ClassLoaders>java -cp classes com.mugil.org.TestHelper
Helper Method

Now let’s see how to take .class files in some other folder or .class files in JAR folder to

To run the .class file in other folders along with the one we are running adding the .class files separated by semicolon would be an easy way
as below

D:\java\ClassLoaders>java -cp D:\java\ClassLoaders\classes;D:\class1; com.mugil.org.TestHelper
Helper Method

The Helper.class is moved to D:\class1 folder and TestHelper.class is in D:\java\ClassLoaders\classes folder
TestHelper.class needs Helper.class to run.

Now how about JAR Files

D:\class1>jar cvf helper.jar com\mugil\org\Helper.class
added manifest
adding: com/mugil/org/Helper.class(in = 296) (out= 227)(deflated 23%)

To run the classes in the JAR Files the same command applies.D:\class1 is the location where the JAR’s are located(helper.jar).

D:\java\ClassLoaders>java -cp D:\java\ClassLoaders\classes;D:\class1; com.mugil.org.TestHelper
Helper Method

Once the JAR is created the .class files can be deleted and added to lib folder

While Creating JAR make sure you maintain the folder structure.Creating JAR file without adding com\mugil\org folder will result in classNotFound Exception

D:\java\ClassLoaders>java -cp D:\java\ClassLoaders\classes\lib\Helper.jar;D:\java\ClassLoaders\classes\; com.mugil.org.TestHelper

Class loaders are the part of the Java Runtime Environment that dynamically loads Java classes into the Java virtual machine. It is responsible for locating libraries, reading content and loading the classes contained within the libraries. When JVM is started three class loaders are used

How ClassLoaders works

  1. When JVM requests for a class, it invokes loadClass function of the ClassLoader by passing the fully classified name of the Class.
  2. loadClass function calls for findLoadedClass() method to check that the class has been already loaded or not. It’s required to avoid loading the class multiple times.
  3. If the Class is not already loaded then it will delegate the request to parent ClassLoader to load the class.
  4. If the parent ClassLoader is not finding the Class then it will invoke findClass() method to look for the classes in the file system.

1. Bootstrap class loader (Written in C)
2. Extensions class loader (Written in Java)
3. System or Application class loader (Written in Java)

Apart from CLASSPATH java looks into two other locations to load the JAR Folder
C:\Program Files\Java\jdk1.8.0_111\jre\lib in JRE installation Folder
C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext

Bootstrap class loader
It loads JDK internal classes, typically loads rt.jar and other core classes for example java.lang.* package classes

rt.jar is one of the JAR files in JRE Folder. You can see the content in rt.jar by renaming it into rt.jar.
rt.jar is loaded by the bootstrap class loader.

Extensions class loader
It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory.
You can add your JAR files like DB Connection JAR in the EXT folder and would be available to all application which runs on JVM

helper.jar added to ext folder

D:\java\ClassLoaders>java -cp D:\java\ClassLoaders\classes;D:\class1; com.mugil.org.TestHelper
Helper Method

D:\java\ClassLoaders>java -cp D:\java\ClassLoaders\classes; com.mugil.org.TestHelper
Helper Method

Note:In the second statement the D:\class1 is missing which has the JAR files which is now moved to EXT folder.No need to specify the JAR files as JAR files in EXT are loaded by default

System (or) Application class loader
System or Application class loader and it is responsible for loading application specific classes from CLASSPATH environment variable, -classpath or -cp command line option, Class-Path attribute of Manifest file inside JAR.

Delegation of Classes

  1. Delegation Classes are classes which delegates the call to its Parent Class which inturn Delegates to its Parent
  2. Each class loader has a parent. Class Loaders may delegate to its Parent. Parent may or may not load the class
  3. Loaded classes are always cached
  4. Application loader asks the Extension Class loader which inturn asks Bootstap loader
  5. If Bootstap loader couldnt find the class it will send fail message which makes the Extension Class loader to search for classes within
  6. If Extension loader couldnt find the class it will send fail message to Application Class Loader and makes to search for classes within
  7. If Application Class loader couldnt find the class NoClassDefinition Error would be Displayed

import java.net.URLClassLoader;

public class Delegation 
{
	public static void main(String[] args) 
	{
		URLClassLoader classloader = (URLClassLoader)ClassLoader.getSystemClassLoader();
		
		do {
			System.out.println(classloader);
		} while ((classloader = (URLClassLoader)classloader.getParent()) != null);
		
		System.out.println("Bootstrap ClassLoader");
	}
}

Output

sun.misc.Launcher$AppClassLoader@1497b7b1
sun.misc.Launcher$ExtClassLoader@749cd006
Bootstrap ClassLoader

To See the location of the Class Files loaded you can use the below code

.
.
do {
			System.out.println(classloader);
			
			for(URL url : classloader.getURLs())		
			 System.out.println("\t %s"+ url.getPath());
			
		} while ((classloader = (URLClassLoader)classloader.getParent()) != null);
.
.

Output

sun.misc.Launcher$AppClassLoader@1497b7b1
	 %s/D:/java/ClassLoaders/bin/
sun.misc.Launcher$ExtClassLoader@749cd006
	 %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/access-bridge-64.jar
	 %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/dnsns.jar
	 %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/jaccess.jar
	 %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/localedata.jar
	 %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/sunec.jar
	 %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/sunjce_provider.jar
	 %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/sunmscapi.jar
	 %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/zipfs.jar
Bootstrap ClassLoader

In the above Output, you can see the Application Class Loaders loads the Java class from the Project Directory and EXT jars from the EXT C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/ Folder

Why we need Custom ClassLoader?
Whenever a class is referenced in a java program it is loaded using JVM’s bootstrap class loader. This often becomes a problem when two different classes with same name and same package declaration are to be loaded. For example relying on JVM’s class loader one cannot load two different versions of the same JDBC driver. The work around to this problem is lies in making a custom class loader and loading classes directly from JAR archives.

Other Reasons

  1. Better Memory Management Unused modules can be removed which unloads the classes used by that module, which cleans up memory.
  2. Load classes from anywhere Classes can be loaded from anywhere, for ex, Database, Networks, or even define it on the fly.
  3. Runtime Reloading Modified Classes Allows you to reload a class or classes runtime by creating a child class loader to the actual class loader, which contains the modified classes.Hot Deployment
  4. Provides Modular architecture Allows to define multiple class loader allowing modular architecture.
  5. Support Versioning Supports different versions of class within same VM for different modules. Multiple Version Support
  6. Avoiding conflicts Clearly defines the scope of the class to within the class loader.
  7. Class loading mechanism forms the basis of Inversion of Control

Simple URL Class Loader
In the below example we are using URL Class Loading method to load the Classes from the JAR file.We can load Classes from File Based URL or Network Based URL
We can also load class from DB

SimpleClassLoader.java

public class SimpleClassLoader {
	public static void main(String[] args) {
		URL url;
        try {
            url = new URL("file:///D:/jars/helper.jar");
            URLClassLoader ucl = new URLClassLoader(new URL[]{url});
            Class clazz = ucl.loadClass("com.mugil.org.Helper");
            Object o = clazz.newInstance();
            Helper objHelper = (Helper)o;
            System.out.println(o.toString());
    		System.out.println(objHelper.getMessage());            
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
	}
}

Output

Helper Method
com.mugil.org.Helper@4631c43f

Note: In the above example you can see the Typecasting from Object to Helper which again makes the code tightly coupled and defeats the purpose of the class loader dynamically loads Java classes into the Java Virtual Machine. To resolve this issue we can use Interface which is loaded by application class loader with the implementing class loaded by our own class loader.

Account.java

public interface Account {
	public Integer getInterestRate(); 
}

SavingsAccount.java

public class SavingsAccount implements Account {
	@Override
	public Integer getInterestRate() {
		return 10;
	}
}

Implementation classes added to our JAR so it can be loaded by our Class Loader

D:\java\ClassLoaders\bin> jar cvf Accounts.jar com\mugil\org\SavingsAccount.class
added manifest
adding: com/mugil/org/SavingsAccount.class(in = 496) (out= 301)(deflated 39%)

CalculateInterest.java

public class CalculateInterest {
	public static void main(String[] args) 
	{
		URL url;
        try {
            url = new URL("file:///D:/jars/Accounts.jar");
            URLClassLoader ucl = new URLClassLoader(new URL[]{url});
            Class clazz = ucl.loadClass("com.mugil.org.SavingsAccount");
            Account o = (Account)clazz.newInstance();            
            System.out.println(o.toString());
    		System.out.println(o.getInterestRate());            
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
	}
}	

In the above code I can change the logic interest is calculated in the SavingsAccount and redeploy the JAR without taking effect in other parts of the program.

The above jar file could be loaded accross network by giving URL as below

.
.
URL url = new URL("http://localhost:8080/Accounts.jar");
.
.

Multiple version Support of Same JAR

Java bytecode is universal across platforms, you can use it to instrument classes on any system: a measure which methods are called, suppress security-critical calls, divert System.out accesses to your own custom logging routines, or perform advanced dynamic bug-testing routines.

	public static void main(String[] args) {
		try { 
            URL url1 = new URL("file:///D:/jars/Accounts1.jar"); 
            URLClassLoader ucl1 = new URLClassLoader(new URL[]{url1}); 
            Class clazz1 = Class.forName("com.mugil.org.SavingsAccount", true, ucl1);
            Account quote1 = (Account) clazz1.newInstance();

            URL url3 = new URL("file:///D:/jars/Accounts.jar");
            URLClassLoader ucl3 = new URLClassLoader(new URL[]{url3});
            Class clazz2 = Class.forName("com.mugil.org.SavingsAccount", true, ucl3);
            Account quote2 = (Account) clazz2.newInstance();

            System.out.printf("clazz1 == clazz2? %b\n", clazz1 == clazz2);
            System.out.printf("quote1.class == quote2.class? %b\n", quote1.getClass() == quote2.getClass());

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
	}

Output

clazz1 == clazz2? false
quote1.class == quote2.class? false

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 overridden method from Object.These interfaces are also called Single Abstract Method Interfaces. Few Functional Interfaces are Comparable, Runnable and etc.

Example of Functional Interface

@FunctionalInterface
public interface MyFunctionalInterface 
{
	public void MethodOne(int i, double d);
} 
@FunctionalInterface
public interface MyFunctionalInterface 
{
	public void MethodOne(int i, double d);
	
	default boolean methodTwo(String value) 
	{
        return true;
  }
} 

@FunctionalInterface annotation is used to mark an interface as Functional Interface
not mandatory to use it. If the interface is annotated with @FunctionalInterface annotation and when we
try to have more than one abstract method, it throws the compiler error.

There are two ways the abstract method definition in the functional interface could be done

One is by Anonymous Inner class and other is by Lambda Expression

For example in Java, if we have to instantiate runnable interface anonymously, then our code looks like below. It’s bulky

Anonymous Inner class way of method definion for Functional Interface

Runnable r = new Runnable(){
 @Override
 public void run() 
 {
	System.out.println("My Runnable");
 }};

lambda expressions for the above method implementation is

Lambda Expressions way of method definion for Functional Interface

Runnable r1 = () -> {
 System.out.println("My Runnable");
};

Functional interface with abstract method(oneMethod) and default(getMulty), static methods(getSum) which have an implementation and are not abstract and methods overridden from Object Class(toString and equals).

@FunctionalInterface
public interface MyFunctionalInterface 
{
	public void oneMethod(int i, double d);
	public String toString();
	public boolean equals(Object o);

	public static int getSum(int a,int b)
        {// valid->method static
		return a+b;
	}

	public default int getMulty(int c,int d)
        {//valid->method default
		return c+d;
        }
}

Functional Interface could be classified into the following 5 Types based on the parameters and the way the abstract method behaves

  1. Supplier
  2. Consumer
  3. Predicate
  4. Function
  5. Operator
Functional Interface Parameter Types Return Type Abstract Method Name Description
Runnable none void run Runs an action without arguments or return value
Supplier
none T get Supplies a value of type T
Consumer
T void accept Consumes a value of type T
BiConsumer
T, U void accept Consumes values of types T and U
Function
T R apply A function with argument of type T
BiFunction
T, U R apply A function with arguments of types T and U
UnaryOperator
T T apply A unary operator on the type T
BinaryOperator
T, T T apply A binary operator on the type T
Predicate
T boolean test A Boolean-valued function
BiPredicate
T, U boolean test A Boolean-valued function with two arguments

What is need for Default Method in Functional Interface?

  1. If we want to add additional methods in the interfaces, it will require change in all the implementing classes.
  2. As interface grows old, the number of classes implementing it might grow to an extent that its not possible to extend interfaces.
  3. That’s why when designing an application, most of the frameworks provide a base implementation class and then we extend it and override methods that are applicable for our application.
  4. “Default Method” or Virtual extension methods or Defender methods feature, which allows the developer to add new methods to the interfaces without breaking their existing implementation. It provides the flexibility to allow interface to define implementation which will use as the default in a situation where a concrete class fails to provide an implementation for that method.

Lets Imagine we have UserDevices which later wants to provide support for blackberry devices at later part of Software release. You cannot have a abstract method for blackberrySupport and make the implementing classes to do method definition.Instead of that I am writing as default method in interface which prevents all the implementing classes to write its own method definition.

public interface UserDevices {
    default void blackberrySupport(){
       System.out.println("Support for Blackberry Devices");
    }
}

public class Device implements UserDevices {
}

What if the class implements two interfaces and both those interfaces define a default method with the same signature?

public interface UserDevices1 {
    default void blackberrySupport(){
       System.out.println("Support for Blackberry Devices1");
    }
}

public interface UserDevices2 {
    default void blackberrySupport(){
       System.out.println("Support for Blackberry Devices2");
    }
}

public class Device implements UserDevices1 , UserDevices2 {
}

This code fails to compile with the following result:

java: class Device inherits unrelated defaults for blackberrySupport() from types UserDevices1 and UserDevices2 

In this case we have to resolve it manually by overriding the conflicting method

public class Device implements UserDevices1, UserDevices2  {
    public void blackberrySupport(){
       UserDevices1.super.blackberrySupport();
    }
}

The Best Example of Default Method is addition of foreach method in java.util.List Interface.

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.