Friday, November 3, 2017

Core Java Preparation_1 + Immutable + OOPS + Array + Collection




Page :
Immutable : 2
StringBuffer Equals method : 2
Local Variable: 35
Memory :
Modifiers: 44
Core java - Inheritance: 29
Copy Constructor : 60
clone: 61
Polymorphism : 51
Encapsulation : 55
Abstraction : 58
Arrays : 87
Generic : 70
Collection :71
Set : 54
HashSet works internally : 79
HasHMap : 80
equal : 91
HashCode : 91
Iterator : 85
comparable & Comparator : 122
Garbeg Collector : 105
Error :  100
Exception : 101
Immutable in String : 138
String : 132
Static : 147
Thread : 143
JVM : 163
Constructor : 166
Final : 193
impo Q : 153
Singleton Design pattern : 194
Project Details : 168
Serialization : 176
Externalizatio n : 180
--------------------------
Project Details : 221
Web Services : 236
Spring : 270
spring objective Questions: 330
Servlet & JSP: 238/9
DB : 331
hibernate : 344
Hibernate Cache :  344
Hibernate Criteria : 341
hibernat-Cascade: 350
Hibernate Transaction Management : 351
Batch-Processing :352
Core Java Programming : 372


Immutable :


package com.Immutable;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public final class DOB {
      
       private final String Fname;
       private final String Lname;
       private final Calendar myCalendar = new GregorianCalendar(2013, 04, 10);
       private final Date date = myCalendar.getTime();
      
       public DOB(String fname, String lname) {
              super();
              this.Fname = fname;
              this.Lname = lname;
              //this.date = date;
       }

       public String getFname() {
              return Fname;
       }

       public String getLname() {
              return Lname;
       }

       /*public Date getDate() {
              return date;
       }*/
      
       public Date getDate() {
              return new Date(date.getTime());
       }
      
}


package com.Immutable;

public class DOB_Main {

       public static void main(String[] args) {

              DOB dob = new DOB("Perwaiz", "Ali");
             
              dob.getDate().setYear(2017);
             
              System.out.println(dob.getFname()+" "+ dob.getLname()+ " "+ (1900+dob.getDate().getYear()));
             
       }

}

OUTPUT : Perwaiz Ali 2013

package com.Immutable;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public final class DOB {

private final String Fname;
private final String Lname;
private final Calendar myCalendar = new GregorianCalendar(2013, 04, 10);
private final Date date = myCalendar.getTime();

public DOB(String fname, String lname) {
super();
this.Fname = fname;
this.Lname = lname;
//this.date = date;
}

public String getFname() {
return Fname;
}

public String getLname() {
return Lname;
}

/*public Date getDate() {
return date;
}*/

public Date getDate() {
return new Date(date.getTime());
}


}











Immutable class User defined


package com.example.demo.immutable;
public class ImmutableClass {
private int id;
private String name;
private NoImmutableClass noImmutableClass;
public ImmutableClass(int id, String name, NoImmutableClass noImmutableClass) {
this.id = id;
this.name = name;
this.noImmutableClass = noImmutableClass;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
/*
* public NoImmutableClass getNoImmutableClass() { return noImmutableClass; }
*/
/* Making non changeable class, once assign value, it cannot be change */
public NoImmutableClass getNoImmutableClass() {
return new NoImmutableClass(name, name);
}
@Override
public String toString() {
return "ImmutableClass [id=" + id + ", name=" + name + ", noImmutableClass=" + noImmutableClass + "]";
}
}

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

package com.example.demo.immutable;

public class NoImmutableClass {

private String state;
private String country;

public NoImmutableClass(String state, String country) {
this.state = state;
this.country = country;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}

@Override
public String toString() {
return "NoImmutableClass [state=" + state + ", country=" + country + "]";
}

}

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

package com.example.demo.immutable;

public class ImmutableTest {

public static void main(String[] args) {

ImmutableClass immutableClass = new ImmutableClass(100,"Country",new NoImmutableClass("Maharastra","India"));
immutableClass.getNoImmutableClass().setCountry("USA");
System.out.println(immutableClass.toString());
}

}



StringBuffer Equals method




The equals method of StringBuffer is not overridden from Object, so it is just reference equality, i.e., the same as using ==. I suspect the reason for this is that StringBuffer is modifiable, and overriding equals is mostly useful for value-like classes that you might want to use as keys (though lists also have an overridden equals and StringBuffer is kind of a list, so this is a bit inconsistent).
1.  System.out.println(sb1 == sb2);  
StringBuffer's equals method returns true only when a StringBuffer object is compared with itself. It returns false when compared with any other StringBuffer, even if the two contain the same characters.
This is because "==" checks the reference equality and since both sb1 and sb2 are different object references, so the output in this case is "false"
Still if you want to check if the content is equal in these two StringBuffer Objects, you can use this:
sb1.toString().equals(sb2.toString())
 
2. System.out.println(sb1.equals(sb2));
This is giving output as "false" because .equals() method has not been overridden in the StringBuffer Class. So it is using the .equals() method from its parent "Object" class. In the object class .equals() has been written to check the reference equality.
Note that sb3.equals(sb4) will return "true" in case of String. Because .equals() method has been overridden in String class to check and match the content of two different Strings.

StringBuffer does not override the Object.equals method, so it is not performing a string comparison. Instead it is performing a direct object comparison. Your conditional may as well be if(s1==s2). If you want to compare the strings you'll need to turn the buffers into strings first.


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

Myth about the file name and class name in Java

The first lecture note given during java class is “In java file name and class name should be the same”. When the above law is violated a compiler error message will appear as below
/***** File name: Trial.java ******/
public class Geeks
{
   public static void main(String[] args) {
        System.out.println("Hello world");
   }
}
Run on IDE
Output:
javac Trial.java
Trial.java:9: error: class Geeks is public, should be
                    declared in a file named Geeks.java
public class Geeks
^
1 error 
But the myth can be violated in such a way to compile the above file.
/***** File name: Trial.java ******/
class Geeks
{
    public static void main(String[] args) {
        System.out.println("Hello world");
    }
}
Run on IDE
Step 1: javac Trial.java
Step1 will create a Geeks.class (byte code) without any error message since the class is not public.
Step 2: java Geeks
Now the output will be Hello world
The myth about the file name and class name should be same only when the class is declared in
public.
The above program works as follows :
Now this .class file can be executed. By the above features some more miracles can be done. It is possible to have many classes in a java file. For debugging purposes this approach can be used. Each class can be executed separately to test their functionalities(only on one condition: Inheritance concept should not be used).
But in general it is good to follow the myth.
For example:
/*** File name: Trial.java ***/
class ForGeeks
{
   public static void main(String[] args){
      System.out.println("For Geeks class");
   }
}

class GeeksTest
{
   public static void main(String[] args){
      System.out.println("Geeks Test class");
   }
}
Run on IDE
When the above file is compiled as javac Trial.java will create two .class files as ForGeeks.class and GeeksTest.class .
Since each class has separate main() stub they can be tested individually.
When java ForGeeks is executed the output is For Geeks class.
When java GeeksTest is executed the output is Geeks Test class.

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

Local Variables

·        Local variables are declared in methods, constructors, or blocks.
·        Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.
·        Access modifiers cannot be used for local variables.
·        Local variables are visible only within the declared method, constructor, or block.
·        Local variables are implemented at stack level internally.
·        There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use.

Example

Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to only this method.
public class Test {
   public void pupAge() {
      int age = 0;
      age = age + 7;
      System.out.println("Puppy age is : " + age);
   }
 
