Skip to main content

Interview question on java for Experience

  1. Why does StringBuffer/StringBuilder not override equals or hashCode?
    Ans:   Actually behind this everything depends upon hashcode code value. To understand this concept lets take an example :
String str1 = new String("chandan");
String str2 = new String("chandan");

HashMap hm = new HashMap()
hm.put(str1,"hello");
hm.put(str2,"bye");
final hm:
hm = { chandan=bye }
In above code, str1 and str2 are two different String objects. It should be added in HashMap ? Answer is NO. Because before inserting/putting value in HashMap, it internally checks and compare hashCode value of str1str2. Both retun same hascode value because String class override equals() and hashcode() method. So upon executing hm.put(str2,"bye"); first key will get override with new value. Now try this :
StringBuilder sb1 = new StringBuilder("chandan");
StringBuilder sb2 = new StringBuilder("chandan");

HashMap hm = new HashMap()
hm.put(sb1,"hello");//sb1 and sb2 will return different HashCode 
hm.put(sb2,"bye");// StringBuffer/StringBuilder does not override hashCode/equals methods
final hm:
{chandan=hello, chandan=bye}
Both value will be added in hashMap because sb1 and sb2 both returns different hashcode. StringBuilder/ StringBuffer does not override equals() and hashCode() method.

Question:- IS Java  Pass by value or pass by reference ?
Ans:- Java always passes arguments by value NOT by reference.
 e.g.:-   public class Test {

       public static void main(String[] args) {
     
              Integer i = new Integer(10); 
              Integer j = new Integer(20); 
              swap(i, j); 
              System.out.println("i = " + i + ", j = " + j); 
           } 
       // swap() doesn't swap i and j 
         public static void swap(Integer i, Integer j)  
         { 
          Integer temp = new Integer(i); 
          i = j; 
          j = temp; 
       }  }

Output: i = 10, j = 20 Like C/C++, Java creates a copy of the variable being passed in the method and then do the manipulations. Hence the change is not reflected in the main method.

Question :- What is concept of Cloning and Difference between  Shalow Copy and Deep Copy in java  ?
Answer :-  Cloning is a process of creating an exact copy of an existing object in the memory. In java, clone() method of java.lang.Object class is used for cloning process. This method creates an exact copy of an object on which it is called through field-by-field assignment and returns the reference of that object. Not all the objects in java are eligible for cloning process. The objects which implement Cloneable interface are only eligible for cloning process. Cloneable interface is a marker interface which is used to provide the marker to cloning process.

Shalow Copy:-The default version of clone() method creates the shallow copy of an object. The shallow copy of an object will have exact copy of all the fields of original object. If original object has any references to other objects as fields, then only references of those objects are copied into clone object, copy of those objects are not created. That means any changes made to those objects through clone object will be reflected in original object or vice-versa. Shallow copy is not 100% disjoint from original object. Shallow copy is not 100% independent of original object.

    class Course
    {
        String subject1;
        String subject2;
        String subject3;
        public Course(String sub1, String sub2, String sub3)
        {
            this.subject1 = sub1;
            this.subject2 = sub2;
            this.subject3 = sub3;
        }
    }
    class Student implements Cloneable
    {
        int id;
        String name;
        Course course;
        public Student(int id, String name, Course course)
        {
            this.id = id;
            this.name = name;
            this.course = course;
        }
        //Default version of clone() method. It creates shallow copy of an object.
        protected Object clone() throws CloneNotSupportedException
        {
            return super.clone();
        }
    }
    public class ShallowCopyInJava
    {
        public static void main(String[] args)
        {
            Course science = new Course("Physics", "Chemistry", "Biology");
            Student student1 = new Student(111, "John", science);
            Student student2 = null;
            try
            {
                //Creating a clone of student1 and assigning it to student2
                student2 = (Student) student1.clone();
            }
            catch (CloneNotSupportedException e)
            {
                e.printStackTrace();
            }
            //Printing the subject3 of 'student1'
            System.out.println(student1.course.subject3);         
            //Changing the subject3 of 'student2'
            student2.course.subject3 = "Maths";
            //This change will be reflected in original student 'student1'
            System.out.println(student1.course.subject3);      
        }
    }

