Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Requirement is to search a particular String in the Array of String value. To achieve this we need to have some set string values in a String array and secondly we need to have a String value to be searched.

Tips to Proceed...

1. Take counter
2. Iterate String and match the value on each iteration using equals() method.

Steps to do....

1. Take a counter count=0 .
2. Get the String to be searched.
3. Iterate the String Array and keep on searching from index=0 till length.
4. While looping keep on matching the string value with each index value of the Array.
5. If it get matched print "Match Found" and increment a counter.
6. If not matched then Print " No Match Found ".

Program :


public class Lab1{

    public static void main(String args[]){

 int count=0;
  
 String arr[]= new String[10];
 Scanner sc = new Scanner(System.in);
 System.out.println("Enter the String ");

 for(int i=0;i<10;i++){    // Iterate loop to store value in Array
     System.out.print((i+1)+". ");
     arr[i]=sc.next();
 }

 System.out.println("Enter the String to be searched");
 String s=sc.next();      // Enter value to be searched
  
 for(int i=0;i<arr.length;i++){ // Loop to search the Element
     if(s.equals(arr[i])){  
  System.out.println("Match Found");
  count++;
     }
 }
        
        if(count==0)     // Checking No Such Element Present in Array
          System.out.println("No Element Found ");

 System.out.println("No of Words Found in Number:"+count);
  
 }
}










The above question means that we need to execute some line of code which perform something before the main() method execution. As we know that when we execute our program JVM will call main() at very first , so it seems that its not possible to perform something before the main() method execution but is possible with the static initialization block and calling method while initializing static variable 

Important Points :

1. Static initialized will always be executed before main() method calling by JVM.
2. Final static variable can be initialized using static initialization block.

1st Approach by static initialization block: 

Program :

public class Lab1 {

    static {                       // static initialization block
 int sum=10+20;
 System.out.println("SUM:"+sum);
    }

    public static void main(String[] args) { // main method
 
       System.out.println("main() method");
    }

}

In the above program sum=10+20 will be executed before main() method and hence output will look like ,
SUM:30
main() method

NOTE : We can also call a static method from static initialization block which too can perform some task which will always counted before main() method execution.


public class Lab1 {

    static {                 // static initialization block
 int s=Lab1.sum(10,20);
        System.out.println("SUM:"+s);
    }

    public static int sum(int a,int b ){
        return (a+b);
    }

    public static void main(String[] args) { // main method
 
       System.out.println("main() method");
    }

}


Now in the above program static sum() method will be called first before main() method. And the output will look like ,

SUM:30
main() method

2nd Approach by Calling static method while initializing static variable :

public class Lab1 {

    static int x=Lab1.sum(10,20); 

    public static int sum(int a,int b ){
        System.out.println("SUM:"+(a+b));
        return (a+b);
    }

    public static void main(String[] args) { // main method
 
       System.out.println("main() method");
    }

}



In the above program at the time of call loading JVM will try to initialize the static variable 'x' here and while initializing it will call static method sum(). So this method will be executed before the main() method execution. The output will look like,

SUM:30
main() method








This question might be asked in as interview to judge logic on how you are going to achieve without providing you the length() method to calculate the String length easily.

Tips to Think ....

1. As we know that in Java String doesn't end with the NULL character with in C it ends with the NULL character.
2. To get to the end of String we have nothing as a mark in Java but in C we can check for the NULL character.
3. Now have to think to get the mark to the end of the String.
4. One way of doing is to caught the Exception if JVM will throw "StringIndexOutOfBoundsException" if we try to access the extra index of the String.

Steps to do :

1.Initialize a count i.e c=0;
2. Run the while loop making it true ( goes infinite looping ).
3. Within the loop access the String using charAt() at each index.
4. After accessing it last index if it try to access the next index which is not actually present in the memory will will raise to "StringIndexOutOfBoundsException" and we need to caught the exception within try-catch block.
5. Keep Increasing the counter after each iteration.
6. Print the Counter at the catch block will give the length of the String.
7. Use the break statement to break the infinite looping with the while(true).

Program

public class Lab1 {

    public static void main(String[] args) {
  
        String s1="sushant";
 int count=0;
 int i=0;
 while(true){
        try{
    s1.charAt(i);
           i++;
    count++;
        }catch(StringIndexOutOfBoundsException e){
    System.out.println("String Length is : "+count);
    break;
       }
  }
     }
}





This is a interview question can be asked in an experienced or fresher's interview to write a program which will add up all the integer value present in a string and print the added number.

Tips to think how to do it...

1. For this kind of problem always think of first matching the number in a String .
2. How you are going to match?
3. The only simplest way is with the help of ASCII of 0-9 .

