Tuesday, February 7, 2017

Garbage Collector and its Algorithms - JAVA

-------------------Garbage Collection-----------------------
In java , programmer need not to care about the objects which are no longer in use. garbage collector
destroy those objects and make the memory available for the programmer to use again.
- garbage collector not guaranteed to run at any specific time.
there are few method of garbage collector



------------The finalize () method:
Called by the garbage collector on an object when garbage collector determines that there are no more references to the object
Note :

The finalize method is never invoked more than once by a Java virtual machine for any given object.
Our program must not rely on the finalize method because we never know if finalize will be executed or not.

----------------gc() – request to JVM

We can request to run the garbage collector using java.lang.System.gc() but it does not force garbage collection, the JVM will run garbage collection only when it wants to run it.­­
We may use system.gc() or runtime.gc()
import java.lang.*;
public class Test
{
    public static void main(String[] args)
    {
        int g1[] = { 0, 1, 2, 3, 4, 5 };
        System.out.println(g1[1] + " ");

        // Requesting Garbage Collector
        System.gc();
        System.out.println("Hey I just requested "+
                          "for Garbage Collection");
    }
}

--------What happens when group of object only refer to each other?

It is possible that a set of unused objects only refer to each other.
This is also referred as Island of Isolation.
For example, object o1 refers to object o2. Object o2 refers to o1. None of them is referenced by any other object.
In this case both the objects o1 and o2 are eligible for garbage collection.


-------------------ALGORITHM USED BY Garbage Collector to remove objects.
Garbage Collector uses 2 alogrithm to remove objects

* Mark and sweep Algorithm
* Island of isolation


-------------------Mark and sweep alogrithm-------------
The main activity of garbage collector is to first identify the unused objects and them claim the head memory to available for use.
There are 2 phase to perform in marks and sweep alogrithm-
1) mark phase
2) sweep phase

In Mark Phase , whenever any object is created its mark bit is set to be false (0) , so in mark phase we set all the reachable object marked bit as true(1),
to perfome is operation , we simply do graph traversal , deepth first search in particular, here we consider all objects as nodes ,and all the nodes connected to one nodes are visited and set as true.

Root is a variable that refer to an object and is directly accessible by local variable. We will assume that we have one root only.
We can access the mark bit for an object by: markedBit(obj).

In Sweep Phase : In sweep phase , all the unreachable objects are sweeped , i.e all the objects whose marked bits are false , will be remove heap memory.
and then the marked bit of all the reachable object will again sets as false , so that they will be again available to recurring process.


------------Island of Isolation -----------------------

Object 1 references Object 2 and Object 2 references Object 1. Neither Object 1 nor Object 2 is referenced by any other object. That’s an island of isolation.
Basically, an island of isolation is a group of objects that reference each other but they are not referenced by any active object in the application. Strictly speaking, even a single unreferenced object is an island of isolation too.

Design Pattern

Design Pattern
-----------------
* Creatational Design Pattern- the way to create object.
used when we need to make decision for creating the instance of class.
Type-
1) Factory Design pattern- It says that let create the abstract class or interface for creating an object but let the subclass decide which class to instanciated.
 * also known as virtual constructor

 Ex -

 package inv.learning.designpattern;


interface Animal{

String name="";
String getType();

}
class Dog implements Animal{

@Override
public String getType() {
// TODO Auto-generated method stub
return "Dog";

}

}
class Cat implements Animal{

@Override
public String getType() {
// TODO Auto-generated method stub
return "Cat";

}

}

class AnimalFactory{

static Animal getAnimal(String str){
if(str==null)
return null;
else if (str.equalsIgnoreCase("CAT"))
return new Cat();
else if (str.equalsIgnoreCase("DOG"))
return new Dog();
else
return null;
}

}
public class FactoryDesign {

public static void main(String[] args) {
// AnimalFactory factory = new AnimalFactory();
Animal dog = AnimalFactory
.getAnimal("Cat");
System.out.println(dog.getType());
Animal cat= AnimalFactory.getAnimal("DOG");
System.out.println(cat.getType());
}

}

