IMPORTANT QUESTIONS FOR JAVA INTERVIEW

1)How many ways  are there to create an object?
      i) Using ‘new’ operator:
                Test s=new Test();  
     ii) Factory method:
             Thread t=Thread.currentThread();
    iii)  newInstance():
               Class c=Class.forName(“Test”);
             Object obj=c.newInstance();           àcreates Test class Object.
                      Test t=(Test)obj;
   iv)  clone():  
           Test t1=new Test(10,20); 
             Test t2=t1.clone();
    v)   Deserialization:
             FileInputStream fis=new FileInputStream(“Test.txt”);
        ObjectInputStream ois=new ObjectInputStream(fis);
        
     UserDefSerCls   uds=new UserDefSerCls(,” ”,);
            Ois.readObject(uds);
             Ois.close();
    
2) What are the differences b/w HashMap and HashSet?
     
                   HashMap 
                                HashSet
 It stores the data in key,value format.

 It allows duplicate elements as values.

It implements Map

 It allows only one NULL key.

  It stores grouped data .

  It does not allow any duplicates.

 It implements Set.

It  does not allow NULL .

     


3) What is the difference b/w wait(-), sleep(-)& wait(-),yield()?

              Wait(-)
                          Sleep(-)
  Running  to Waiting/ Sleeping/Block.

 It makes the current thread to sleep up to the given seconds and it could sleep less than the given seconds if it receives notify()/notifyAll() call.

In this case, the locks will be released before going into waiting state so that  the other threads that are waiting on that object will use it.

Causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
               
Do

It makes the current thread to sleep for exactly the given seconds.



In case of sleep(), once the thread is entered
into synchronized block/method, no other
  thread will be able to enter into that
   method/block.

 
     Yield()à when a task invokes yield(), it changes from Running state to Runnable state.


*4)  Can we create a userdefined immutable class?
        Yes. 
i)                    Make the class as final and
ii)                  make the data members as private and final.

*5)  What are the differences b/w String and StringBuffer?
                 
                   String
         StringBuffer
It is immutable.

It won’t give any additional space.


 It is mutable.

gives 16 additional characters memory space.

6)  Which “Collections F/W”  classes did you use in your project?
         List, ArrayList, LinkedList—add()
        Set, TreeSet, HashSet--
        HashMap—put(), get(), entrySet(), keyset()
        Map.Entry
        Iterator----hasMoreElements(), next()
        ListIterator.

7)  Can you write the simple code for HashMap?
          
                 HashMap<String,String> hm=new HashMap<String,String>();
     
 hm.put(“key1”,”value1”);
 hm.put(“key2”,”value2”);
 hm.put(“key3”,”value3”);   

                                    Set set=hm.keySet();          //   gives keys Set i.e., {key1,key2,key3}

                                  Iterator<string>  itr=set.iterator();      

                        while(itr.hasNext()){                //true….false
                             String empkeys=itr.next();  //for keys
                             String  empvalnames=hm.get(empkeys);  //gives values by taking keys.

                    System.out.println(“empname”+empvalnames+”empid”+empkeys);
         }

8) What are thread states?

   i) Start: Thread thread=new Thread();

  ii) Runnable: looking for its turn to be picked for execution by the Thread Schedular based
                        on thead priorities. (setPriority())
iii) Running:  The Processor is actively executing the thread code.  It runs until it becomes
                       blocked, or voluntarily gives up its turn with Thread.yield(). 
                       Because of Context Switching overhead, yield() should not be used very    
                       frequently.

iv) Waiting:   A thread is in a blocked state while it waits for some external processing such
                       as file I/O to finish.
    Sleepingàsleep(): Java threads are forcibly put to sleep (suspended) with this overloaded method.
                                    Thread.sleep(milliseconds); Thread.sleep(milliseconds,nanoseconds);
   Blocking on I/O: Will move to runnable after I/O condition like reading bytes of data etc changes.
   Blocked on Synchronization: will move to Runnable when a Lock is acquired.

v) Dead: The thread is finished working.
    How to avoid Deadlock:
       1) Avoid a thread holding multiple locks----
                If no thread attempts to hold more than one lock ,then no   deadlock occurs.
  
       2) Reordering  lock acquisition:--
            If we require threads to alway  acquire locks in a particular order, then no deadlock occurs.