Steps to do :

1. Take a int variable c=0.
2. Run the loop from 0 to String length.
3. Get the each index value using charAt() method which will return the char value.
4. Convert that char into int by typecasting or any other way.
5. Now check that ASCII fall into the range of 48-57 for 0-9 int number.
6. If it matches then first convert that number into integer using Integer.parseInt().
7. Then add with the c and store to the same variable i.e c.
8. Repeat from 3-7 till the end of the loop.
9. At the end of loop , Print c outside the loop.

Program


public class Lab1 {

   public static void main(String[] args) {
 
 String s="s16u7ty9";
 int c=0;
 for(int i=0;i<s.length();i++){
    char ch=s.charAt(i);         // Getting each char from String
    int x=(int)ch;               
    for(int y=48;y<=57;y++){       // Loop for checking the ASCII
       if(x==y){
   int num=Integer.parseInt(""+ch); //Getting the int value
   c=c+num;
       }
    }
 }
 System.out.println("Total Sum:"+c); // Final sum 

   }

}







This is one of the important and mostly asked question in fresher and experienced interview. Singleton class means a class with only one object. It will have only one object which will be returned always when ever we try to create the object of singleton class. We can create our own singleton class. Interviewer will ask you to write your own singleton class, for that you need to remember following points to create your own singleton class :

a) Declare a static resource ( Object of the singleton class ) .
b) Create that resource in the static initialization block so that will be creating at the class loading time.
c) There must be a static method which return the resource.
d) Most importantly Constructor should be made private. 

Hello.java

class Hello{

   static Hello hello;
   
   private Hello(){}

   static {

     hello = new Hello(); 

   }

   public static Hello getHello(){

        return hello;
   
   }

}


A. java

class A{

  public static void main(String[] args){

     Hello h = Hello.getHello();  // return the object created at class loading.
     Hello h1 = Hello.getHello(); // It will also return the same object. 

  }
}




Hello class is the singleton class in which Hello is created in the static initialization block so that object will be created once which is at the time of class loading and will be returned as many times we try to create an object of Hello class. 

Why Constructor is made private ?

It is because object shouldn't be created directly using new operator.

Explanation :

As the Hello class ( Singleton class ) will be loaded the static initialization block will be executed and hence resource will be created and then whenever we call getHello() method it will always return the object created at the time of class loading. 

This is one of the common question to be asked in interview to judge your basic level of knowledge. We all know that String is immutable which means that once object created cannot be modified or if try to modify, it will create another String literal in the String pool. So this proves that String is immutable, but this is we are proving theoretically. Now if interviewer ask you to prove the same by writing programs then you will be doing like this,

class A{

  public static void main(String[] args){

     String s="java";  // Create a object in String pool.

     s = s + "java" ; // Create another object with "javajava" as 
                         String literal in the String pool

  }


It is a public abstract interface. Many classes and interfaces are extending this abstract interface for different purposes.


SuperClass of Appendable:-

From java.lang package -

StringBuffer

StringBuilder

From java.io package -

BufferedWriter

CharArrayWriter

FileWriter

FilterWriter

OutputStreamWriter

PipedWriter

PrintStream

PrintWriter

StringWriter

Writer

From java.nio package - 

CharBuffer

From java.rmi.server package -

LogStream

All the above classes and interfaces are designed for different purposes and used all abstract method defined in the AbstractStringBuilder class for their own way of implementing the code by overriding these four methods.  


Methods of AbstractStringBuilder class


public abstract Appendable append(CharSequence cs) throws IOException;

public abstract Appendable append(CharSequence cs, int i, int j)  throws IOException;

public abstract Appendable append(char cs) throws IOException;





It is a private class or more specifically we can say its a ' private - package ' class i.e it is declared as not public and as abstract. As it was not there before the release of JDK 1.5 and was first introduced in java 5.0 as the superclass for both StringBuffer and StringBuilder.  Initially before JDK 1.5 there was only one class i.e StringBuffer ( which is thread safe ) and was extending Object class, but later with the release of JDK 1.5 AbstractStringBuilder and StringBuilder was introduced and now StringBuffer is extending AbstractStringBuilder . 

What is private - package class ?
If we declare a non-public class in a package whose scope will be within that package only , in other terms we create any instance of the class outside the package and hence can be considered as private class and called as private-package class. 


Aim behind intoducing AbstractStringBuilder ?
As we knowing that there are two identical class i.e StringBuilder and StringBuffer expects StringBuffer is thread safe and where as StringBuilder is not. Thus all the methods and their implementation are almost identical so instead of writing two times for both the classes they introduce a non-public abstract class i.e AbstractStringBuilder class which has same method with implementation and hence both are classes are using its implementation. 


Interesting facts of AbstractStringBuilder 

If we notice in AbstractStringBuilder class many method returns its own class instance only and its sub-classes i,e StringBuffer and StringBuilder both the classes override the methods of AbstractStringBuilder class and restrict the return type to their own class instance, this narrowing the return type by overiding the method in its sub-class is termed as ' co-variant return ', which is seen with the release of JDK 1.5 and with the later versions.    


Constrcutors of AbstractStringBuilder class


