Core java interview questions and Answers for 5 - 7 Years Experience.

 Part 5

Core java interview questions and Answers for 5-7 Years Experience covered in this post:

    Core java interview questions and Answers for 5 - 7 Years Experience.

        What is the difference between Iterator and Enumarator?

     

    Iterator

    Enumerator

    1.

    Iterator is applicable to collection objects which not legacy classes.

    An enumerator is applicable to all legacy classes which are released Java 1.0.

    2.

    Iterator can perform read-only and remove operations.

    The enumerator can perform only read-only operations.

    3.

    Iterator has three methods for iteration.

                1.       hasNext();    

                2.       next();

                3.       remove();

    Enumeration has two methods.

                1.       HasMoreElement();

                2.       nextElement();


        What is the ListIterators and why do we require ListIterators in Collection framework?

    -          ListIterator is a child interface of the Iterator interface.

    -          ListIterator is an iterator can be applicable to list

    -          List iterator can move bidirectionally.

    -          There are 9 methods present inside ListIterator which are as follows.

    1.       hasNext();

    2.       next();

    3.       nextIndex();

    4.       hasPrevious();

    5.       previous();

    6.       previousIndex();

    7.       remove();

    8.       add();

    9.       set();

    package simplifiedjava.crackedInterview;

    import java.util.ArrayList;

    import java.util.ListIterator; 

    public class ListIteratorDemo {

          public static void main(String[] args) {       

                ArrayList<Integer> list = new ArrayList<Integer>();

                list.add(10);

                list.add(20);

                list.add(30);

                list.add(40);

                list.add(50);           

                ListIterator<Integer> itr = list.listIterator();           

                while(itr.hasNext()) {

                      int no = itr.next();

                      System.out.println(no);

                      boolean result = itr.hasNext();

                      System.out.println(result);              

                }          

          }

    } 

    Output:

    10

    true

    20

    true

    30

    true

    40

    true

    50

    false 


     

    Click here to Purchase on AmazonClick here to Purchase on Amazon

    Click here to Purchase on Amazon

    Note: Please click on Image to Purchase the books from Amazon.in

        What is the Enumarator and why do we require Enumarator in Collection framework?

    -          Enumeration can be used to iterate the legacy classes.

    -          Enumeration is also a legacy interface.

    -          Please refer to the below example.

    package simplifiedjava.crackedInterview; 

    import java.util.Enumeration;

    import java.util.Vector; 

    public class EnumerationDemo { 

          public static void main(String[] args) {

                Vector<Integer> v = new Vector<Integer>();

                v.addElement(10);

                v.addElement(20);

                v.addElement(30);

                v.addElement(40);           

                Enumeration<Integer> enu = v.elements();

                while(enu.hasMoreElements()) {

                      int element = enu.nextElement();

                      System.out.println(element);

                }

          }

    }

    Output:

    10

    20

    30

    40


        Can I perform remove operation while iterating CopyOnWriteArrayList object?

    -          We cannot perform the remove operation while iterating the CopyOnWriteArraylist object.

    -          It is possible for List implementations.


        What will happen if I am trying to perform remove operation while iterating CopyOnWriteArrayList?

    -          If we are trying to perform a remove operation while iterating CopyOnWriteArrayList, it will throw UnSupportedOperationException.

    -          Please refer to the bleow example.

    package simplifiedjava.crackedInterview;

     

    import java.util.Iterator;

    import java.util.concurrent.CopyOnWriteArrayList;

     

    public class CopyOnWriteArrayListDemo {

     

          public static void main(String[] args) {

                CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<Integer>();

                list.add(10);

                list.add(20);

                list.add(30);

                list.add(40);

                list.add(50);

               

                Iterator itr = list.iterator();

                while(itr.hasNext()) {

                      System.out.println(itr.next());

                      itr.remove();

                }          

          }

    }

    Output:

    10

    Exception in thread "main" java.lang.UnsupportedOperationException

           at java.util.concurrent.CopyOnWriteArrayList$COWIterator.remove(Unknown Source)

                   at simplifiedjava.crackedInterview.CopyOnWriteArrayListDemo.main(CopyOnWriteArrayListDemo.java:19)


        What the the new methods introduced in CopyOnWriteArrayList to performing read and write operation?

    -          CopyOnWriteArrayList is is concurrent version of list implementation.

    -   All methods of the list will be by default available in CopyOnWriteArrayList.

    -          There are a couple of methods that have been introduced by CopyOnWriteArrayList.

    1.       addIfAbsent():This method will add an element if and only if an element is not present in the list. Please refer to the below example.

    package simplifiedjava.crackedInterview; 

    import java.util.concurrent.CopyOnWriteArrayList; 

    public class CopyOnWriteArrayListDemo { 

          public static void main(String[] args) {

                CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<Integer>();

                list.add(10);

                list.add(20);

                list.add(30);

                list.addIfAbsent(20);// This element will be ignored because its already in list.

                list.addIfAbsent(40);// This element will be added because it was not in list.

                System.out.println(list);          

          }

    }

    Output:

    [10, 20, 30, 40]

     

    2.       addAllAbsent(): This method will add all elements if and only if elements are not present in the list. Please refer to the below example.

    package simplifiedjava.crackedInterview; 

    import java.util.concurrent.CopyOnWriteArrayList; 

    public class CopyOnWriteArrayListDemo { 

          public static void main(String[] args) {

                CopyOnWriteArrayList<Integer> list1 = new CopyOnWriteArrayList<Integer>();

                list1.add(10);

                list1.add(20);

                list1.add(30);

                System.out.println("List 1 = "+ list1);           

                CopyOnWriteArrayList<Integer> list2 = new CopyOnWriteArrayList<Integer>();

                list2.add(10);

                list2.add(20);

                list2.add(40);

                System.out.println("List 2 "+ list2);           

                list1.addAllAbsent(list2);

                System.out.println("Updated List = "+ list1);        

          }

    }

    Output:

    List 1 = [10, 20, 30]

    List 2 [10, 20, 40]

    Updated List = [10, 20, 30, 40]


        What is the difference between ArrayList and ArrayList<?> in Java?

    -          ArrayList – This version is non-generic version.

             -       ArrayList<?> - This version is generic version of ArrayList.


        Can I add other object than String in following snippet?

                      ArrayList<String> list = new ArrayList<String>();

    -          We have declared ArrayList with generic type safety.

    -          We already declared the list will be only for String. On other objects are allowed to insert it.

    -          You may refer to question no. 390 for more detail.


        WAP to break singleton using Deserialization? How to prevent Singleton to break with Deserialization?

    package simplifiedjava.crackedInterview; 

    import java.io.Serializable; 

    import javax.activity.InvalidActivityException; 

    public class Singleton implements Serializable{     

          private static Singleton INSTANCE = new Singleton();     

          private Singleton() {  

          }     

          public static Singleton getInstance() {

                if(INSTANCE != null) {

                      return INSTANCE;

                }

                return null;

          }     

          public void m1() {

                System.out.println("m1() method called.");

          }

    } 

    package simplifiedjava.crackedInterview; 

    import java.io.FileInputStream;

    import java.io.FileNotFoundException;

    import java.io.FileOutputStream;

    import java.io.IOException;

    import java.io.ObjectInputStream;

    import java.io.ObjectOutputStream; 

    public class SingletonBreakUsingDeserialization { 

          public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {

                Singleton obj1 = Singleton.getInstance();

                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file.ser"));

                oos.writeObject(obj1);

                oos.flush();

                oos.close();           

                ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file.ser"));

                Singleton obj2 = (Singleton)ois.readObject();

                ois.close();           

                System.out.println("HashCode for Original Object "+ obj1.hashCode());

                System.out.println("HashCode for Desrialized Object "+ obj2.hashCode());

          }

    }

    Output:

    HashCode for Original Object 1442407170

    HashCode for Desrialized Object 990368553

     

    -          To prevent this issue we have to override the readResolve()method in the Singleton class and return the same Singleton Instance.

    -          Please refer to the below example.

    package simplifiedjava.crackedInterview; 

    import java.io.Serializable; 

    import javax.activity.InvalidActivityException; 

    public class Singleton implements Serializable{     

          public static Singleton INSTANCE = new Singleton();     

          private Singleton() {        

          }     

          protected Object readResolve() {

            return INSTANCE;

      }     

          public void m1() {

                System.out.println("m1() method called.");

          }

    } 

    package simplifiedjava.crackedInterview; 

    import java.io.FileInputStream;

    import java.io.FileNotFoundException;

    import java.io.FileOutputStream;

    import java.io.IOException;

    import java.io.ObjectInputStream;

    import java.io.ObjectOutputStream; 

    public class SingletonBreakUsingDeserialization { 

          public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {

                Singleton obj1 = Singleton.INSTANCE;

                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file.ser"));

                oos.writeObject(obj1);

                oos.flush();

                oos.close();           

                ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file.ser"));

                Singleton obj2 = (Singleton)ois.readObject();

                ois.close();           

                System.out.println("HashCode for Original Object "+ obj1.hashCode());

                System.out.println("HashCode for Desrialized Object "+ obj2.hashCode());

          }

    }

    Output:

    HashCode for Original Object 1442407170

    HashCode for Desrialized Object 1442407170


        WAP to break Singleton using Cloning? How to prevent Singleton to break with Cloning?

    -          The class implements a Clonable interface then only the object of that class is a Clonable object.

    -          Clone means creating a copy of an original object.

    -          Please refer to the below example.

    package simplifiedjava.crackedInterview; 

    public class Singleton implements Cloneable{     

          public static Singleton INSTANCE = new Singleton();     

          private Singleton() {           

          }     

          public static Singleton getInstance() {

                if(INSTANCE == null) {

                      INSTANCE = new Singleton();

                }

                return INSTANCE;

          }     

          @Override

        protected Object clone() throws CloneNotSupportedException  {

            return super.clone();

        }     

          public void m1() {

                System.out.println("m1() method called.");

          }

    } 

    package simplifiedjava.crackedInterview; 

    public class SingletonBreakUsingCloning { 

          public static void main(String[] args) throws CloneNotSupportedException {

                Singleton obj1 = Singleton.getInstance();

                Singleton obj2 = (Singleton)obj1.clone();           

                System.out.println("HashCode of obj1"+ obj1.hashCode());

                System.out.println("HashCode of obj2"+ obj2.hashCode());

          }

    }

    Output:

    HashCode of obj1 : 2018699554

    HashCode of obj2 : 1311053135 

     

    -          We can prevent breaking the singleton in a Clonable pattern. Inside clone() method we can simply throw CloneNotSupportedException explicitly.

    -          Please refer to the below example.

    package simplifiedjava.crackedInterview; 

    public class Singleton implements Cloneable{     

          public static Singleton INSTANCE = new Singleton();     

          private Singleton() {           

          }     

          public static Singleton getInstance() {

                if(INSTANCE == null) {

                      INSTANCE = new Singleton();

                }

                return INSTANCE;

          }     

          @Override

        protected Object clone() throws CloneNotSupportedException  {

            throw new CloneNotSupportedException();

        }     

          public void m1() {

                System.out.println("m1() method called.");

          }

    } 

    package simplifiedjava.crackedInterview; 

    public class SingletonBreakUsingCloning { 

          public static void main(String[] args) throws CloneNotSupportedException {

                Singleton obj1 = Singleton.getInstance();

                Singleton obj2 = (Singleton)obj1.clone();           

                System.out.println("HashCode of obj1 : "+ obj1.hashCode());

                System.out.println("HashCode of obj2 : "+ obj2.hashCode());

          }

    }

    Output:

    Exception in thread "main" java.lang.CloneNotSupportedException

           at simplifiedjava.crackedInterview.Singleton.clone(Singleton.java:20)

           at simplifiedjava.crackedInterview.SingletonBreakUsingCloning.main(SingletonBreakUsingCloning.java:7)

     


        What is the difference between Web Application and Enterprise Application?

     

    Web Application

    Enterprise Application

    1.

    The web application can be deployed on the web as well as Enterprise applications.

    An enterprise application cannot deploy on a web application it can only deploy on an Enterprise application.

    2.

    Servet, JSP, HTML can be deployed on Web application.

    EJB, JMS can be deployedon Enterprise application.


        What are SOLID Priciple?

    Principle

    Description

    Single Responsibility Principle

    Each class should be responsible for a single part or functionality of the system.

    Open-Closed Principle

    Software components should be open for extension, but not for modification.

    Liskov Substitution Principle

    Objects of a superclass should be replaceable with objects of its subclasses without breaking the system.

    Interface Segregation Principle

    No client should be forced to depend on methods that it does not use.

    Dependency Inversion Principle

    High-level modules should not depend on low-level modules, both should depend on abstractions.




    • Java interview questions and answers all MNC - Click here
    • Basic core java interview questions and answers for freshers - Click here
    • Core java interview questions for 3 years experience - Click here
    • Core java interview questions and answers for 3-5 years exp - Click here
    • Core java interview questions and Answers for 5 - 7 Years exp - Click here
    • Basic Java Interview Questions and Answers - Click here
    • Java interview questions and answers on oops - Click here
    • Java interview questions and answers on Strings - Click here
    • Java interview questions on exception handling - Click here
    • Interview questions on multithreading in java for experienced - Click here
    • Interview questions on serialization in java for experienced - Click here

    • Interview questions on inner class in java for experienced - Click here
    • Interview questions on Collections in java for experienced - Click here


    Upcoming questions in next post:


    Previous Post                                                                    Next Post



    Thank you techies for visiting this blog. I hope you enjoyed this blog and got more technical knowledge. I have tried to cover all types of questions and provided examples tested on eclipse as much as I can. Guys, please don’t just mug up the questions and answers. Try to clear your concepts with examples. Try to write a code on eclipse once you read the concepts. It will help you to memorize the concepts for a very long time. Simultaneously you will be prepared for interview programs as well. It will help you to survive in the IT sector for a long time. It may be easy to crack an interview but it's really tough to survive in the IT industry with inadequate knowledge and skills. 

    I have collected all the questions from actual interviews attended by my friends, colleagues, college mate and classmate. I have covered frequently asked questions as well as challenging questions. I have included many programs to understand the concept thoroughly. I will try to explain the concept with the help of a real-time program in eclipse. 

    You can share more questions which are not covered in this blog or post. Always welcome your suggestions and queries. I will definitely try to resolve it. 

    Please comment your queries and new set of questions under the comment sections. I will create a new post for those questions. 

    My total experience is 10. Initially I had worked on some support projects and then I moved to java projects. I had worked with many multi-national companies like R-Systems, Tata Consultancy Services, Cybage Softwares.  Fortunately, TCS and Cybage has given me an opportunity to take interviews for experienced candidates. I have conducted more than 1000 interviews by now.

    Mock sessions will be conducted for minimal charges. I will guide you personally on how to crack interviews. All sessions will be online sessions only. My interview book will be provided free of cost if you enroll for personal training. Once you have done practice then I assured you will definitely crack almost all java interviews. 

    I have published my book named with "All MNC Java Interview" which is available on amazon. You can go through it or you can directly contact to me if you are interested to read the book. I will give you special discount. I have covered near about 550 questions and answers with program tested on eclipse and necessary diagram. 

    I have covered interview questions asked in all reputed MNC like TCS, Infosys, Capgemini, Tech Mahindra, Cognizant, City Bank, Barclays, Amdocs, Mindtree etc. My purpose behind this book is, help you to get a job in your dream company. I can understand this is a struggling period for job seekers and freshers. Everybody must have gone from this phase. so never give up. Keep upgrading yourself. I am sure you will get a job in your dream company. All the best!!! 

    Please reach out to me for personal training for interview preparation. 

    You can reach out to me at mncjavainterview@gmail.com.

     


    Post a Comment

    0 Comments