   public static void main(String args[]) {
      Test test = new Test();
      test.pupAge();
   }
}
This will produce the following result −
Output
Puppy age is: 7
                                    MEMORY








Modifiers









          Access
          Modifier
within class
within package
outside package by subclass only
outside package
    Private
Y
N
N
N
    Default
Y
Y
N
N
    Protected
Y
Y
Y
N
     Public
Y
Y
Y
Y


Java access modifiers with method overriding
If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.
1.      class A{  
2.      protected void msg(){System.out.println("Hello java");}  
3.      }  
4.        
5.      public class Simple extends A{  
6.      void msg(){System.out.println("Hello java");}//C.T.Error  
7.       public static void main(String args[]){  
8.         Simple obj=new Simple();  
9.         obj.msg();  
10.     }  
11.  }  
NOTE :- The default modifier is more restrictive than protected. That is why there is compile time error.




package com.Accessifier_Content;

public class Protected_Class_Test {
protected int number = 100;
protected void name(){
System.out.println("Ali");
}
}
------------------------
package com.Accessifier;

import com.Accessifier_Content.*;

public class Protected_Class_Test_Main extends Protected_Class_Test {

int num = super.number;
public static void main(String[] args) {

Protected_Class_Test_Main pctm = new Protected_Class_Test_Main();
int num = pctm.number;
}
}
--------------------------------------

package com.Accessifier_Content;

public class Protected_Class_Test_Main_2 {

public static void main(String[] args) {

Protected_Class_Test pct = new Protected_Class_Test();
int num = pct.number;
pct.name();
}
}


--------------------------------------------------------------------------------
package com.Accessifier_Content;

public class Car_3 {
int number_Default =100;
public int number_Defalt_Public = 200;
protected int number_Default_Protected = 300;
}

package com.Accessifier;

import com.Accessifier_Content.Car_3;

public class TestDefault_Extends extends Car_3{

public int speedTesT(){
return super.number_Default_Protected;
}
public static void main(String[] args) {
TestDefault_Extends tde = new TestDefault_Extends();
int number_Main = tde.number_Default_Protected;
Car_3 car_3 = new Car_3();
//car_3.number_Defalt_P
}
}



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

1)      Abstract Class and Interface
2)      OOPs
(a)Inheriteance
(c) Encapsulation
(b)Overloading and overriding(Polymorphism)
(d)Abstraction
3)      Collection
(a)General Collection Questions
(b)List
(c)Set
     i) HashSet
(d) Map
   i) HashMap--- Key
(e)Difference
(f)  HashSet works internally
(g) HashCode( ) and equal( )
(h) HashTable
(i) Comparable and Comparator
(j)Iterator
4)      Heap And Stack
5)      Garbage Collection
6)      Exception Handling
(a)   Chechked Exception
(b)   Unchecked Exception
(c)    Error
(d)   Name of all Exception
7)      String
8)      Static block
Abstract Class and Interface





Methods of Object class
The Object class provides many methods. They are as follows:

Method
Description
public final Class getClass()
returns the Class class object of this object. The Class class can further be used to get the metadata of this class.
public int hashCode()
returns the hashcode number for this object.
public boolean equals(Object obj)
compares the given object to this object.
protected Object clone() throws CloneNotSupportedException
creates and returns the exact copy (clone)
of this object.
public String toString()
returns the string representation of this
 object.
public final void notify()
wakes up single thread, waiting on this
object's monitor.
public final void notifyAll()
wakes up all the threads, waiting on this
object's monitor.
public final void wait(long timeout)throws InterruptedException
causes the current thread to wait for the
specified milliseconds, until another
thread notifies (invokes notify() or notifyAll()
method).
public final void wait(long timeout,int nanos)throws InterruptedException
causes the current thread to wait for
the specified milliseconds and nanoseconds,
until another thread notifies (invokes notify()
or notifyAll() method).
public final void wait()throws InterruptedException
causes the current thread to wait, until
another thread notifies (invokes notify() or
 notifyAll() method).
protected void finalize()throws Throwable
is invoked by the garbage collector before
object is being garbage collected.

OOPS

Inheritance


IS-A Relationship :
§  This refers to inheritance or implementation.
§  Expressed using keyword “extends”.
§  Main advantage is code reusability.
  • Whatever the parent class has, is by default available to the child. Hence by using child reference, we can call both parent and child class methods.
  • Whatever the child class has, by default is not available to parent, hence on the parent class  reference we can only call parent class methods but not child specific methods.
  • Parent class reference can be used to hold child class objects , but by using that reference we can call only parent class methods but not child specific methods.
  • We can't use child class reference to hold parent class objects
Entire java API is implemented based on inheritance. Every java class extends from Object class which has most common and basic methods required for all java classes. Hence we can say “Object ” class is root class of all java methods.
A point to remember on inheritance . A java class cannot extend more than one class at a time so it won't provide support for multiple inheritance in classes, but it can extend more than one interface at a time so we can say java provides support for multiple inheritance w.r.t. interfaces.
HAS-A Relationship
§  Has-A means an instance of one class “has a” reference to an instance of another class or another instance of same class.
§  It is also known as “composition” or “aggregation”.
§  There is no specific keyword to implement HAS-A relationship but mostly we are depended upon “new” keyword.
One of the advantages of Object-Oriented programming language is code reuse. There are two ways we can do code reuse either by implementation of inheritance (IS-A relationship), or object composition (HAS-A relationship). Although the compiler and Java virtual machine (JVM) will do a lot of work for you when you use inheritance, you can also get at the functionality of inheritance when you use composition.

IS-A Relationship:
In object oriented programming, the concept of IS-A is a totally based on Inheritance, which can be of two types Class Inheritance or Interface Inheritance. It is just like saying "A is a B type of thing". For example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is uni-directional. For example House is a Building. But Building is not a House.
It is key point to note that you can easily identify the IS-A relationship. Wherever you see an extends keyword or implements keyword in a class declaration, then this class is said to have IS-A relationship.


package com.Inheritance;


class Person{


}
class Employee extends Person{
}
class Teacher extends Person{

}

public class Teacher_Math extends Teacher {

public static void main(String args[]){

Teacher_Math teacher_Math = new Teacher_Math();
Teacher teacher = new Teacher();
Employee employee = new Employee();
Person person = new Person();

System.out.println(employee instanceof Person);
System.out.println(teacher instanceof Person);
System.out.println(teacher_Math instanceof Teacher);
System.out.println(teacher_Math instanceof Person);

}
}


OUTPUT :-
true
true
true
true

--------------------------------------------------------------------------------------------------------------------
HAS-A Relationship: 
Composition(HAS-A) simply mean use of instance variables that are references to other objects. For example: Maruti has Engine, or House has Bathroom.
Let’s understand these concepts with example of Car class.

  1. package relationships;  
  2. class Car {  
  3.   
  4.     // Methods implementation and class/Instance members  
  5.   
  6.     private String color;    
  7.     private int maxSpeed;   
  8.     public void carInfo(){  
  9.   
  10.         System.out.println("Car Color= "+color + " Max Speed= " + maxSpeed);  
  11.     }    
  12.     public void setColor(String color) {  
  13.   
  14.         this.color = color;  
  15.   
  16.     }  
  17.     public void setMaxSpeed(int maxSpeed) {  
  18.   
  19.         this.maxSpeed = maxSpeed;  
  20.   
  21.     }  
  22. }  