  AbstractStringBuilder(int i)

Instance variables of AbstractStringBuilder class

1. char[]   value;
2. int        count;
3. static final int[]    sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, 2147483647 };

Methods of AbstractStringBuilder class

  
  public int capacity()

  public void ensureCapacity(int i)

  void expandCapacity(int i)

  public void trimToSize()

  public void setLength(int i)

  public char charAt(int i)

  public int codePointAt(int i)

  public int codePointBefore(int i)

  public int codePointCount(int i, int j)

  public int offsetByCodePoints(int i, int j)

  public void getChars(int i, int j, char[] c, int k)

  public void setCharAt(int i, char c)

  public AbstractStringBuilder append(Object obj)

  public AbstractStringBuilder append(String s)

  public AbstractStringBuilder append(StringBuffer sb)

  public AbstractStringBuilder append(CharSequence cs)

  public AbstractStringBuilder append(CharSequence cs, int i, int j)
  
  public AbstractStringBuilder append(char[] ch)
  
  public AbstractStringBuilder append(char[] ch, int i, int j)

  public AbstractStringBuilder append(boolean b)

  public AbstractStringBuilder append(char c)

  public AbstractStringBuilder append(int i)

  static int stringSizeOfInt(int i)

  public AbstractStringBuilder append(long l)

  static int stringSizeOfLong(long l)

  public AbstractStringBuilder append(float f) 

  public AbstractStringBuilder append(double d)

  public AbstractStringBuilder delete(int i, int j)

  public AbstractStringBuilder appendCodePoint(int i)

  public AbstractStringBuilder deleteCharAt(int i)
  
  public AbstractStringBuilder replace(int i, int j, String s)
  
  public String substring(int i)

  public CharSequence subSequence(int i, int j)

  public String substring(int i, int j)

  public AbstractStringBuilder insert(int i, char[] c, int j, int k)
  
  public AbstractStringBuilder insert(int i, Object o)

  public AbstractStringBuilder insert(int i, String s)

  public AbstractStringBuilder insert(int i, char[] c)

  public AbstractStringBuilder insert(int i, CharSequence cs)

  public AbstractStringBuilder insert(int i, CharSequence cs, int j, int k)

  public AbstractStringBuilder insert(int i, boolean b)

  public AbstractStringBuilder insert(inti, char c)

  public AbstractStringBuilder insert(int i, int j)

  public AbstractStringBuilder insert(int i, long l)

  public AbstractStringBuilder insert(int i, float f)

  public AbstractStringBuilder insert(int i, double d)

  public int indexOf(String s)

  public int indexOf(String s, int i)

  public int lastIndexOf(String s)

  public int lastIndexOf(String s, int i)

  public AbstractStringBuilder reverse()

  public abstract String toString();

  final char[] getValue()



It is the only abstract interface in the java.lang package. It is the basic interface containing non-implemented methods all regarding and involving characters only like length() , charAt() etc and a special method i.e toString() method. It is the super class of many of the classes and interfaces, which are shown below.

Implementation class for the abstract method declared in the in the CharSequence interface are:-

AbstractStringBuilder (c)   of [ java.lang package ]

String (c)                             of [ java.lang package ]

StringBuffer (c)                   of [ java.lang package ]

StringBuilder (c)                 of [ java.lang package ]

CharBuffer (c)                     of [ java.nio package ]

Segment (c)                         of [ javax.swing.text package ]

Note : (c) represent the class. All the above mentioned names are java class.


Methods of the CharSequence interface :

public abstract int length();

public abstract char charAt(int i);

public abstract CharSequence subSequence(int i, int j);

public abstract String toString();


Some of the important points of CharSequence interface :

* It was first introduced with the release of JDK 1.4.
* CharSequence is originally is the sequence of character and which combines to form a String only,
so we can call a string as the CharSequence.



Java is using java.lang as the default package.All the basic functionality for writing a simple java program are there written in the form of classes and interfaces and also designed some of the possible and probable exception and error raised while compiling and executing programs. Here i am categorizing all the exception, error , abstract class , final classes, interfaces etc....