------------------------------------------------------------------------------------------------------
2) Abstract Factory Pattern-define an interface or abstract class for creating families of related (or dependent) objects but without specifying their concrete sub-classes.



-------------------
3) Singleton Design pattern- define a class which only have one instance and provides a global  point of  access to it.

Ex -
public class Singleton {

public static void main(String[] args) {
MySingletonClass temp=MySingletonClass.getInstance();


}

}
class MySingletonClass {

private final static MySingletonClass myclass=null;
private MySingletonClass(){}
static MySingletonClass getInstance(){
if(myclass == null)
return new MySingletonClass();
else
return myclass;

}
}

----------------------------
3) Prototype design pattern- cloning of an existing object instead of creating new one and can also be customized as per the requirement.
we use this pattern when creating object is expensinve.
t reduces the need of sub-classing.
It hides complexities of creating objects.
The clients can get new objects without knowing which type of object it will be.
It lets you add or remove objects at runtime.

Example-

public class Prototype {
public static void main(String[] args) {
Employee emp= new Employee(10, "vishal", "g4s");
System.out.println("address of first emp object "+emp.address);
Employee emp2=(Employee)emp.getClone();
System.out.println("address of sec emp object "+emp2.address);
}
}
interface InfPrototype{
InfPrototype getClone();
}
class Employee implements InfPrototype
{ int age;
String name;
public String address;

public Employee(){

}
public Employee(int age,String name,String address)
{
this.age=age;
this.name=name;
this.address=address;
}
@Override
public InfPrototype getClone() {
// TODO Auto-generated method stub
return new Employee(age,name,address);
}

}
--------------------------------
4) Builder Design Pattern-  wehen we construct a complex object from simple object using step by step approach.
It provides clear separation between the construction and representation of an object.
It provides better control over construction process.
It supports to change the internal representation of objects.


-----------------------------------------------------------------------------------------------------------------------
STRUCTURAL DESIGN Pattern-simplifies the structure by identifying the relationships

1) Adapter Design Pattern- converts the interface of a class into another interface that a client wants
 it is also known as wrapper.
 When an object needs to utilize an existing class with an incompatible interface.
When you want to create a reusable class that cooperates with classes which don't have compatible interfaces.
When you want to create a reusable class that cooperates with classes which don't have compatible interfaces.



2)Bridge Pattern-Decouple the functional abstraction from the implementation so that the two can vary independently
The Bridge Pattern is also known as Handle or Body.

When you don't want a permanent binding between the functional abstraction and its implementation.
When both the functional abstraction and its implementation need to extended using sub-classes.
It is mostly used in those places where changes are made in the implementation does not affect the clients.

Thanks for reading
-Noeik

Breadth first Traversal(BFT) AND Depth First Traversal(DST) Program in java

Hello Guys , Hope you all are doing good , so today we are going to see the BST and DST Program in java.

Let see the implementation of BST and DST in single program


package inv.learning.searching;

import java.util.Iterator;
import java.util.LinkedList;

public class BFT {

public static void main(String[] args) {

Graph g = new Graph(5);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(0, 3);
g.addEdge(1, 4);
System.out.println("Breadth First Search --");
g.BST(0);

System.out.println("Depth first search --");
g.DST(0);

}
}
class Graph{

int V;
LinkedList adj[];

Graph(int v){
V=v;
adj = new LinkedList[v];
for(int i=0;i<v;i++)
{
adj[i]= new LinkedList<>();
}
}
public void addEdge(int v,int w)
{
adj[v].add(w);
}

public void BST(int s)
{
boolean[] visited = new boolean[V];
visited[s]=true;
LinkedList<Integer> queue= new LinkedList<>();
queue.add(s);
while(queue.size()!=0)
{
int n = queue.poll();
System.out.println(n+" ");
Iterator<Integer> itr = adj[n].listIterator();
while(itr.hasNext())
{
int i = itr.next();
if(!visited[i]){
visited[i]=true;
queue.add(i);
}

}
}

}
public void DST(int s){
boolean[]  visited = new boolean[V];

DSTUtil(s, visited);
}

public void DSTUtil(int s, boolean[] visited){
visited[s]=true;
System.out.println(s+" ");
Iterator itr = adj[s].listIterator();
while(itr.hasNext())
{
int i = (int) itr.next();
if(!visited[i])
{
DSTUtil(i, visited);

}
}


}


}