9)    What are differences b/w concrete,abstract classes and interface & they are given?
       
      Concrete class:   A class of  only Concrete methods is called Concrete Class.
                                  For this, object instantiation is possible directly.
                                  A class can extends one class and implements many interfaces.
               Abstract class:
                      Interface:
*A class of only Concrete or only Abstract or both.

*Any java class can extend only one abstract class.

*It won’t force the programmer to implement/override all its methods.

*It takes less execution time than interface.

*   It allows constructor.

This class can’t be instantiated directly.
                      
 A class must be abstract when it consist at least one abstract method.
                     
It gives less scope than an Interface.

It allows both variable & constants declaration.


It allows methods definitions or declarations whenever we want.

It gives reusability hence it can’t be declared as “final”.

 only abstract methods.
                

A class can implements any no. of  interfaces
(this gives multiple interface inheritance )

It forces the programmer to implement all its methods

Interface takes more execution time due to its complex hierarchy.
*   It won’t allow any constructor.

It can’t be instantiated but it can refer to its subclass objects.



It gives more scope than an abstract class.
                
By default, methodsàpublic  abstract
                  variablesàpublic static final.

               
It allows  methods declarations whenever we want . But it involves complexity.
              
Since they give reusability hence they must not be declared as “final”.




10)    Can you create a userdefined immutable class like String?
        Yes, by making the class as final and its data members as private, final.

11)    Name some struts supplied tags?
        a) struts_html.tld                    b)  struts_bean.tld
        c) struts_logic.tld                    d)  struts_nested.tld
       d) struts_template.tld              e)  struts_tiles.tld.

12)    How to retieve the objects from an ArrayList?
          
    List list=new ArrayList();                                     //  List<String> list=new ArrayList<String>();

 list.add(“element1”);                                              list.add(“element1”);
list.add(“element2”);                                                list.add(“element2”);
 list.add(“element3”);                                                list.add(“element3”);
                                                                                  //  Iterator<String> iterator=list.iterator();    
                                                                                         for(String str:list)
                                                                              s.o.p(str);   }
  Iterator    iterator=list.iterator();                                      
           while(iterator.hasNext()){                                                                                  
String str=(String)itr.next();
        S.o.p(string); 
}
       }

13)   Can I take a class as “private”?
        Yes, but it is declare to inner class, not to outer class. If we are declaring "private" to outer class nothing can be accessed from that outer class to inner class.
16)    How can you clone an object?
           A a1=new ();
           B  a11=a1.clone();

17)    What methods are there in Cloneable interface?
          Since Cloneable is a Marker/Tag interface, no methods present.When a class implements this interface that class obtains some special behavior and that  will be realized by the JVM.


20)  Which JSP methods can be overridden?
          jspInit() & jspDestroy().

21)   Explain the JSP life-cycle methods?
1. Page translation: The page is parsed & a Java file containing the corresponding servlet is   
                                    created.
2. Page compilation:   The Java file is compiled.
3.   Load class:         The compiled class is loaded.
4 .Create instance:     An instance of the servlet is created.
5. Call jspInit():       This method is called before any other
                              method to allow initialization.
6. Call _jspService(): This method is called for each request. (can’t be overridden)
7. Call jspDestroy(): The container calls this when it decides take the instance out of service.
                          It is the last method called n the servlet instance.                                                        
 22)   What  Design Patterns are you using in your project?
       i) MVCàseparates  roles using different technologies,
      ii)  Singleton Java classàTo satisfy the Servlet Specification, a servlet must be a Single   
                                                 Instance  multiple thread component.
      iii) Front Controllerà A Servlet developed as FrontController can traps only the requests.
      iv) D.T.O/ V.OàData Transfer Object/Value object is there to send huge amount of data
                                        from one lalyer to another layer.
    It avoids Network Round trips.
      v) IOC/Dependency Injectionà F/w s/w or container can automatically instantiates the   
                                               objects  implicitly and  injects  the dependent data to that object.
      vi) Factory methodà It won’t allows object instantiation from out-side of the calss.
      vii) View Helperà It is there to develop a JSP without Java code so that readability,
                                      re-usability will become easy.