Classes in java.lang packages


List of Abstract Interfaces (1)

CharSequence

List of Abstract classes (5)

AbstractStringBuilder

ClassLoader

Enum

Number

Process

List of Final classes (18)

Boolean 

Byte

Character

Class

ConditionalSpecialCasing

Double

Float

Integer

Long

Math

ProcessBuilder

ProcessEnvironment

ProcessImpl

Short

String

StringBuilder

StringBuffer

System


List of Classes (18)

CharacterData00

CharacterData01

CharacterData02

CharacterData0E

CharacterDataLatin1

CharacterDataPrivateUse

CharacterDataUndefined

Error

Exception

Object

Runtime

SecurityManager

Shutdown

StringCoding

Thread

ThreadGroup

ThreadLocal

Throwable

List of Exception Classes (25)

ArithmeticException

ArrayIndexOutOfBoundsException

ArrayStoreException

ClassCastException

ClassNotFoundException

CloneNotSupportedException 

EnumConstantNotPresentException

IllegalAccessException

IllegalArgumentException

llegalMonitorStateException

IllegalStateException

IllegalThreadStateException

IndexOutOfBoundsException

InstantiationException

InterruptedException

NegativeArraySizeException

NoSuchFieldException

NoSuchMethodException

NullPointerException

NumberFormatException

RuntimeException

SecurityException

StringIndexOutOfBoundsException

TypeNotPresentException

UnsupportedOperationException


List of Error Classes (18)

AbstractMethodError

AssertionError

ClassCircularityError

ClassFormatError

ExceptionInInitializerError

IllegalAccessError

InstantiationError

InternalError

LinkageError

NoClassDefFoundError

NoSuchFieldError

NoSuchMethodError

StackOverflowError

UnknownError

UnsatisfiedLinkError

UnsupportedClassVersionError 

VirtualMachineError

VerifyError 



Java Packages is the collection of pre-defined classes interfaces and thus all these classes contains both the implemented and non-implemented methods. Java is using java.lang package as the default package. Below are the list of some of the packages in java.

java.lang package

java.util package

java.io package

java.math package

java.rmi package

java.sql package

A java package is the collection of similar types. After Writing all the required pre-defined classes in java, those are being categorized in different categories and hence are termed as packages. For ex-

java.lang packages contains all the basic operations which are required for writing a simple java application and hence is the default package for any java class. Like that ,

java.io packages contains all the required classes and functionality for doing input and output operations using file and console.

As the java vendors has categorized the different classes in different packages, the same we can do while developing our own java application, which makes us to say that packages can be used to search and locate the classes and interfaces. Best practice is to always keep the classes in a packages which must be followed by three dots naming convention.

For ex-  com.def.core ---> A package name , followed with three dots.

Note: Package must always be the first statement of any java class and can be only one package statement in each java file.

package is the keyword used before declaring any package name in the java source file.
For ex-    package  com.def.core.* ;

In the above statement .* indicate we are supposed to use all the classes defined in the com.def.core package.








Basically there are three way to convert an primitive value to string so that if we have requirement to use that primitive as a string then we can you this concept and way of conversion but now the point is out of these three way which one is the best and take less time and doesn't have any performance issue.

The three ways of converting primitive into string are :

1. Using Empty string
2. Using valueOf() with String class
3. Using toString() with Wrapper class.

Using Empty String

With the use of an empty string we are creating an new string in the constant string pool and if that string literal is already present in the pool then it will create the object in the heap which points to the pool literal object and return the heap memory address to its original object. For ex-

public class prog {

    public static void main(String[] args) {

 String s=""+10;
 String x1="java10";
 String x2="java"+10;
 System.out.println(x1.equals(x2)); // true
 System.out.println(x1==x2);    // false
 System.out.println(x1.hashCode()==x2.hashCode());//true

    }

}

In the above example ( x2== x1 ) will give false that means s2 and s1 both are different object and which proves that x1 literal get stored in string pool first and then while storing s2 literal it will first check the pool, if present then it will create an new object in the heap memory if we are using new operator that means internally  String is created with the use of ' new ' operator. 

Using valueOf() with String class

Another option for making a primitive value to string value is the use of valueOf( int i ) defined static in the String class, which return string value and take integer value from its integer type parameter. Here i have used only int type but valueOf() can be used with any primitive type. For ex- 

public class prog {

    public static void main(String[] args) {

 int x=10;
 String s1=String.valueOf(x);
 System.out.println(s1); 
 
     }

}

using valueOf() which it self used Integer.toString( int, int ) internally to convert it into string type value.