Output-

Breadth First Search --


Depth first search --


Thanks for reading
-Noeik

JVM - Classloading in java

Hello Everyone , Hope you all are doing good , Today we will learn about class loading in java , class loading is very basic topic which most of the programmer dont know, so lets see what and type of classloaders.

--jvm Class Loading---
Three activities while class loading
-loading
-linking
-initialization


Loading--- The class loader reads the .class files and generate the correposnidn binary data.

Let see this with example

import java.lang.reflect.Method;

public class ClassLoading {

public static void main(String[] args) {
Student s1= new Student();
Class c1= s1.getClass();

System.out.println(s1.getClass().getName());
Method[] m = s1.getClass().getMethods();
for(Method m1:m)
{
System.out.println(m1.getName());
}
Student s2 = new Student();
Class c2= s2.getClass();
System.out.println(c1==c2);
}


}


class Student {

String name;
int roll_no;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRoll_no() {
return roll_no;
}
public void setRoll_no(int roll_no) {
this.roll_no = roll_no;
}

}

Output----
inv.learning.jvm.Student
getRoll_no
setRoll_no
getName
setName
wait
wait
wait
equals
toString
hashCode
getClass
notify
notifyAll
true


NOTE: If we see the line System.out.println(c1==c2) it will give true that means Class c1 and Class c2 always point to same Class Object.
For every loaded .class file, only one object of Class is created.

--------------------------------------------------------
Linking-- Performs verification, preparation, and (optionally) resolution.
Verification : Its ensure the correctness of .class file if not generated by valid compile it will give the runtime exception.
Preparation : JVM allocates memory for class variables and initializing the memory to default values.
Resolution : It is the process of replacing symbolic references from the type with direct references. It is done by searching into method area to locate the referenced entity.

----------------------

Initialization:- In this phase all the static variable and static blocked get the assigned values in the code , it executed from top to bottom and from parent to child.
basically there are 3 type of class loader.
1) Bootstrap class loader- These class loader is essential used to load the trusted classes. Like all the native java api classes which are defined in JAVA_HOME/jre/lib.
2)Extension class loader- child of bootstrap class loader , load all the class of JAVA_HOME/jre/lib/ext .
3) Application class loader - child of extension class loader , used to load the application .class files.

package inv.learning.jvm;

public class ClassLoadingDemo {

public static void main(String[] args) {

// String class is loaded by bootstrap loader, and
        // bootstrap loader is not Java object, hence null
System.out.println(String.class.getClassLoader());

System.out.println(ClassLoadingDemo.class.getClassLoader());
}
}

Thanks for reading
-Noeik

Monday, February 6, 2017

Polymorphism and its type-Java

Hello guys , today we will read about one important characteristice of oops i.e Polymorphism

--polymorphism---

One thing in many form
or
The ability to appear in more than one form

In Java there are 2 type of polymorphism
-compiler time polymoriphism (static binding) -achieved by method overloading

-runtime polymorphism(dynamic binding) -achieved by method overriding

---Overloading---------------
there are 2 type of overloading in java
-method overloading
-constructor overloading
-operator overloading

-------------------------------Method Overloading----------------------------------
If the class contains more than one method with same name and different no. of arguments(return type is not consider in overloadding) or same no. of argument with different data types.
Ex -
class c{
void m1(int a)
void m1(int a , int b)
void m2(char c)
void m2(String str)

}
Method signature - method name and paramters is metehod signature
Real time example-
for Adhar Card we have few options to get the duplicate adhar card
we can provide- dob and name
pan no
name and father name
so here we will use method overloading as we dont know what the user is going to give to fetch its information.

--------------------------------Constructor Overloading--------------
Same constructor name with different no. of arguments or same constructor with same no. of arguments with different data type.