As shown above Car class has couple of instance variable and few methods. Maruti is specific type of Car which extends Car class means Maruti IS-A Car.
  1. class Maruti extends Car{  
  2.   
  3.     //Maruti extends Car and thus inherits all methods from Car (except final and static)  
  4.   
  5.     //Maruti can also define all its specific functionality  
  6.   
  7.     public void MarutiStartDemo(){  
  8.   
  9.         Engine MarutiEngine = new Engine();  
  10.   
  11.         MarutiEngine.start();  
  12.   
  13.         }  
  14.   
  15.     }  
Maruti class uses Engine object’s start() method via composition. We can say that Maruti class HAS-A Engine.
  1. package relationships;  
  2.   
  3. public class Engine {  
  4.   
  5.     public void start(){  
  6.   
  7.         System.out.println("Engine Started:");  
  8.   
  9.     }    
  10.     public void stop(){  
  11.   
  12.         System.out.println("Engine Stopped:");  
  13.   
  14.     }  
  15.   
  16. }  
RelationsDemo class is making object of Maruti class and initialized it. Though Maruti class does not have setColor(), setMaxSpeed() and carInfo() methods still we can use it due to IS-A relationship of Maruti class with Car class.
  1. package relationships;  
  2.   
  3. public class RelationsDemo {  
  4.   
  5.     public static void main(String[] args) {          
  6.   
  7.         Maruti myMaruti = new Maruti();  
  8.   
  9.         myMaruti.setColor("RED");  
  10.   
  11.         myMaruti.setMaxSpeed(180);  
  12.         myMaruti.carInfo();        
  13.         myMaruti.MarutiStartDemo();  
  14.   
  15.     } 
  16. }  
If we run RelationsDemo class we can see output like below.

Composition : 
§  Without existence of container object, if there is no chance of existence of contained objects then container and contained objects are said to be strongly associated and this strong association is known as composition.
Eg: A “university” has several “departments”. Without existence of “university” there is no chance for the “departments” to exist. Hence “university” and “departments” are strongly associated and this strong association is known as composition.

Aggregation
§  Without existence of container object, if there is a chance of existence of contained objects then container and contained objects are said to be loosely associated and this strong association is known as aggregation.
Eg: A  “department” has several “professors”. Without existence of “departments” there is good chance for the “professors” to exist. Hence “professors” and “department” are loosely associated and this loose association is known as Aggregation.

Remember, Java methods are inherited, constructors are not. Consider the following class:
publicclassExample{
publicvoid sayHi {
system.out.println("Hi");
}
Example(){}
}
publicclassSubClassextendsExample{
}
The SubClass class automatically inherits the sayHi method found in the parent class. However, the constructor Example() is not inherited by the SubClass.

1           Difference between Association, Composition and Aggregation in Java, UML and Object Oriented Programming

In Object-oriented programming, one object is related to other to use functionality and service provided by that object. This relationship between two object is known as association in  object oriented general software design, and depicted by an arrow in Unified Modeling language or UML. Both Composition and Aggregation are form of association between two objects, but there is subtle difference between composition and aggregation, which is also reflected by their UML notation. We refer association between two objects as composition, when one class owns other class and other class cannot meaningfully exist, when it's owner destroyed, for example Human class is composition of several body parts including Hand, Leg and Heart. When human object dies, all it's body part ceased to exist meaningfully, this is one example of Composition. Programmers often confuse between Association, Composition and Aggregation in Object oriented design discussions, this confusion also makes difference between Association, Composition and Aggregation one of the popular questions in Java Interviews, only after difference between abstract class and interface . Another example of Composition is Car and it's part e.g. engines, wheels etc. Individual parts of car cannot function, when car is destroyed.  While in case of Aggregation, including object can exists without being part of main object e.g. a Player which is part of a Team, can exists without team and can become part of other teams as well. Another example of Aggregation is Student in School class, when School closed, Student still exist and then can join another School or so.  In UML notation, composition is denoted by a filled diamond, while aggregation is denoted by an empty diamond, which shows their obvious difference in terms of strength of relationship. Composition is more stronger than Aggregation. In Short, relationship between two objects is referred as association, and an association is known as composition when one object owns other, while an association is known as aggregation when one object uses other object. In this OOPS tutorial, we will see couple of more examples to understand difference between Association, Composition and Aggregation better.

An Example of Association, Composition and Aggregation in Java
Here is an example of composition and aggregation, in terms of Java Code. By looking at this code, you can gauge differences between these two. By the way, Composition is also very much preferred in object oriented design over inheritance, even Joshua bloach has stated its importance in classic book, Effective Java.

Composition : Since Engine is part-of Car, relationship between them is Composition. Here is how they are implemented between Java classes.
publicclassCar {
//final will make sure engine is initialized
privatefinal Engine engine;  
 
publicCar(){
       engine  = new Engine();
    }
}
 
classEngine {
private String type;
}


Aggregation : Since Organization has Person as employees, relationship between them is Aggregation. Here is how they look like in terms of Java classes
publicclassOrganization {
private List employees;
}
 
publicclassPerson {
private String name;   
}
----------------------------------------------------------------------------------------------------
Java Inheritance
Java Inheritance defines an is-a relationship between a superclass and its subclasses. This means that an object of a subclass can be used wherever an object of the superclass can be used. Class Inheritance in java mechanism is used to build new classes from existing classes. The inheritance relationship is transitive: if class x extends class y, then a class z, which extends class x, will also inherit from class y.
For example a car class can inherit some properties from a General vehicle class. Here we find that the base class is the vehicle class and the subclass is the more specific car class. A subclass must use the extends clause to derive from a super class which must be written in the header of the subclass definition. The subclass inherits members of the superclass and hence promotes code reuse. The subclass itself can add its own new behavior and properties. The java.lang.Object class is always at the top of any Class inheritance hierarchy.
class Box {
 
               double width;
               double height;
               double depth;
               Box() {
               }
               Box(double w, double h, double d) {
                               width = w;
                               height = h;
                               depth = d;
               }
               void getVolume() {
                               System.out.println("Volume is : " + width * height * depth);
               }
}
 
public class MatchBox extends Box {
 
               double weight;
               MatchBox() {
               }
               MatchBox(double w, double h, double d, double m) {
                               super(w, h, d);
                               weight = m;
               }
               public static void main(String args[]) {
                               MatchBox mb1 = new MatchBox(10, 10, 10, 10);
                               mb1.getVolume();
                               System.out.println("width of MatchBox 1 is " + mb1.width);
                               System.out.println("height of MatchBox 1 is " + mb1.height);
                               System.out.println("depth of MatchBox 1 is " + mb1.depth);
                               System.out.println("weight of MatchBox 1 is " + mb1.weight);
               }
}
Output
Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0

------------------------------------------------------------------------------------------------
composition
Java composition is achieved by using instance variables that refers to other objects. For example, a Personhas a Job. Let’s see this with a simple code.
package com.journaldev.composition;
public class Job {
    private String role;
    private long salary;
    private int id; 
    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }
    public long getSalary() {
        return salary;
    }
    public void setSalary(long salary) {
        this.salary = salary;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
}
package com.journaldev.composition;
public class Person {
    //composition has-a relationship
    private Job job;
    public Person(){
        this.job=new Job();
        job.setSalary(1000L);
    }
    public long getSalary() {
        return job.getSalary();
    }
}
Here is a test class that uses person object and get it’s salary.
package com.journaldev.composition;
public class TestPerson {
    public static void main(String[] args) {
        Person person = new Person();
        long salary = person.getSalary();
    }
}
Notice that above test program is not affected by any change in the Job object. If you are looking for code reuse and the relationship between two classes is has-a then you should use composition rather than inheritance.
Benefit of using composition is that we can control the visibility of other object to client classes and reuse only what we need.
Also if there is any change in the other class implementation, for example getSalary returning String, we need to change Person class to accommodate it but client classes doesn’t need to change.
Composition allows creation of back-end class when it’s needed, for example we can change PersongetSalary method to initialize the Job object.
--------------------------------------------------------------------------------------------------------------------Java - HAS-A Relationship






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