Using toString() with Wrapper class

Every wrapper class is having overridden toString() method with parameter as any primitive type. So we have one more option to make a primitive data as string type by using toString( int i ) . Here also i have used int type but toString() is available with any primitive type as argument. For ex-

public class prog {

    public static void main(String[] args) {

 int x=10;
 String s1=Integer.toString(x);
 System.out.println(s1); 
 
     }

}

toString() method internally uses character array concept to create an String. So this is the most efficient way of converting into string value.

So it is recommended to use any of the either valueOf() or toString().

Note: It is not recommended to convert with the use of empty string . 
String is a reference data type and hence string literals are treated as object and get stored in the string constant pool. We must have to define any string within double-quote otherwise it will give compilation error. String can be represented in two form either with using ' new ' operator or without using new operator.

Two way of string representation in java :
1. Without using new operator
2. With using  new operator.

Without using new operator

String can be represented without using new operator that means we are directly assigning string value to its reference. If we are defining like this then first it will search for the string literal whether it is present in the String pool or not. If it is present then simply it returns the reference of the existing object to the current reference. For ex-

public class A {

 public static void main(String[] args) {

    String s = "java";
           String s1= "java";
           System.out.println(s==s1);  // true 
           System.out.println(s.hashCode()==s1.hashCode()); // true
 }
}


In the above program with the first statement i.s String s="java", it will search in the string pool whether that string literal is present or not. If it is present in the pool then it will return the reference to the reference variable 's' which also starts pointing to that object.



With the second statement again it will start searching in the string pool , if present then return the reference variable and if not then create the object in the pool and then return the reference. 

Important points regarding Creating string without new operator

1. First search in the string pool whether string literal is present or not.
2. If present in the pool then return the reference.
3. If not present in the pool then crate and object and return the reference of that object.

With using new operator 

With the help of new operator it is definitely going to create an object. First it will search in the string pool that whether that string literal is present or not , if not present then it will create an object in the pool itself and if present then it will create an object in the heap memory and that memory will hold the reference of the already present literal in the pool. So with the above statement its confirm that with the use of new operator it is going to create an object but in heap or in pool it all depends upon the string literal's presence in the pool.
For ex- 

public class A {

 public static void main(String[] args) {

    String s = new String("java");
           String s1= new String("java");
           System.out.println(s==s1);  // true 
           System.out.println(s.hashCode()==s1.hashCode()); // true
 } 
}

In the above for the first statement it will search in the pool whether string literal " java " is present in the pool or not , if not then create the object in the pool itself and if present in the heap memory and return the reference of the already stored object to the reference variable " s ". 

For the second its the string literal " java " is surely present in the pool so JVM will create object in the object in the heap memory and return the reference to that object and that object reference value is returned to the " s1 " reference variable.

Example with and without new operator 

public class A {

 public static void main(String[] args) {

           String s="java";  //without new operator 
           String s1="java";
    String s2 = new String("java"); // with new operator
           String s3= new String("java"); // with new operator
           System.out.println(s==s1);  // true 
           System.out.println(s.hashCode()==s1.hashCode()); // true
 } 
}

From the above example:

String s = "java" ---> Create object in the String pool ( if not present )
String s="java"---> Return the reference of the object present in the pool .
String s1= new String("java") --> Create the String object in the heap.
String s2=new String("java")--> Create the String object in the heap.

Diagram showing how memory is assigned in the heap and string pool.



In the above diagram we can see that s2 and s3 contain the reference of the object created in the heap memory and which itself contains the reference of the string pool object.


But in case of without using new operator, always reference value is returned and it is not going to create any object in the heap memory. This is the major difference between the string object with and without using new operator. 
It is the manually implemented coding for doing cloning. This concept has came to overcome the limitation found with shallow cloning which fails to clone the data member. Through deep cloning we can be able to cover up the problem with the shallow cloning. Now with the help of deep cloning we can able to clone the object members as well but to achieve this we don't have any predefined method, so we need to write our own code. Deep Cloning is just a term to indicate that we are also cloning the object members.

To achieve deep cloning we need to override the clone method and need to create an object of the object member so that we have other object  and need to copy return that object to the clone object.

See the example below then you will be more clear about the above statement written.

Example showing Deep Cloning

class E{
    int y=40;
    String s1="tutorial";
    public E(int y2, String s12) {
 this.y=y2;
 this.s1=s12;
   }
   public E(){}
 }

public class deepCloning implements Cloneable{

    int x= 20;
    String s="java";
    E e;
  
