Wednesday 31 July 2013

Java interview questions and answers 2



57. What is meant by a wrapper class ?
Ans: A primitive wrapper class is one of eight classes define in the package
java.lang. in java language to provide object methods for the eight primitive types, also all of the wrapper classes are immutable. Wrapper classes are used to represent primitive values than an Object is required and does not contain constructors.
  The Wrapper class maintains the following information:
  • The wrapper name.
  • A WrapperInfo object that contains all of the information that pertains to this wrapper. This information gets stored in subclasses of the Wrapper class.
  • The wrapper core library name and  returned name of the native library that loaded the wrapper.
      The primitive wrapper classes and their corresponding primitive types are:
 
 Primitive data type
  Primitive Wrapper class
  boolean
   Boolean
   byte 
   Byte
  short
   Short
   int
    Integer
   long
   Long
   float
   Float
   double
  Double
   char
  Boolean
   *In the wrapper class all Byte, Short, Integer, Long, Float, and Double  are in subclasses of the Number class.
58. What is meant by static variable and static method ?
Ans: A static variable and static method is declare as static by using static keyword in front them. A static variable is shared by all the instances of that class i.e only one copy of the static variable is maintained in memory and each static member call by main method.

A static method cannot access non-static/instance variables, because a static method is never associated with any instance of a class.
59. What is meant by Garbage collection ?
Ans: In Java, garbage collection( included part of JVM) is a form of automatic
memory management. it attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program, or collect those object which lose there reference and identity and no longer in used.
  JVM perform automatic garbage collection.
The basic principles of garbage collection are:
  1. Find data objects in a program that cannot be accessed in the future.
  2. Reclaim the resources used by those objects.
60. What is meant by abstract class?
Ans:  A class declared
abstract by adding a keyword in front of class, and abstract class have following property like it is incompletely implemented, such a class cannot be instantiated, but can be extended by subclasses.
61. What is meant by final class and methods ?
Ans: A final class which can't be extended, means that a final class can not become a superclass nor have a subclass.
An example final class is written below:
  final class Demo {
        // This class cannot be extended
       }

A
Method provides information about, and access to, a single method on a class or interface.//
 Every Java program must have one
main() method.
     //following simple code
    class 
     {
            public static void main(String[] args)
            {
      System.out.println("Hello World!");
            }
     }


 
62. What is meant by interface ?
Ans: Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body.
63. What is meant by a resource leak ? In java this situation arises when references to objects that are no longer required. To avoid this you should remember to set all variables to null as soon as you are finished with the reference. This will allow the gc to free up the memory that the objects were consuming.
64. What is the difference between interface and abstract class ?
Ans: In an abstract class the method/behavior define in that class is partially or concrete implemented in its subclass while is case of interface, the method/behavior can't be implemented in subclass interface.

68. What is singleton class ? A singleton is an class that can be instantiated once, and only once. This is a fairly unique property, but useful in a wide range of object designs. Creating an implementation of the singleton pattern is fairly straightforward - simple block off access to all constructors, provide a static method for getting an instance of the singleton, and prevent cloning.

69. What is the difference between an array and a vector ?
Ans: Following difference.
  • Vector are synchronized means method that belongs to its contents is thread safe while Array is unsynchronized means method is not thread safe.
  •  Vector is a growable array of objects and dynamic while Vector is a set of related data type and static.
70. What is meant by constructor ?
Ans:  For initialization of instance variables a constructor must be used and constructor must have same name as class name.
71. What is meant by casting ?
Ans: If the two types are compatible, then Java will perform the conversion automatically, However 
Typecast Objects with a dynamically loaded Class because object references depends on the relationship of the classes involved in the same hierarchy.
72. What is the difference between final, finally and finalize ?
Ans:
   final- keyword
   finally - block
 finalize()- method
used to declare constants means further no modifications
The finally block always executes when the try block exits and usually used to release all the resources utilized inside the try block.
finalize method is called by the garbage collector on an object when the garbage collector determines that there are no more references to the object and free some resource from that object.
74. What are the main packages in java ?
Ans:  Main Package in java is-
  • java.applet.*
  • java.lang.*
  • java.awt.*
  • java.io.*
  • java.math.*
  • java.security.*
  • java.rmi.*
  • java.beans.*
  • java.net.*
  • java.nio.*
  • java.sql.*
  • java.swing.*
  • java.applet.*