23)   What is Singleton Java class & its importance?
      A Java class that allows to create only one object per JVM is called Singleton Java class.
      Ex:  In Struts f/w, the ActionServlet is a Singleton Java class.
      Use: Instead of creating multiple objects for a Java class having same data, it is recommended  to  create       only one object & use it for multiple no. of times.

24)   What are the differences b/w perform() & execute()?
            perform() is an deprecated method.

25)   What are the drawbacks of Struts? Is it MVC-I or II?     Struts is MVC-II
       1) Struts 1.x components are API dependent.  Because Action & FormBean classes must
          extend from the Struts 1.x APIs pre-defined classes.
       2) Since applications are API dependent hence their “Unit testing” becomes complex.
       3) Struts allows only JSP technology in developing View-layer components.
       4) Struts application Debugging is quite complex.
       5) Struts gives no built-in AJAX support. (for asynchronous communication)

Note:    In Struts 1.x, the form that comes on the Browser-Window can be displayed
            under no control of F/W s/w  & Action class.

26)   What are the differences b/w struts, spring and hibernate?
       Struts:  allows to develop only webapplications and  it can’t support POJO/POJI model                          programming.
       Spring: is useful in developing all types of Java applications and support POJO/POJI model                   programming.
      Hibernate: is used to  develop DB independent persistence logic It also supports POJO/POJI            model  programming.

27)   What are differences b/w Servlets & Jsp?
           Servlets:
  i)  It  requires Recompilation and  Reloading when we do modifications in a Servlet.(some servers)
 ii)  Every Servlet must be configured in “web.xml”.
iii)  It is providing less amount of implicit objects support.
iv)  Since it consists both HTML & B.logic hence modification in one logic may disturbs
       the other logic.
v)  No implicit Exception Handling support.
vi)  Since it requires strong Java knowledge hence non-java programmers shows no interest.
vii) Keeping HTML code in Servlets is quite complex.

                                             JSP:
   i)   No need of Recompilation & Reloading when we do modifications in a JSP page.
  ii)   We need not to Configure a JSP in a “web.xml”.
  iii)   It is providing huge amount of Implicit Objects support.
  iv)   Since Html & Java code are separated hence no disturbance while changing logic.
  v)   It is providing implicit XML Exception Handling support.
 vi)   It is easy to learn & implement since it is tags based.
 vii)   It allows to develop custom tags.
viii)  It gives JSTL support.JSP Standard Tag LibraryàIt provides more tags that will help to develop a        JSP without using Java code .
ix)   It gives all benefits of Servlets.

28)   What is the difference b/w ActionServlet & Servlet?
        ActionServlet: It is a predefined Singleton Java class and it traps all the requests
        coming to Server.   It acts as a Front-Controller in Struts 1.x.
        
    Servlet:  a Java class that extends HttpServlet/GenericServlet or implements Servlet 
        interface and is a Server side technology to develop dynamic web pages.
       It is a Single instance multiple thread component. It need not be a Singleton Java class.

29)   What are Access Specifiers & modifiers?
     i) public-    à    Universal access specifier.
                       --can be used along with: class, innerclass, Interface, variable, constructor, method.                      
    ii) protectd à  Inherited access specifier.
                            --can be used along with: innerclass, variable, method, constructor.
    iii) default    à  Package access specifier(with in the package).
                    --can be used along with: class, innerclass, interface, variable, constructor, method.
   iv) private    à  Native access specifier.
                             -- can be used along with: innerclass, variable, constructor, method.

à Some other access modifiers:
      i) static------------innerclass,variable,block,method.
      ii) abstract—----- class,method.
      iii) final--------------class,variable,method.
      iv) synchronized---block,method.
      v) transient---------variable.
     vi) native-------------method.
     vii) volatile-----------variable
     viii) strict fp-----------variable
          
30) Which JSP tag is  used to display error validation?
                    In Source page:    
    <%@page  errorPage=”error-page-name.jsp”>
                  
                    In  Error page:

     <%@page  isErrorPage=”true”>

Search This Blog

All the rights are reserved to this blog is belongs to me only.. Powered by Blogger.