   deepCloning(int x2, String s2, E e1){ //To initialize the property 
 this.x=x2;
 this.s=s2;
 this.e=e1; 
   }
   public deepCloning() {
 e=new E();
   }
   protected Object clone(){   //overridden clone() method 
 deepCloning d2=null;
 E e1= new E(this.e.y,this.e.s1);
 d2=new deepCloning(this.x,this.s,e1);
 return d2;
   }

public static void main(String[] args) {

        deepCloning d = new deepCloning();
 deepCloning d1=null;
 try{
  d1=(deepCloning)d.clone();// Cloning statement 
 }catch(Exception e){
  e.printStackTrace();
 }
 System.out.println(d);
 System.out.println(d1);
 d1.e.y=30;
 System.out.println(d1.e.y);
 System.out.println(d.e.y);

 }  
}

In the above code we can see that clone method is overridden to our class in which we try to create and separate object for the class E and also create and object of the current object to return the class E object so that the clone object will have that reference value for its Object member. 

And all the constructor used in the respective class to initialize the property otherwise there may have chance to throw NullPointerExcpetion
It is a default cloning in java implemented by the Java vendor simply by using one predefined method in the Object class i.e clone().  Using shallow cloning we can only be able to clone the member of the class but fails to clone object members of the class. To clone the object member we need to write our own code which is also called as Deep Cloning.

To achieve shallow Cloning we need to implement Cloneable interface and need to call the clone() method with the object of the class whose object is to be cloned but it returns the Object class object so need to type-cast to its respective class type.

Example showing shallow cloning :

public class deepCloning implements Cloneable {

    int x= 20;
    String s="java";
 
  public static void main(String[] args) {
     deepCloning d = new deepCloning();
     deepCloning d1=null;
      try{
 d1=(deepCloning)d.clone(); // Cloning statement 
      }catch(Exception e){
 e.printStackTrace();
       }
 System.out.println(d);    // Original Object
 System.out.println(d1);   // Cloned Object
        System.out.println(d.x);  // 20 as output
 System.out.println(d1.x); // 20 as output
 d1.x=30;                  // Value changed to 30 by 
                                     cloned object
 System.out.println(d.x);  // 20 as output
 System.out.println(d1.x);//30 as output(not affecting d) 

 }
}

In the above code
d   = Original Object
d1 = Cloned Object
If we try to change the object d will not reflect on object d1 and vice-versa.

What if we are not implemeting the Cloneable interface ?
If we are not implementing Cloneable then it will Runtime error saying CloneNotSupportedException. So its mandatory to implement Cloneable Interface which is marker interface to indicate JVM that the object of that implementing class is to be cloned.

Example showing how shallow Cloning fails to clone Object member

class F{

     int x=30;
     String s="java";
}

   public class deepCloning implements Cloneable{

 int x=40;
 String s1="tutorial";
 F f;

 deepCloning(){
     f = new F();
 }
   public static void main(String[] args) {
 
 deepCloning sc = new deepCloning();
 deepCloning sc1=null;
 try{
      sc1=(deepCloning)sc.clone();//Cloning statement 
 }catch(Exception e){
      e.printStackTrace();
 }
 System.out.println(sc.f.x);  // 30 as output
 System.out.println(sc1.f.x); // 30 as output
 sc.f.x=60;                 // changing the x value of f
 System.out.println(sc.f.x); // 60 as output
 System.out.println(sc1.f.x);// 60 as output
 }

}

In the above code even if i tried to change the value of  instance variable x of class F through deepCloning class object, the value get changed but by accessing with the cloned object it result the changed value which indicated that cloned object's object member f is also pointing to the same object. To avoid this type of problem we have the concept of deep cloning. We can see the last two line of the above program that result of both line even if in the previous line i modified the value of x to 60. 


Diagrammatic representation of the above program

Diagram of Shallow Cloning

                                       ( Above diagram showing the shallow cloning )

What is the problem with the shallow Cloning ?

While Cloning it fails to clone the object member. As we can see in the above example while cloning it simple copies the reference value of the ' f ' to the cloned object which also point the object which was pointing by the original object;s object member. 
Cloning is a concept used to create a new object of the existing object. It means creating another object in the memory same as the existing one by copying the content of it.

For cloning a object java vendor has provided a method i.e clone() method in the Object class which is used to clone the object.

Clone() method is defined as protected in the Object and return the Object class object. Signature of the clone() is :-

protected Object clone() throws CloneNotSupportedException

This method throws one exception i.e java.lnag.CloneNotSupportedException, that means we need to handle this exception while using clone() in our program or we need to define the same exception with the throw keyword in the sub-class. 