Download MatchBox.java
What is not possible using java class Inheritance?

1. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed.
2. Members that have default accessibility in the superclass are also not inherited by subclasses in other packages, as these members are only accessible by their simple names in subclasses within the same package as the superclass.
3. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass.
4. A subclass can extend only one superclass

class Vehicle {
 
-------------------------------------------------------------------

package com.Accessifier_Content;
public class Car_3 {
int number_Default =100;
public int number_Defalt_Public = 200;
}
---

package com.Accessifier;

import com.Accessifier_Content.Car_3;

public class TestDefault_Extends extends Car_3{

public static void main(String[] args) {

TestDefault_Extends tde = new TestDefault_Extends();
int number_Main = tde.number_Defalt;

}
}





----------------------------------------------------------------
               // Instance fields
               int noOfTyres; // no of tyres
               private boolean accessories; // check if accessorees present or not
               protected String brand; // Brand of the car
               // Static fields
               private static int counter; // No of Vehicle objects created
               // Constructor
               Vehicle() {
                               System.out.println("Constructor of the Super class called");
                               noOfTyres = 5;
                               accessories = true;
                               brand = "X";
                               counter++;
               }
               // Instance methods
               public void switchOn() {
                               accessories = true;
               }
               public void switchOff() {
                               accessories = false;
               }
               public boolean isPresent() {
                               return accessories;
               }
               private void getBrand() {
                               System.out.println("Vehicle Brand: " + brand);
               }
               // Static methods
               public static void getNoOfVehicles() {
                               System.out.println("Number of Vehicles: " + counter);
               }
}
 
class Car extends Vehicle {
 
               private int carNo = 10;
               public void printCarInfo() {
                               System.out.println("Car number: " + carNo);
                               System.out.println("No of Tyres: " + noOfTyres); // Inherited.
                               //  System.out.println("accessories: "    + accessories); // Not Inherited.
                               System.out.println("accessories: " + isPresent()); // Inherited.
                               //        System.out.println("Brand: "     + getBrand());  // Not Inherited.
                               System.out.println("Brand: " + brand); // Inherited.
                               //  System.out.println("Counter: "    + counter);     // Not Inherited.
                               getNoOfVehicles(); // Inherited.
               }
}
 
public class VehicleDetails { // (3)
 
               public static void main(String[] args) {
                               new Car().printCarInfo();
               }
}
Output
Constructor of the Super class called
Car number: 10
No of Tyres: 5
accessories: true
Brand: X
Number of Vehicles: 1

-----------------------------------------------------------------------------------------------------
DownloadVehicleDetails.java

this and super keywords

The two keywords, this and super to help you explicitly name the field or method that you want. Using this and super you have full control on whether to call a method or field present in the same class or to call from the immediate superclass. This keyword is used as a reference to the current object which is an instance of the current class. The keyword super also references the current object, but as an instance of the current class’s super class.
The this reference to the current object is useful in situations where a local variable hides, or shadows, a field with the same name. If a method needs to pass the current object to another method, it can do so using the this reference. Note that the this reference cannot be used in a static context, as static code is not executed in the context of any object.
class Counter {
 
               int i = 0;
               Counter increment() {
                               i++;
                               return this;
               }
               void print() {
                               System.out.println("i = " + i);
               }
}
 
public class CounterDemo extends Counter {
 
               public static void main(String[] args) {
                               Counter x = new Counter();
                               x.increment().increment().increment().print();
               }
}
Output

i : 3

----------------------------------------------------------------------------------------
Copy Constructor in Java Example
Sometimes a programmer wants to create an exact but separate copy of an existing object so that subsequent changes to the copy should not alter the original or vice versa. This is made possible using the copy constructor.
A copy constructor is a constructor that creates a new object using an existing object of the same class and initializes each instance variable of newly created object with corresponding instance variables of the existing object passed as argument. This constructor takes a single argument whose type is that of the class containing the constructor.
class Rectangle 

{ 
        int length; 
        int breadth; 
        //constructor to initialize length and bredth of rectang of rectangle 
        Rectangle(int l, int b) 
        {  
           length = l; 
           breadth= b; 
        } 

        //copy constructor 
        Rectangle(Rectangle obj) 
        { 
          System.out.println("Copy Constructor Invoked"); 
          length = obj.length; 
          breadth= obj.breadth; 
        } 
       //method to calcuate area of rectangle 
       int area() 
       { 
          return (length * breadth); 
       } 
} 

       //class to create Rectangle object and calculate area 
       class CopyConstructor 
{ 
          public static void main(String[] args) 
          { 
            Rectangle firstRect = new Rectangle(5,6); 
            Rectangle secondRect= new Rectangle(firstRect); 
            System.out.println("Area  of First Rectangle : "+ firstRect.area()); 
            System .out.println("Area of First Second Rectangle : "+ secondRect.area()); 
          } 
} 
------------------------------------------------------------------------------------------------------------------

Object Cloning in Java



The object cloning is a way to create exact copy of an object. For this purpose, clone() method of Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.
The clone() method is defined in the Object class. Syntax of the clone() method is as follows:
1.      protected Object clone() throws CloneNotSupportedException  

Why use clone() method ?

The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new keyword, it will take a lot of processing to be performed that is why we use object cloning.

Advantage of Object cloning

Less processing task.

Example of clone() method (Object cloning)

Let's see the simple example of object cloning
1.      class Student18 implements Cloneable{  
2.      int rollno;  
3.      String name;  
4.        
5.      Student18(int rollno,String name){  
6.      this.rollno=rollno;  
7.      this.name=name;  
8.      }  
9.        
10.  public Object clone()throws CloneNotSupportedException{  
11.  return super.clone();  
12.  }  
13.    
14.  public static void main(String args[]){  
15.  try{  
16.  Student18 s1=new Student18(101,"amit");  
17.    
18.  Student18 s2=(Student18)s1.clone();  
19.    
20.  System.out.println(s1.rollno+" "+s1.name);  
21.  System.out.println(s2.rollno+" "+s2.name);  
22.    
23.  }catch(CloneNotSupportedException c){}  
24.    
25.  }  
26.  }  
Output:101 amit
       101 amit
As you can see in the above example, both reference variables have the same value. Thus, the clone() copies the values of an object to another. So we don't need to write explicit code to copy the value of an object to another.
If we create another object by new keyword and assign the values of another object to this one, it will require a lot of processing on this object. So to save the extra processing task we use clone() method.
-----------------------------------------------------------------------------------------------------------------------

Shallow Copy


package com.Clone;


class A {

int i;
int j;
}
public class CloningTest {
public static void main(String[] args) {

A a = new A();

a.i = 10;
a.j = 20;

A b = a;


b.i = 50;

b.j = 60;

System.out.println(a.i);

System.out.println(a.j);
System.out.println("-------------------------");
System.out.println(b.i);
System.out.println(b.j);
}

}