Ex-
class Test
{
Test(int i)
{
syso("one arg constructor with int");
}
Test(int i, int k)
{
syso("2 arg constructor with int");
}
Test(char cs)
{
syso("one arg constructor with char");

}
main()
{
Test t=new Test(1);
Test t1 = new Test(1,2);
Test t3 =new Test('r');

}
}
------------------operator overloading--------------
one operator with more than one behaviour
no java is not supported operator overloading

Only one operator + is defined in java implisitly

Root class of all class is object class
Default package in java is java.lang package


-----------------------------Method Overriding-----------------------------------
To Achieve the overriding we required 2 java classes with inheritance concept

Overriden class is the parent class whose method is going to override
overriding class is the child class whose method will override the parent method
There are some rules of Method Overriding
1) Overridden method signature and child class method signature must be same
2) Return type of both the method must be same at primitive level
3)co varint return type in which the parent class has parent return type and class method is having the sub type of parent return type
4) if a method is declared as final overriding is not possible
-final class methods are final(bcz if it is not a final we will be able to override) but variable is not final
5) static method can't be override
6)child class is not able to hold the parent reference object
ex - Child child = new Parent() // invalid


Hope these points will help you in your preparation .

Thanks for reading
-Noeik



Thursday, February 2, 2017

Basic and tricky java Interview Questions

Hi guys , Hope you all are doing good , Today I am going to share few tricky questions which i felt everyone who is preparing for java interview should know. So lets see

Q1) Difference between new operator and newInstance() method ?/
-    new is used when we know the type of class instance know at design time.
     if you dont know then we use newInstance method
    ex-
     Student std = new Student();
      Object o = Class.forName(arg[0]).newInstance();


Q2) classNotFoundException vs NoClassDefFoundException
       when we write like this
      Test test= new Test();
      and the Test.class file is not found then at runtime we will get NoClassDefException found.                (unchecked exception)
         Object o = Class.forName(args[0]).newInstance();
        will get the ClassNotFoundException (checked exception)



Q3) Diff b/w checked and unchecked exception
exception which are be checked by compiler  how to handle the expection. for the smooth execution of program.
ex- FileNotFoundException is checked exception , compiler ask to handle the exception while compile.
exception which are not checked by compiler
ArthematicException is unchecked exception.


control flow of try catch
if exception in araised in catch block it is abnormal exception

variable combination of try catch final block
- try catch
-try catch catch(catch should be in child to parent heirarchy)
try final
try catch final


------------------String---------------
Why String is always final in java - due to immutability ,security (thread safe) etc
Why we use character array over string to store password ?
-as string is immutable and it is persist till the garbage collector called . As data is stored for long time because string pool used the string data
- if we use JPasswordField then it will also return array[] for getPassword() and depricated getText() field

--------------String Pool-----------------
Why we use string pool ?
String pool is used to store the references of the strings
Ex-
String s=“prasad”;
String s1=“prasad”;
System.out.println(s==s1)  // output  true;

The class is loaded when JVM is invoked.
JVM will look for all the string literals in the program
First, it finds the variable s which refers to the  literal “prasad” and it will be created in the memory
A reference for the literal “prasad” will be placed in the string constant pool memory.
Then it finds another variable s2 which is referring to the same string literal “prasad“.
Now that JVM has already found a string literal “prasad“, both the variables s and s2 wil refer to the same object i.e. “prasad“.
----intern() --------------
intern method check whether the string is present in spring pool if yes then return the reference of the string otherwise create new string object
Ex-
String s ="prasad";
String s1="prasad".intern();
System.out.println(s==s1)  // output true
System.out.println(s.equals(s1));   // output true

String s ="prasad";
String s1="prasad1".intern();
System.out.println(s==s1)  // output false
System.out.println(s.equals(s1));   // output false

---------------------------

Difference btw encapculation & abstraction(how to achieve abstraction using encp)
- by decreasing the scope of behaviour(methods)
encapsulation - wrapping of data and associated func into a single unit is encp -(class)
Ex-
if we have one function which will call the other function so we can scope down the other function to achieve abstraction

Class A{

public void m1()
{
m4internal();
}
public void m2()
{
}
}
Class B{

protected void m4internal()

}

Hope these will be helpful for you , if you have any problem , do let me know

Thanks for Reading
-Noeik