We need to implement Cloneable interface to that class whose object we want to clone because by implementing JVM will got to know that this class is to be cloned.Syntax for Cloneable interface :

public interface java.lang.Cloneable{}

Cloneable interface is a marker interface that means without any method or member defined or we can say that empty interface. 

There are two types of cloning possible in java

1. Shallow Cloning ( default Cloning )
2. Deep Cloning ( Manual Cloning ) 

Shallow Cloning 

It is the Default implementation of the clone() method in the Object class. If we are using clone() method then it do shallow cloning. It is used to clone the data members of the existing class but fails to clone any of the member object. To overcome this limitation of the Shallow cloning there is a concept given by the java vendor is deep cloning. 

Deep Cloning 

It is manual implementation which has to be done by user itself. As not predefined method is available so we need to write our own code to do deep cloning and it is used to fulfill the limitations of the shallow cloning as it fails to clone the object member.   

It is a concept in java to achieve the Dynamic / Run-time polymorphism. It is the process of assigning sub-class object in super type reference later if needed that sub-class object can be type-caste into its super type. Dynamic dispatch can be achieved only with the instance member.

Important point regarding dynamic dispatch

1. If we are trying to access instance member with dynamic dispatch concept then it will access sub-class overridden method.

2. If we are trying to access static member with the dynamic dispatch concept then it will access super-class method as because compiler internally replace the super-class reference variable with its class name.

Example showing dynamic dispatch with instance and static method.

class B {

 public static void display(){
  System.out.println("super-class static method");
 }
 public void add(){
  System.out.println("super-class instance method");
 }
}

public class A extends B{
 
 public static void display(){
  System.out.println("sub-class static method");
 }
 public void add(){
  System.out.println("sub-class instance method");
 }
 
 public static void main(String[] args) throws Exception {
  
  B b = new A(); // Dynamic dispatch 
  b.display();  // Calling static method
  b.add();     // Calling instance method
 }

}

In the above code the statement B b = new A() is used to store sub-class in its super-class and tried to access static method " display " which will super-class display() method as because compiler internally convert the b.display() into B.display() but in case of instance it will access with the object only that's why it call the overridden method in sub-class. 

Note : The same will happen with the static and instance variable. With dynamic dispatch concept accessing static variable will access super-class static variable but accessing instance variable will access sub-class instance variable.  

Interface is a keyword in java and also a concept in java to over come the limitation of not supporting multiple inheritance by java. Now with the concept of interface we can have implement multiple interface full filing the concept of a " single class extending more than one class ". In the case of class we can extend only one but with the interface we can implement more than one interface.

Click here to know why java is not supporting multiple inheritance

Syntax to declare an interface :-
interface < interface_name > { }

Syntax to implement an interface :-
class < class_name > implements interface < interface_name > { }

Syntax to implement an interface :-
class < class_name > implements  interface < inter_nm1 >, < inter_nm2>......< inter_nmN > { }

Syntax to extending another interface :-
class < class_name > implements  interface extends < inter_nm1 >, < inter_nm2>......< inter_nmN > { }

Important point regarding interface in java

1. " interface " keyword is used to define any interface in java.

2. We have to use ' implement ' keyword for implementing an interface, extends cannot be used with interface. 

3. Possible to implement more than one interface with single class. 

4.  Interface are fully abstract class. So no need to make an interface as abstract as it is by-default " public abstract ".

5.  An interface can extends another interface but cannot extends/ implements another class. 

6. We cannot declare any instance member inside an interface as it is fully abstract. 

7. Variable declared inside an interface are by default - " public final static " or we can use these modifier explicitly also. 

8. We cannot declare a method as final and static in an interface.

9. We cannot use private , protected , transient and volatile keyword with the variable declared in an interface.

10. We cannot use synchronized and native with the method declared in an interface. 

11. Inner class in an interface are by-default " public static " .

12. We cannot define constructor, instance and static initialization block in an interface. 

13. By-default method declared in an interface are " public abstract " or we can use these keyword explicitly also. 

14. We cannot create an object of an interface as it is fully abstract class.  

15. " .class " file is generated by the compiler for every interfaces. 

Some of the important questions regarding interface with answer

Q1. Why we cannot define instance variable in an interface?
 --> Defining instance variable in an interface is restricted to save memory as because instance variable is inherited in its sub-class.

Now think if we have 3 interfaces(A, B and C)  and 1 class (D).
Interface B and C are extending A and Class D is implementing B and C. That means if declaring instance variable is allowed then for each instance variable as separate copy is also created in the interfaces B and C extending A and those copy are again copied to the class D. So we have many duplicate copies in the sub-classes.