OUTPUT:-

50

60
-------------------------
50

60

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



package com.example.demo.cloning;

class Cat {
int j = 10;
Cat(int j) {
this.j = j;
}
}

class Dog implements Cloneable {
Cat c;
int i;
Dog(Cat c, int i) {
this.c = c;
this.i = i;
}
public Object clone() throws CloneNotSupportedException {
Cat c1 = new Cat(c.j);
Dog d2 = new Dog(c1, i);
return d2;
}
}

public class DeepCloningDemo {

public static void main(String[] args) throws CloneNotSupportedException {
Cat c = new Cat(20);
Dog d1 = new Dog(c, 10);
System.out.println(d1.i + "----" + d1.c.j);
Dog d2 = (Dog) d1.clone();
d2.i = 888;
d2.c.j = 999;

System.out.println(d2.i + "----" + d2.c.j);
}
}

OUTPUT:-
10----20
888----999




-------------------------------------------------------------------------------------------------------------------Polymorphism in Java

Overloading vs Overriding in Java

  1. Overloading happens at compile-time while Overriding happens at runtime: The binding of overloaded method call to its definition has happens at compile-time however binding of overridden method call to its definition happens at runtime.
  2. Static methods can be overloaded which means a class can have more than one static method of same name. Static methods cannot be overridden, even if you declare a same static method in child class it has nothing to do with the same method of parent class.
  3. The most basic difference is that overloading is being done in the same class while for overriding base and child classes are required. Overriding is all about giving a specific implementation to the inherited method of parent class.
  4. Static binding is being used for overloaded methods and dynamic binding is being used for overridden/overriding methods.
  5. Performance: Overloading gives better performance compared to overriding. The reason is that the binding of overridden methods is being done at runtime.
  6. private and final methods can be overloaded but they cannot be overridden. It means a class can have more than one private/final methods of same name but a child class cannot override the private/final methods of their base class.
  7. Return type of method does not matter in case of method overloading, it can be same or different. However in case of method overriding the overriding method can have more specific return type (refer this).
  8. Argument list should be different while doing method overloading. Argument list should be same in method Overriding.
  9. In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter.
    Return type must be same or covariant in method overriding.

Rules for method overriding:
·         In java, a method can only be written in Subclass, not in same class.
·         The argument list should be exactly the same as that of the overridden method.
·         The return type should be the same or a subtype of the return type declared in the original overridden method in the super class.
·         The access level cannot be more restrictive than the overridden method’s access level. For example: if the super class method is declared public then the overridding method in the sub class cannot be either private or protected.
·         Instance methods can be overridden only if they are inherited by the subclass.
·         A method declared final cannot be overridden.
·         A method declared static cannot be overridden but can be re-declared.
·         If a method cannot be inherited then it cannot be overridden.
·         A subclass within the same package as the instance’s superclass can override any superclass method that is not declared private or final.
·         A subclass in a different package can only override the non-final methods declared public or protected.
·         An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.
·         Constructors cannot be overridden.






















-----------------------------------------------------------------------------------------------------------------------------
Polymorphism in java is a concept by which we can perform a single action by different ways. Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.
If you overload static method in java, it is the example of compile time polymorphism. Here, we will focus on runtime polymorphism in java.

1.1         Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.
Let's first understand the upcasting before Runtime Polymorphism.


1.1.1        Upcasting

When reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example:
  1. class A{}  
  2. class B extends A{}  
  1. A a=new B();//upcasting  


Example of Java Runtime Polymorphism

In this example, we are creating two classes Bike and Splendar. Splendar class extends Bike class and overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, subclass method is invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
  1. class Bike{  
  2.   void run(){System.out.println("running");}  
  3. }  
  4. class Splender extends Bike{  
  5.   void run(){System.out.println("running safely with 60km");}  
  6.   
  7.   public static void main(String args[]){  
  8.     Bike b = new Splender();//upcasting  
  9.     b.run();  
  10.   }  
  11. }  
Output:running safely with 60km.
 
Real example of Java Runtime Polymorphism
Consider a scenario, Bank is a class that provides method to get the rate of interest. But, rate of interest may differ according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.
Note: It is also given in method overriding but there was no upcasting.
1.      class Bank{  
2.      int getRateOfInterest(){return 0;}  
3.      }  

4.      class SBI extends Bank{  
5.      int getRateOfInterest(){return 8;}  
6.      }  

7.      class ICICI extends Bank{  
8.      int getRateOfInterest(){return 7;}  
9.      }  
10.  class AXIS extends Bank{  
11.  int getRateOfInterest(){return 9;}  
12.  }  

13.  class Test3{  
14.  public static void main(String args[]){  
15.  Bank b1=new SBI();  
16.  Bank b2=new ICICI();  
17.  Bank b3=new AXIS();  
18.  System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());  
19.  System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());  
20.  System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());  
21.  }  
22.  }  
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9


Java Runtime Polymorphism with data member
Method is overridden not the datamembers, so runtime polymorphism can't be achieved by data members.
In the example given below, both the classes have a datamember speedlimit, we are accessing the datamember by the reference variable of Parent class which refers to the subclass object. Since we are accessing the datamember which is not overridden, hence it will access the datamember of Parent class always.