77. What is the difference between java.applet.* and java.applet.Applet ?
Ans: In java,  java.applet.* is used as a package to import all the classes while java.applet.Applet is utilize a java class.
78. What is a default package ?
Ans: Java classes can be grouped together in packages, and name of package is the same as the directory (folder) name which contains the .java files. So default package is that package which is included automatically when the class is created and contain all the information of the class.
  E.g. of default package is  java.lang or can create default package self for small program.
79. What is meant by a super class and //how can you call a super class ?
Ans:  A Java class may be either a superclass, a subclass, both, or neither. but  a Java superclass is a class which  provide complete access of  method or variable to its subclass.

80. What is anonymous class ?
Ans: An
anonymous class is a local class without a name and it does not use the keywords class, implements or extends. An anonymous class is defined and instantiated in a single succinct expression using the new operator.
81. Name interfaces without a method ?
Ans: Interface without any method is called Marker or Null Interface like
  • Serializable interface
  • Externalizable interface
  • Cloneable interface
     
82. What is the use of an interface ?
Ans:To achieve multiple inheritance.
83. What is a serializable interface ?
Ans:The Serializable interface defines no members but used to indicate that a class may be serialized. If a class is define to be serializable, then its all  subclasses are also serializable.
84. How to prevent field from serialization ?
Ans:  To prevent a field from being serialized, mark the field with transient keyword.
85. What is meant by exception ?
Ans: An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error must be checked and handled manually. Exceptions can be generated by the Java run-time system (or java virtual machine, JVM ), or they can be manually generated by your code.
   Exception is of two type-
      1. Check Exception or Compiletime Exception. An exception which generate by
programming error like user written  program or code and must be handle at   time of compilation of program.
      2. Uncheck Exception or Runtime Exception. An exception which can generate at the runtime of program, the compiler doesn’t force the programmers to catch the exception.
 

86. How can you avoid the runtime exception ?
Ans: By using keyword throws( if more than exception is throw ) or throw( if only one exception is throw).
87. What is the difference between throw and throws ?
Ans--Exception is throwing by the utilize the keyword throw (for single exception) and throws (for multiple exception ),both the keyword help in catching exceptions that are thrown by the Java run-time system.
88. What is the use of finally ?
Ans: The
finally block is always executed before control leaves the try statement. so the code return inside the finally block always executed.
89. Can multiple catch statements be used in exceptions ?
Ans: Yes, it is possible.

        //here the syntax of multiple catch
        try
 
{
          // Exception Generated code return here
       
}

     //First Catch used
        catch
(Exception e)
 
{
          System
.out.println(" First exception caught.", e);
        
}

      // Second Catch used
      catch
(Exception e) {
          System
.out.println(" Second exception caught.", e);
     
}
90. Is it possible to write a try within a try statement ?
Ans: Yes, it is possible .

   //here the syntax of multiple try
      try {
          try {
              // Exception generated code return here.
          } catch (Exception e) {
              System.out.println("Exception: " + e);
          }
      } catch (Exception e) {
          System.out.println("Exception: " + e);

      }

91. What is the method to find if the object exited or not ?
Ans:  Use equals() method.
92. What is meant by a Thread ?
Ans: A thread is a program which defines a separate path of execution, the thread is the smallest unit of dispatchable code. This means that a single program can perform two or more tasks simultaneously.
93. What is meant by multi-threading ?
Ans: Multithreading is a specialized form of multitasking. A multithreaded program contains two or more parts that can run concurrently each part of such a program is called a thread, and each thread defines a separate path of execution.
 
95. What is the method to find if a thread is active or not ?

Ans: For finding the thread is active or not the method isAlive() from package java.lang.Thread.

 
96. What are the thread-to-thread communication ?

Ans: Thread to thread communication means one thread able to sleep,
wait, resume even dead to another thread on respected method call.

97. What is the difference between sleep and suspend ?

Ans:

98. Can thread become a member of another thread ?

Ans: Since every thread has there own name and priority  for
identification purposes. So one thread able to start another thread but not
become the member of another thread




99. What is meant by deadlock ?

Ans:  Dead lock  is a typically error condition that occur relates specifically to
multitasking is deadlock, which occurs when two threads have a circular
dependency on each other
and a pair of
synchronized objects.

    Deadlock generally occur for two reasons:


 
·         In general, it occurs when the two threads time-slice in just the right
·            way.

 
·          It may involve more than two threads and two synchronized objects
·          // An example of deadlock.
 

class
A {
·          
·             synchronized void call(B y) {
       
·                 String name =
·            Thread.currentThread().getName();
       
·                 System.out.println(name +
·            " initilization A");
       
·                 try {
           
·                     Thread.sleep(500);
       
·                 } catch
·            (Exception
·            e) {
           
·                     System.out.println(" Interrupted"
·            + e);
       
·                 }
       
·                 System.out.println(name +
·            " trying to initilization B.last()");
       
·                 y.last();
   
·             }

   
·          
·             synchronized void last() {
·             }
}

·           
class
·            B {
  
·             synchronized void bar(A x) {
       
·                 String name =
·            Thread.currentThread().getName();
       
·                 System.out.println(name +
·            " initilization B ");
       
·                 try {
           
·                     Thread.sleep(1000);
       
·                 } catch
·            (Exception
·            e) {
           
·                     System.out.println(" Interrupted"
·            + e);
       
·                 }
       
·                 System.out.println(name +
·            " trying to initilization A.last()");
       
·                 x.last();
   
·             }

   
·          
·             synchronized void last() {
   
·             }
}

·        

·            class Deadlock
·            implements Runnable
·            {

   
·          
·             A x = new A();
   
·             B y = new B();

   
·          
·             Deadlock() {
       
·                 Thread.currentThread().setName("MainThread");
       
·                 Thread t =
·            new Thread(this,
·            "ChildThread");
       
·                 t.start();
       
·                 x.call(y);                                            
·            // get lock on a in this thread.
   
·             }

   
·          
·             public void run() {
       
·                 y.bar(x);                                            
·            // get lock on b in other thread.
   
·             }

   
·          
·             public static void main(String
·            args[]) {
       
·                 new Deadlock();
   
·             }
}
·          Result:
·              MainThread initilization A
·              ChildThread initilization B
·              MainThread trying to initilization B.last()
·              ChildThread trying to initilization A.last()
·          

100. How can you avoid a deadlock ?

Ans: Avoid a Deadlock/ Prevention of Deadlock


 
·         When a lock is held than never call any method that need other lock ,i.e.-
·            never call synchronized method of another class from a synchronized method.

 
·         When a synchronized method are going to call doesn't able to call
·            another synchronized method, so at that condition kill that method.

 
·          Whenever a program contain  two or more than two thread those
·            consume more resource than try to Implementation of " hold and wait" 
·            or " suspend and resume" method.

·          


 Example to avid Deadlock condition.

  // followig example is for avod deadlock condition



   class Item {

    int item;

    boolean flag = false;

    public synchronized int getItem() {

        if (!flag) {

            try {

                wait();

            } catch (Exception e) {

            }

        }

        System.out.println("getItem() method:" + item);

        flag = false;

        notify();

        return item;

    }



    public synchronized void setItem(int item) {

        if (flag) {

            try {

                wait();

            } catch (Exception e) {

            }

        }



        this.item = item;

        System.out.println("setItem() method:" + item);

        flag = true;

        notify();

    }

}


class SynchronizedConsumer extends Thread {



    Item it;

    SynchronizedConsumer(Item it) {

        this.it = it;

    }

    public void run() {

        for (int i = 1; i <= 5; i++) {

            int item = it.getItem();

        }

    }

}




class SynchronizedProducer extends Thread {

    Item it;
    public SynchronizedProducer(Item it) {

        this.it = it;

    }



    public void run() {

        for (int i = 1; i <= 5; i++) {

            it.setItem(i);

        }

    }

}

 
class SynchronizedMain {

    public static void main(String args[]) {

        Item it = new Item();

        SynchronizedConsumer cons = new SynchronizedConsumer(it);

        SynchronizedProducer pros = new SynchronizedProducer(it);

        cons.start();

        pros.start();

    }

}


   Result:
     setItem() method:1
     getItem() method:1
     setItem() method:2
     getItem() method:2
     setItem() method:3
     getItem() method:3
     setItem() method:4
     getItem() method:4
     setItem() method:5
     getItem() method:5

No comments:

Post a Comment