Output : Biology
                Maths

Deep Copy:-
Deep copy of an object will have exact copy of all the fields of original object just like shallow copy. But in additional, if original object has any references to other objects as fields, then copy of those objects are also created by calling clone() method on them. That means clone object and original object will be 100% disjoint. They will be 100% independent of each other. Any changes made to clone object will not be reflected in original object or vice-versa. 

To create a deep copy of an object, you have to override the clone() method as demonstrated in the below example
 
   class Course implements Cloneable
    {
        String subject1;
        String subject2;
        String subject3;
        public Course(String sub1, String sub2, String sub3)
        {
            this.subject1 = sub1;
            this.subject2 = sub2;
            this.subject3 = sub3;
        }
        protected Object clone() throws CloneNotSupportedException
        {
            return super.clone();
        }
    }
    class Student implements Cloneable
    {
        int id;
        String name;
        Course course;
        public Student(int id, String name, Course course)
        {
            this.id = id;
            this.name = name;
            this.course = course;
        }
        //Overriding clone() method to create a deep copy of an object.
        protected Object clone() throws CloneNotSupportedException
        {
            Student student = (Student) super.clone();
            student.course = (Course) course.clone();
            return student;
        }
    }
    public class DeepCopyInJava
    {
        public static void main(String[] args)
        {
            Course science = new Course("Physics", "Chemistry", "Biology");
            Student student1 = new Student(111, "John", science);
            Student student2 = null;
            try
            {
                //Creating a clone of student1 and assigning it to student2
                student2 = (Student) student1.clone();
            }
            catch (CloneNotSupportedException e)
            {
                e.printStackTrace();
            }
            //Printing the subject3 of 'student1'
            System.out.println(student1.course.subject3);         
            //Changing the subject3 of 'student2'
            student2.course.subject3 = "Maths";
            //This change will not be reflected in original student 'student1'
            System.out.println(student1.course.subject3);       //Output : 
        }
    }

Output : Biology
                Biology

Question :What is Marshalling and Unmarshalling ?(Detail)
Ans:
Marshalling :- 
It is process of converting the data or object into   byte stream.
Unmarshalling: - It is process of converting byte stream back into its origional object.

Comments

Popular posts from this blog

Mockito interview Questions

1.       Question 1. What Is Mockito? Answer : Mockito allows creation of mock object for the purpose of Test Driven Development and Behavior Driven development. Unlike creating actual object, Mockito allows creation of fake object (external dependencies) which allows it to give consistent results to a given invocation. 2.       Question 2. Why Do We Need Mockito? What Are The Advantages? Answer : Mockito differentiates itself from the other testing framework by removing the expectation beforehand. So, by doing this, it reduces the coupling. Most of the testing framework works on the "expect-run-verify". Mockito allows it to make it "run-verify" framework. Mockito also provides annotation which allows to reduce the boilerplate code. 3.       Question 3. Can You Explain A Mockito Framework? Answer : In Mockito, you always check a particular class. The dependency in that class is injected using m...

JAVA Expert Interview Questions Answers 2017

Java Basics ::  Interview Questions and Answers Home  »  Interview Questions  »  Technical Interview  »  Java Basics  » Interview Questions 1.     What is the difference between a constructor and a method? A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator. 2.     What is the purpose of garbage collection in Java, and when is it used? The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. 3.  ...

Java Example Program to Convert List to Set

import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class ListToSet {  /**   * @author Amarjit Kumar   * @category interview questions   *   * Description: Convert List to set in java with example program   *   */  public static void main(String[] args) {   ArrayList<String> arrList= new ArrayList<>();   arrList.add("Java");   arrList.add("Java");   arrList.add("List to String");   arrList.add("Example Program");   Set<String> strSet = new HashSet<String>(arrList);   System.out.println(strSet);   System.out.println(arrList);  } } /*  * Java program to convert list to set. Convert ArrayList of string to HashSet  * in java example program How to convert List to Set in java Set<String> strSet  * = new HashSet<String>(arrList); HashSet having a constructor which will take  * list as an ar...