1.1.1.1       Rule: Runtime polymorphism can't be achieved by data members.

  1. class Bike{  
  2.  int speedlimit=90;  
  3. }  
  4. class Honda3 extends Bike{  
  5.  int speedlimit=150;  
  6.   
  7.  public static void main(String args[]){  
  8.   Bike obj=new Honda3();  
  9.   System.out.println(obj.speedlimit);//90  
  10. }  
Output:90

1.2         Java Runtime Polymorphism with Multilevel Inheritance

Let's see the simple example of Runtime Polymorphism with multilevel inheritance.
  1. class Animal{  
  2. void eat(){System.out.println("eating");}  
  3. }  
  4.   
  5. class Dog extends Animal{  
  6. void eat(){System.out.println("eating fruits");}  
  7. }  
  8.   
  9. class BabyDog extends Dog{  
  10. void eat(){System.out.println("drinking milk");}  
  11.   
  12. public static void main(String args[]){  
  13. Animal a1,a2,a3;  
  14. a1=new Animal();  
  15. a2=new Dog();  
  16. a3=new BabyDog();  
  17.   
  18. a1.eat();  
  19. a2.eat();  
  20. a3.eat();  
  21. }  
  22. }  
Output: eating
        eating fruits
        drinking Milk


1.2.1        Try for Output

  1. class Animal{  
  2. void eat(){System.out.println("animal is eating...");}  
  3. }  
  4.   
  5. class Dog extends Animal{  
  6. void eat(){System.out.println("dog is eating...");}  
  7. }  
  8.   
  9. class BabyDog1 extends Dog{  
  10. public static void main(String args[]){  
  11. Animal a=new BabyDog1();  
  12. a.eat();  
  13. }}  
Output: Dog is eating
Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is invoked.

2           Polymorphism In Java

2.1         Introduction

Java is an object-oriented programming language, so polymorphism in Java is the bread and butter of object-oriented programming in Java. In this tutorial we're going to find out what polymorphism is, why it is so useful, and then show how to use it to create elegant programs. This concept is somewhat difficult to put into practice because it happens to be much more abstract than many of the other concepts. However, if you can master it, you will become that much better of a programmer and you will have a much easier time mastering the Java language.

2.2         What is Polymorphism?

Polymorphism is THE concept to master if you want to master object-oriented programming. Because Java is an object-oriented language, it makes sense that you should learn the concepts and power of polymorphism in Java.
Simply put, polymorphism is what allows actions to act differently based on the object performing the action or the object the action is being performed on. Let's just use a super simple, real life example. What is a typical sound that a cat makes? Let's just say it's meow. Let's call this action makeSound() because remember, a method can represent an action. What sound does a dog make? Let's just say a dog goes woof. We can also call this action makeSound(). Let's also just pretend that all animals can makeSound(). Thus, makeSound(), depending on the type of animal, does something different. The action acts differently based on the object.
This concept of polymorphism in Java especially, is actually not hard to understand at all. Oh look, different animals make different sounds, and the same method can be used to make each distinct sound. If you've done the Java inheritance tutorial, you already know how to do this!
One powerful tool for using polymorphic behavior is to use the same method name but in the same class, over and over again to get the desired effects you want. How can we use polymorphism in Java to accomplish this?

2.3         Overloaded Methods

Let's use our makeSound() example again. Let's say a dog makes a woof sound, but if the dog is injured, the dog might make a whimper noise instead. How can we use makeSound() to produce both sounds? Take a look at this code snippet:

NOTE: At this point, if you're not sure you understand the code you see, you REALLY should go back to the Intermediate Tutorials and read the tutorial on Methods In Java. Then you can come back to learn about polymorphism in Java once you have a better understanding of methods.
We can see here that depending on the number of parameters we pass to makeSound(), the dog will make a different sound. But wait! Couldn't we have just used an if statement and make this just one method? Yes, we could have done that and that's probably a better way of programming this for this particular example. What if an outside action causes the difference in dog sound though? Something like this:

If the dog did not have the variable to know it was hurt, you would not be able to write that if statement as easily.
You can overload a method as much as you want as long as the number of parameters are different or the types of parameters are different. You could not do this for example:

This is because those are the same number of parameters AND are the same types of parameters.

2.4         Overridden Methods

In Java, you can create a method in a superclass (or parent class), then in a subclass ALSO define that method. Let's see an example of this using Animal:


Now, let's say you could actually create Animals. If you could, then calling makeSound() would call the method defined in the superclass. If you create a specific Dog, calling makeSound() will display "woof". Now let's say you created a specific Cat. In that example, Cat does not have a makeSound() method, so when you call makeSound() on Cat, it calls the method in the superclass Animal and does nothing. Remember, Cat and Dog are subclasses of Animal because they extend Animal.
This behavior is called method overriding, and it is EXTREMELY powerful stuff when it comes to polymorphism in Java. Java will let you do this because its possible more specific types of objects have more specific behaviors for actions. How does Java then know which method to actually call? Java will always pick the object's true type for choosing which method to call, the superclass or the subclass. We will see what true type really means in the next section.

2.5         Dynamic Method Binding

Do not let the long name confuse you. This is not that scary of a term! We won't discuss why this is dynamic, but let's just say that Java decides what method to call during runtime, or once the program is running. Dynamic method binding is how Java decides what method to call when it has to decide between the superclass and the subclass. So, how exactly does it decide? To illustrate this point, we must first illustrate the concept of true type versus referenced type.

Look, we just made a Dog but declared it as an Animal! Normally you would see this:

However, you can also declare a variable by its supertype or abstract type to make it more generic. Let's say you don't know what kind of animal you want:

Notice how the variable is not assigned to anything! We have an animal that has not been instantiate, and it does not equal anything. We can't create just Animals because they are abstract, so we must make a specific kind of animal, which is what we did with the example above by making the Animal be a new Dog.
So, which version of makeSound() would you use if you saw Animal animal = new Dog() ? Would you choose the Animal's version or the Dog's version? The answer is that Java will choose the true type, and the true type is the object that actually gets created. In this example, what we are really creating is a Dog, even though we are referencing the variable as an Animal.
Why in the world wouldn't we just do Dog dog = new Dog() ? The answer is that by using abstraction, you can actually group many different types of objects together. Let's see how we can use this concept for storing objects:

We could not do the above if the Cat objects and Dog objects were made the traditional way and not by referencing them as Animals.
It is very important you do not flip the reference and the true type! You could not do this:

First of all, in our example, you cannot create Animal objects because they are abstract. Let's assume you could though. This is still illegal because a specific type cannot be the reference of a more broad type. Think about it this way: A dog is an animal but an animal is not necessarily a dog. The above example is basically saying that an Animal is a Dog, and this is not always true.
Polymorphism in Java allows you to fully control how you group objects together and gives you the power to make them as specific as you want. It is also the crucial part of object-oriented programming that allows you to build hierarchies of objects, objects that have a logical structure that makes sense in the real world. Because of polymorphism, you can create highly sophisticated programs in Java that are easy to read and are well organized. It does not guarantee an awesome organization of your code, but if you're careful it can help you immensely in doing so.
My final advice about polymorphism in Java is to practice! Practice making a bunch of abstract and regular classes. Create your own object structures. Make different objects extend each other. Write the same methods over and over again using different parameters and putting them in the parent classes and subclasses. Then, test out your objects by writing a main class that uses the classes and methods you write in different ways. By doing so, you will be on your way to mastering this highly abstract, highly powerful concept!
If you would like to leave a comment for Polymorphism in Java, please click here to go to the questions/comments page! Or, simply click the appropriate contact link in the sidebar. Thanks!

Encapsulation
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class, therefore it is also known as data hiding.
To achieve encapsulation in Java
·        Declare the variables of a class as private.
·        Provide public setter and getter methods to modify and view the variables values.
·         Encapsulation in java is a process of wrapping code and data together into a single unit, for example capsule i.e. mixed of several medicines.
·         We can create a fully encapsulated class in java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it.
·         The Java Bean class is the example of fully encapsulated class.

2.5.1.1       Advantage of Encapsulation in java

·         By providing only setter or getter method, you can make the class read-only or write-only.
·         It provides you the control over the data. Suppose you want to set the value of id i.e. greater than 100 only, you can write the logic inside the setter method.
The whole idea behind encapsulation is to hide the implementation details from users. If a data member is private it means it can only be accessed within the same class. No outside class can access private data member (variable) of other class. However if we setup public getter and setter methods to update (for e.g. void setSSN(int ssn))and read (for e.g.  int getSSN()) the private data fields then the outside class can access those private data fields via public methods. This way data can only be accessed by public methods thus making the private fields and their implementation hidden for outside classes. That’s why encapsulation is known as data hiding. Lets see an example to understand this concept better.
/* File name : EncapTest.java */
publicclassEncapTest{
privateString name;
privateString idNum;
privateint age;

publicint getAge(){
return age;
}

publicString getName(){
return name;
}

publicString getIdNum(){
return idNum;
}

publicvoid setAge(int newAge){
      age = newAge;
}

publicvoid setName(String newName){
      name = newName;
}

publicvoid setIdNum(String newId){
      idNum = newId;
}
}


publicclassRunEncap{

publicstaticvoid main(String args[]){
EncapTest encap =newEncapTest();
      encap.setName("James");
      encap.setAge(20);
      encap.setIdNum("12343ms");

System.out.print("Name : "+ encap.getName()+" Age : "+ encap.getAge());
}
}

2.6                     Benefits of Encapsulation:

·        The fields of a class can be made read-only or write-only.
·        A class can have total control over what is stored in its fields.
·        The users of a class do not know how the class stores its data. A class can change the data type of a field and users of the class do not need to change any of their code.
·         Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.
·         Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.
·         Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface.
·         The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.
·         Encapsulation in java is a process of wrapping code and data together into a single unit, for example capsule i.e. mixed of several medicines.
·        
·         We can create a fully encapsulated class in java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it.
·         The Java Bean class is the example of fully encapsulated class.

·         Advantage of Encapsulation in java

·         By providing only setter or getter method, you can make the class read-only or write-only.


·         It provides you the control over the data. Suppose you want to set the value of id i.e. greater than 100 only, you can write the logic inside the setter method.


Java – Abstraction

What is Abstraction?
Abstraction is process of hiding the implementation details and showing only the functionality.

Abstraction in java is achieved by using interface and abstract class. Interface give 100% abstraction and abstract class give 0-100% abstraction.

What is Abstract class in Java?
 A class that is declared as abstract is known as abstract class.

Syntax:
abstract class <class-name>{}

An abstract class is something which is incomplete and you cannot create instance of abstract class.
If you want to use it you need to make it complete or concrete by extending it.
A class is called concrete if it does not contain any abstract method and implements all abstract method inherited from abstract class or interface it has implemented or extended.

What is Abstract method in Java?

A method that is declare as abstract and does not have implementation is known as abstract method.
If you define abstract method than class must be abstract.

Syntax:

abstract return_type method_name ();

An abstract method in Java doesn't have body, it’s just a declaration. In order to use abstract method you need to override that method in Subclass.

Example 1 :( Without abstract method)

class Employee extends Person {

private String empCode;

public String getEmpCode(){
return empCode;
}

publicvoid setEmpCode(String empCode){
this.empCode = empCode;
}
}

abstractclass Person {

private String name;

public String getName(){
return name;
}
publicvoid setName(String name){
this.name = name;
}
}

publicclass Main{
               publicstaticvoid main(String args[]){
 //INSTIATING AN ABSTRACT CLASS GIVES COMPILE TIME ERROR
 //Person p =  new Person() ;

 //THIS REFERENCE VARIABLE CAN ACESS ONLY THOSE METHOD WHICH ARE OVERRIDDEN
        Person person =new Employee();
        person.setName("Jatin Kansagara");
        System.out.println(person.getName());
}
}



Example 2: (with abstract method)

publicclass Main{
               publicstaticvoid main(String args[]){
        TwoWheeler test =new Honda();
        test.run();
}
}
abstractclass TwoWheeler {
publicabstractvoid run();
}
class Honda extends TwoWheeler{
               publicvoid run(){
                               System.out.println("Running..");
               }
}

When do you use abstraction?
When you know something needs to be there but not sure how exactly it should look like.

Advantages of Abstraction
By using abstraction, we can separate the things that can be grouped to another type.

Frequently changing properties and methods can be grouped to a separate type so that the main type need not undergo changes. This adds strength to the OOAD principle -"Code should be open for Extension but closed for Modification".

Simplifies the representation of the domain models.

Summary:
-    Use abstraction if you know something needs to be in class but implementation of that varies.
-     In Java you cannot create instance of abstract class , its compiler error.
-    abstract is a keyword in java.
-    A class automatically becomes abstract class when any of its method declared as abstract.
-     abstract method doesn't have method body.
-    Variable cannot be made abstract, its only behavior or methods which would be abstract.
-    If a class extends an abstract class or interface it has to provide implementation to all its abstract method to be a concrete class. Alternatively this class can also be abstract.

Array


Finding duplicate element in Array

here j =i+1 ; on second for loop

package com.Duplicate;
public class ArrayValue {

       public static void main(String[] args) {
              String sa[] = {"java","C","Python","java"};
              for(int i=0;i<sa.length;i++){
                     for(int j=i+1;j<sa.length;j++)
                     {
                           if(sa[i].equals(sa[j])){
                                  System.out.println(sa[i]);
                           }
                     }
              }
             
       }
}
Example
The following code snippets are examples of this syntax −
double[] myList;   // preferred way.
or
double myList[];   // works but not preferred way.

Creating Arrays

You can create an array by using the new operator with the following syntax −

Syntax

arrayRefVar = new dataType[arraySize];
The above statement does two things −
·        It creates an array using new dataType[arraySize].
·        It assigns the reference of the newly created array to the variable arrayRefVar.
------------------------------------------------------------------------------------------------------------------------------

Check if an array has duplicate numbers

Given an array numbers, how do we write a function checkDuplicates() which returns true if the array has at least one element repeated; returns false if all the elements are unique.

We discuss three different implementations of this function with various time and space complexities.
Method-1: Naive approach
This approach checks every possible pair in the array to see if there are any duplicates. This is exhaustive  search and we can find the answer in O(n2) time. Because there are n(n-1)/2 possible pairs for an array of size n.

Time complexity: O(n2)
Space complexity: O(1)

The following is the C++ function which implements this approach.
 
bool checkDuplicates( int array[], int n)
{
 int i,j;
 for( i = 0; i < n; i++ )
 {
  for( j = i+1; j < n; j++ )
  {
   if( array[i] == array[j] )
    return true;
  }
 }
 return false;
}
 
Method-2: Sorting Approach
First sort the array using any sort which runs in O(n log n) time ( Quick sort/ Heap sort/ Merge sort).
Then all the duplicate elements comes together. Then simply compare all the adjacent elements to see if there are any duplicates.
Time complexity: O(n log n)
Space complexity: O(1)
The following is the C++ function which implements this approach.

bool checkDuplicates( int array[], int n)
{
 std::sort( array, array+n);
 int i;
 for( i = 0; i < n-1; i++)
 {
  if( array[i] == array[i+1] )
   return true;
 }
 return false;
}
Method-3: Set/HashTable approach
Use a data structure like a Set or a Hash Table which keeps track of the elements. When trying to insert into these data structures, we can see if the element already exists; If the element already exists in the data structure, we say that the array has duplicates.

Time complexity: O(n)
Space complexity: O(n)

The following is the Java function which implements this approach.

public static boolean checkDuplicates(int [] array)
    {
        HashSet<Integer> hSet = new HashSet<Integer>();
        for( int i = 0; i < array.length; i++ )
        {
            if( !hSet.add(array[i]) )
                return true;
        }
        return false;
    }
 
public static void main(String[] args) {
        int[] arr1 = new int[] { 10, 3, 4, 20};
        int[] arr2 = new int[] { 10, 20, 30 };
 
        //convert arr1 to java.util.Set
        Set<Integer> set1 = new HashSet<Integer>();
        for (int i : arr1) {
            set1.add(i);
        }
        // print the duplicates
        for (int i : arr2) {
            if (set1.contains(i)) {
                System.out.println(i); // print 10 20
            }
        }
    }

Generics

http://www.journaldev.com/1663/java-generics-example-method-class-interface











































Collection

















1.      ArrayList class
2.      LinkedList class
5.      HashSet class
6.      LinkedHashSet class
7.      TreeSet class
8.      PriorityQueue class
9.      Map interface















General Collection Questions

1.1.1        16) How to synchronize List, Set and Map elements?