For ex- Now if we have define 100 instance variable then it will create 100 copy in B and 100 in C and finally class D contain total of 100+ 100= 200 unnecessary copy which will obviously take memory as it an instance variable.
So to solve this problem declaring instance variable is restricted instead static is allowed which will create one memory.  

Q2. Why we cannot define variable defined in an interface as private and protected ?
        There are two reason behind it :-

  1. It is because by-default it is using public so we cannot define both public and protected to a single variable. 
  2. As interface doesn't have any instance method implementation and we need to access private member with the help of any method as because we cannot create an object of an interface and with cannot directly access with the sub-class object so need some method implementation which is not possible.   

When we use an abstract modifier before the name of any user-define class then it is called as an abstract class. Abstract class in java has only method signature whose implementation must be in its sub-classes.

Important points regrading Abstract class

1. It cannot be instantiate means we cannot create object of an abstract class.
2. An abstract class can have instance member.
3. Abstract class doesn't have any method implementation instead can have only method declaration.
4. We cannot make an inner class as abstract.
5. We cannot use static method but can use static variable in the abstract class.
6. Extending abstract class means we need to override the abstract methods defined in the abstract class.
7. If we don't want to override abstract in its sub-class then declare that sub-class as abstract.
8. An abstract class may or may not have an abstract method.
9. Constructor of the abstract class will be used to instantiate the abstract class instance variable.
10. Overridden abstract class methods will be accessed by its sub-class object.
11. We can be able to create and reference variable for an abstract class.

Why we cannot instantiate an abstract class?
As because we are not implementing abstract method while declaring it in abstract class. So if an user have any chance to create an instance of abstract class means can able to call abstract method with that object but we don't have any body while declaring it in abstract so no need of calling an empty body method. That's why we are not allowed to create an instance of an abstract class.

If we are not allowed to create and instance of an abstract class then how it can have an instance variable?
We can be able to access instance member of any super-class with its sub-class object therefore we can be able to access the instance member of any abstract class with the object of its sub-class.

Who is responsible to initialize the instance member of abstract class and how?
Its obvious that constructor is always responsible to initialize any instance member of any class. Here by creating its sub-class object will call its constructor and with the super implementation in it, will be able to class its super-class constructor i.e abstract class constructor and finally that constructor is responsible to initialize its instance member.

Why we cannot use static keyword with the abstract method?
By using static keyword with the abstract method will make it eligible to call it with its class name but no need of calling an empty body method. So it is restricted to use static with the abstract method.

Why we need to override abstract method in its sub-class?
It is because an user can be able to call abstract method with its sub-class object so we need to override so that it will call an overridden implemented method.

What will happened if we are extending an abstract class with another abstract class?
Then no need to override the abstract method in its sub-class because sub-class itself is an abstract class.

Why we can create an reference variable of an abstract class?
It is because creating an reference variable doesn't instantiate the member of the abstract class and hence contain null means not referring any object.

Use of an abstract class

1. When we have only static member in our class which can able be accessed with its class name so no need of creating object unnecessarily.So for restricting user to create an object declare that class as abstract.

2. It is used to when the user want to have their own implementation. So declaring a method as abstract will give a chance to an user to have their own implementation for same method name.

An example showing an abstract class with some valid and invalid statement.

abstract class A{

 static int x;                 // valid
 int y;                       // valid
 abstract void add();         // valid
 static abstract void sub(); // invalid as static is not allowed.
}
public class E extends A {

 void add(){}       //Compulsory to override abstract method 
 
 public static void main(String[] args) {
  E e = new E();
  System.out.println(A.x);
  A a = new A();        // Invalid 
 }
}
Abstract is a keyword in java. So its a reserved word in java. general meaning of abstract is to hide the implementation, only show the outer structure. Now in computer science its meaning is that user can have their own implementation with abstract method.

Where we can use abstract keyword ?
Abstract can be used with class and method.

By using abstract with the method a user can able to have their own implementation according to their wish. Its the facility given by the java vendor to the user to have their own implementation.

Abstract with class

Using abstract modifier before the class name can make a class as abstract. Making a class as abstract means we cannot instantiate that class.

Syntax :

abstract  < access_modifier > class < class_name > {  } 

< access_modifier > --> Only public is used with abstract . Private and protected are not used.

To know more about abstract class Click here !

Abstract with method

Declaring abstract modifier with the method name will make that method as abstract. An abstract method cannot have their implementation where it is declared, it must be override in its sub-classes.

Syntax :

abstract  < access_modifier > < return_type > < method_name > {  } 

< access_modifier > --> Only public and protected are used. Private cannot be used with it.


Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic