Friday, November 18, 2011

Basic Java Interview Questions


    Show answers
  1. What is the difference between Java and C++?
    JavaC++
    Memory managed (or garbage collected) languageProgrammer has to manage the heap memory.
    Compiled java code is platform independentC++ binary code is platform specific.
    Compiled and Interpreted languageCompiled language
    Pure object orientedFunctions can be disassociated from any class
    Supports multilevel inheritanceSupports multiple and multilevel inheritance
    Supports function overloadingSupports function and operator overloading
    Supports only signed numeric data typesSupports both signed and unsigned data types
    Supports unicode characters and char type takes 2 bytes in memoryDoesn't support unicode characters by default
  2. Is Java a compiled language or an interpreted language?
    Java is both compiled (to byte code) and interpreted language.
  3. What is byte code?
    Source java file is compiled into a intermediate code before interpreted by JVM. This intermediate code is called byte code.
    This is similar to MSIL in .Net
  4. What is JVM/JRE?
    JVM stands for Java Virtual Machine and JRE stands for Java Runtime Environment. Both (in most cases) used interchangeably. They represent the run time system for Java without which java code can not run.
  5. How does Java achieve platform independence?
    Java achieves platform independence by means of JVM. JVM differs from platform (Windows, Linux, Mac, Solaris, Unix) to platform. Since JVM converts the byte code to the underlying platform binary code, byte code remains platform independent and there by Java.
  6. Does Java support multiple/multilevel inheritance?
    Java does not support multiple inheritance but it supports multilevel inheritance.
  7. What is the difference between c++ and Java array?
    C++ array is created in stack where as Java array is created in heap.
    C++ array is a contiguous normal memory. Java array is an Object and it has run time boundary checking feature and a read only attribute called length to indicate the length of the array.
  8. Describe final/finally/finalize.
    final - similar to const in C/C++.
    finally - used to cleanup the resource after try/catch block is executed.
    finalize - similar to destructor in C++.
  9. Why should the main method be static?
    So that the JVM can call the main method without creating object for the class in which the main method is declared.
  10. Where are the equals() and hashcode() methods defined?
    They are defined in Object class and available to any java object as all java classes are children of Object class.
  11. Do you need to override equals() method when overriding hashcode() or vice versa?
    Yes. They are complementary to each other to represent the object equality. Hence it will give unpredictable behavior when one of them is not overridden.
  12. Is there anything wrong with the following code?
    void test() {
     try{
         BufferedReader in = new BufferedReader(new FileReader("sample.txt"));
         String line = null;
         while((line=in.readLine())!=null) {
             ...
         }
     } catch(IOException e) {
         ...
     } catch(FileNotFoundException e) {
         ...
     }
    }
    The catch chain should be such that the child most exception class is at the top and the parent exception class is at the bottom. Otherwise compiler will throw unreachable code exception.
  13. What are checked and unchecked exception?
    Any exception class that extends java.lang.RuntimeException or its children is called unchecked exception. These exceptions are checked at the compile time so you dont have to catch or declare to be thrown.
    eg. NullPointerException, ArrayIndexOutOfBoundException
    All other exceptions are called checked exceptions and you need to handle them in your code.
    eg. IOException, FileNotFoundException
  14. What do a method and a class mean when are qualified with final keyword?
    The final class can not be extended and the final method can not be overridden.
  15. What is nested class? what are their types?
    A class declared inside another class is called nested class. It has two types namely, static nested class and inner class.
  16. How to create an instance for an inner class outside of the enclosing class?
    You need to have the instance of the outer class to create the instance of the inner class.
    e.g OuterClass var = outerClassObject.new InnerClass();
  17. Is virtual supported in Java?
    Yes, all the non final methods are virtual by default. Hence you dont have to qualify them as virtual; in fact there is no virtual keyword in Java.
  18. Is operator over loading supported in Java?
    No. However the Java system itself has overloaded '+' operator for String concatenation.
  19. What is an abstract method?
    A method without a body is called abstract method. It is generally qualified with the keyword abstract.
  20. What is an abstract class?
    A class qualified with abstract keyword is called abstract class. It may or may not have abstract methods.
  21. Can an abstracted class be instantiated?
    No. However it can be extended and instance for the subclass can be created.
  22. What is a default constructor?
    When there is no user defined constructor, the java system provides a no-arg constructor and this constructor is called default constructor.
  23. Is there a destructor in Java?
    There is a finalize method used to cleanup any resource. Remember this method will be called when the object is garbage collected and NOT when the object goes out of scope.
  24. How do you define a singleton class?
    By making the constructor as private and providing a static accessor method to create and return the object of the singleton class. However the code should ensure that there is only one instance at any time.
  25. Can an interface have variables?
    Yes, they are public static final by default.
  26. Can a class be defined as abstract class without having any abstract method?
    Yes.
  27. Can a concrete class have any abstract method?
    No.
  28. Can an abstract class be private or final?
    No.
  29. Can a class be defined as private or protected?
    Yes, only the nested class can take private or protected access specifiers. The top level class, however, can take only the public access specifier.
  30. What are the different access specifiers available?
    public, protected, private and package (no keyword)
  31. Can a class access the protected members of another class without subclassing it?
    Yes if it is in the same package of the class which defines the protected member.
  32. What are all the mechanisms available for handling exception in Java?
    1. Handle using try-catch block 2. Declare it to be thrown
  33. Is JVM same for all the platforms?
    No. It is platform dependent.
  34. What are the different types of parameter passing in Java?
    Pass-by-value and Pass-by-reference. Primitive types are passed by value and all the objects are passed by reference.
  35. Does Java support pointers?
    No.
  36. What is WORA?
    Write Once; Run Anywhere.
  37. What is Garbage collection?
    GC is a task/feature built into JVM for collecting all (or required) free memory (which is occupied by objects with no reference)
  38. Can you run the garbage collection?
    No. But you can instruct JVM to run the GC using System.gc(). But there is no guarantee that it will run.
  39. What is static import?
    You can use static import to import the static members of a class. For example, if you are using Math.min(...) method very often in your code, you can simply say min(...) instead of that, by saying import static java.util.Math.min;
  40. If a class does not have any explicit package declaration, what package the class will belong to?
    It belongs to default package and is directly placed under src directory.
  41. What is serialization?
    A mechanism to send the object over internet or to store in a file/database. For an object to be serialized the class of that object must implement java.io.Serializable interface.
  42. What is thread?
    It is a construct to run any task concurrently. Java provide java.lang.Thread class to enable multi-tasking.
  43. What are the different ways available for creating threads?
    Extending java.lang.Thread class or implementing java.lang.Runnable interface
  44. By default how many threads will be available in a java program?
    Only one thread, the main thread. In the case GUI/Swing program it will be more, such as main, EDT, AWT, etc.
  45. What is jar file?
    A Java archive file (basically in zip format) containing all the source and resource file of a package/program/module.
  46. What is the difference between notify() and notifyAll()?
    notify() sends wakeup signal to one of the awaiting thread where as notifyAll() send this signal to all the threads awaiting on the same monitor object.
  47. What is volatile variable?
    'volatile' is a qualifier to mark any variable such that this variable is expected to be updated outside the thread that is reading it, i.e., more than one thread can/will modify the variable which is qualified with 'volatile'. e.g. one thread runs a loop with a conditional flag and this flag will be update by another thread
  48. Does Java support unsigned numeric types?
    No
  49. What are primitive wrapper classes?
    Each primitive types (byte, short, int, long, float, double, char) have their corresponding immutable objects and those object classes (Byte, Short, Integer, Long, Float, Double, Character) are called wrapper classes
  50. What is auto boxing and auto unboxing?
    Whenever a primitive value is assigned to its wrapper variable either directly or indirectly (through method call) then a corresponding wrapper object is created and assigned automatically with the primitive value given. This is called auto boxing. The reverse of this is called auto unboxing. Caution:when you try to unbox a null value, NullPointerException is thrown.
  51. What is enum? how it is different from C++ enum?
    Enums in Java are special classes for which you can't create objects at run time. They are similar to C++ enum and differ in the following ways.
    • Type safe: You can't assign any other value to a enum varialbe (except null)
    • Name space: it is not an int any more; it is fully qualified.e.g org.season.Season season, rather than int season as in C++;
    • Brittleness: If a method expects season value, it can't take any arbitrary values such as 25 or 26 unlike C++ enum
    • Informative printed values: when you print an enum, you get the enum name itself instead of numeric value (unlike C++)
  52. What is var-arg?
    Like printf method in C language, java methods (1.5 or above) can now take variable arguments.e.g.
    void argTest(String format, Integer... args){...}
    Here the method call looks like,
    • argTest("sample numbers");
    • argTest("sample numbers", 2);
    • argTest("sample numbers", 2, 3);
    • argTest("sample numbers", new Integer[]{2, 3});
    You can access the args variable as if it is an array.
  53. What is annotation? What is the usage of annotation?
    Annotations provide meta data about the Type they are annotating. They are used by compilers(@override), IDEs, and containers such as EJB, servlet (@EJB, @Stateless, @WebServlet etc)
  54. What do you mean by a deprecated class/method?
    Deprecated class/method is no longer supported and may be removed in the future release
  55. What is the difference between an instance member and class member?
    You need object of the class to access the instance member. But class members can be accessed by using the class itself.
  56. Can a class be member of another class?
    Yes. They are called nested classes. They are of two types viz static nested class and inner class
  57. What is anonymous class?
    An inner class with out a name.
  58. Can a class extend any one class and implement an interface at the same time?
    Yes
  59. Can an anonymous class extend any one class and implement an interface at the same time?
    No. It can either implement an interface or extend a class.
  60. How do you pass any parameter to an anonymous class constructor?
    No, you can't.
  61. How do you carry out post creation operation in anonymous class?
    Use object initializers.
  62. What is a static block?
    A block which will be executed at the time of class loading to initialize the class members. This is executed only once in the lifetime of a class.
  63. Can a final variable be initialized anywhere other than at the declaration statement?
    Yes. If it is not initialized along with the declaration, then it can be initialized once in the constructor.
  64. Can a static variable be final?
    Yes.
  65. Are primitive wrapper class objects mutable?
    Yes, they can't be modified.
  66. Is String a mutable class?
    No. It is immutable.
  67. What does Clonable interface do?
    It is a marker interface to let the object of a class to be colend.
  68. What are the rules for a class to be serializable?
    • Must have a public no-arg constructor.
    • All the members of the class must be serializable or they have to be marked as transient.