Yes, Collections class provides methods to make List, Set or Map elements as synchronized:
public static List synchronizedList(List l){}
public static Set synchronizedSet(Set s){}
public static SortedSet synchronizedSortedSet(SortedSet s){}
public static Map synchronizedMap(Map m){}
public static SortedMap synchronizedSortedMap(SortedMap m){}

1.1.2        17) What is the advantage of generic collection?

If we use generic class, we don't need typecasting. It is typesafe and checked at compile time.

1.1.3        18) What is hash-collision in Hashtable and how it is handled in Java?

Two different keys with the same hash value is known as hash-collision. Two different entries will be kept in a single hash bucket to avoid the collision.

1.1.4        19) What is the Dictionary class?

The Dictionary class provides the capability to store key-value pairs.
20) What is the default size of load factor in hashing based collection?
The default size of load factor is 0.75. The default capacity is computed as initial capacity * load factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.
Q22) Arrange in the order of speed - HashMap,HashTable, Collections.synchronizedMap,concurrentHashmap
Ans) HashMap is fastest, ConcurrentHashMap,Collections.synchronizedMap,HashTable.
discarded its entry is effectively removed from the map, so this class behaves somewhat differently than other Map implementations.

List

Q1) What is difference between ArrayList and vector?
Ans)
·         Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.
  • Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.
  • Performance - Since vector is thread-safe , the performance is slower than ArrayList.

1.1.5        1) What is the difference between ArrayList and Vector?


No.
ArrayList
Vector
1)
ArrayList is not synchronized.
Vector is synchronized.
2)
ArrayList is not a legacy class.
Vector is a legacy class.
3)
ArrayList increases its size by 50% of the array size.
Vector increases its size by
doubling the array size.

Q3) If an Employee class is present and its objects are added in an arrayList. Now I want the list to be sorted on the basis of the employeeID of Employee class. What are the steps?
Ans)
  • Implement Comparable interface for the Employee class and override the compareTo(Object obj) method in which compare the employeeID
  • Now call Collections.sort() method and pass the list as an argument.
Now consider that Employee class is a jar file.
  • 1) Since Comparable interface cannot be implemented, create Comparator and override the compare(Object obj, Object obj1) method.
  • 2) Call Collections.sort() on the list and pass comparator as an argument.
Q5) What are the classes implementing List interface?
Ans) There are three implementation of List interface:
  1. ArrayList : It is a resizable array implementation.The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe.
  2. Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block.
  3. LinkedList: the LinkedList implements Queue interface too and provide FIFO (First In First Out) operation for add operation. It is faster than ArrayList if it's mainly used forinsertion and deletion of elements.
Q8) What is difference between Arrays and ArrayList ?
Ans)
·         Arrays are created of fix size whereas ArrayList is dynamic in nature and can vary its length. Also the size of array cannot be incremented or decremented. But with arrayList the size is variable.
  • Once the array is created elements cannot be added or deleted from it. But with ArrayList the elements can be added and deleted at runtime.
·         List list =new ArrayList();
·           list.add(1);
·           list.add(3);
  list.remove(0)//  will remove the element from the 1st location.
  • ArrayList is one dimensional but array can be multidimensional.
int[][][] intArray=new  int[3][2][1];// 3 dimensional array
  • Array can contain objects of a single data type or class. ArrayList if not used with generic can contain objects of different classes

1.1.1        2) What is the difference between ArrayList and LinkedList?

No.
ArrayList
LinkedList
1)
ArrayList uses a dynamic array.
LinkedList uses doubly linked list.
2)
ArrayList is not efficient for manipulation because a lot of shifting is required.
LinkedList is efficient for manipulation.
3)
ArrayList is better to store and fetch data.
LinkedList is better to manipulate data.


Q9)  When to use ArrayList or LinkedList ?
Ans)
  1. Adding new elements is pretty fast for either type of list. Inserting element to n location in arraylist and to first location in linkedlist takes O(1).
  2. For the ArrayList, doing random lookup using "get" is fast, but for LinkedList O(n), it's slow. It's slow because there's no efficient way to index into the middle of a linked list. Linkedlist lookup always start from 1st location.
  3. When removing elements, using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But LinkedList is fast, because deletion can be done simply by changing a couple of links.
So an ArrayList works best for cases where you're doing random access on the list and a LinkedList works better if you're doing a lot of editing in the middle of the list.

Q13) Why is it preferred to declare: List<String> list = new ArrayList<String>(); instead of ArrayList<String> = new ArrayList<String>();
Ans) It is preferred because:
  1. If later on code needs to be changed from ArrayList to Vector then only at the declaration place we can do that.
  2. The most important one – If a function is declared such that it takes list. E.g void showDetails(List list);
    When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList,Vector,LinkedList making the function more flexible.
Q15) How to sort list in reverse order?
Ans) To sort the elements of the List in the reverse natural order of the strings, get a reverse Comparator from the Collections class with reverseOrder(). Then, pass the reverse Comparator to the sort() method.
3.      List list =new ArrayList();
4.      Comparator comp = Collections.reverseOrder();
5.      Collections.sort(list, comp)
Q17) How to sort list of strings - case insensitive ?
Ans) using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
Q18) How to make a List (ArrayList,Vector,LinkedList) read only ?
Ans) A list implementation can be made read only using Collections.unmodifiableList(list). This method returns a new list. If a user tries to perform add operation on the new list; UnSupportedOperationException is thrown.
Q20) Which is faster to iterate LinkedHashSet or LinkedList?
Ans) LinkedList.
HashMap vs ConcurrentHashMap

1.  Thread -Safe : 

     ConcurrentHashMap is thread-safe that is the code can be accessed by single thread at a time .    
     while HashMap is not thread-safe .

2.  Synchronization Method :

    HashMap can be synchronized by using    
    synchronizedMap(HashMap)  method .  By using this  

    method we get a HashMap object which is equivalent 
    to the HashTable object . So every modification  is performed    
    on  Map is locked on Map object.


import java.util.*;

public class HashMapSynchronization {
    public static void main(String[] args) {
        // create map
        Map<String,String> map = new HashMap<String,String>();
       
        // populate the map
        map.put("1","ALIVE ");
        map.put("2","IS");
        map.put("3","AWESOME");
       
        // create a synchronized map
        Map<String,String> syncMap = Collections.synchronizedMap(map);
       
        System.out.println("Synchronized map :"+syncMap);
    }
}


   ConcurrentHashMap synchronizes or locks on the certain portion of the Map . To optimize
   the performance of ConcurrentHashMap , Map is divided into different partitions depending
   upon the Concurrency level . So that we do not need to synchronize the whole Map Object.

3.  Null Key
     ConcurrentHashMap does not allow NULL values . So the key can not be null in
     ConcurrentHashMap .While In HashMap there can only be one null key .
 
 
4.  Performance 
     In multiple threaded environment HashMap is usually faster than ConcurrentHashMap . As    
     only single thread can access the certain portion of the Map and thus reducing the performance . 
     While in HashMap any number of threads can access the code at the same time .




------------------------------------------------------------------------------------------------------------
SET



Q6) which all classes implement Set interface?
Ans) A Set is a collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. HashSet,SortedSet and TreeSet are the commonly used class which implements Set interface.
  • SortedSet - It is an interface which extends Set. A the name suggest, the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface.
  • TreeSet - It is the implementation of SortedSet interface. This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized.
  • HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets.

Q16) Can a null element be added to a Treeset or HashSet ?
·         Ans) A null element can be added only if the set is of size 1 because when a second element is added then as per set defination a check is made to check duplicate value and comparison with null element will throw NullPointerException.
HashSet is based on hashMap and can contain null element.

Q21) Which data structure HashSet implements
Ans) HashSet implements hashmap internally to store the data. The data passed to hashset is stored as key in hashmap with null as value.

No comments:

Post a Comment