Thursday, July 14, 2011

Java Interrview Questions - Java Basic

  1. What is the dIfference between Interface and Abstract Class
  2. Abstract class defined with methods. Interface will declare only the methods. Abstract classes are very much useful when there is a some functionality across various classes. Interfaces are well suited for the classes which varies in functionality but with the same method signatures.
    Also interface can be used for multiple inheritence
  3. What is the difference between List and Set
  4. A List can have duplicate items but a Set can not.List is an ordered collection while a Set is not
    Set(as defined in java docs) : A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
    List(as defined in java docs) : An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
  5. What is the difference between ArrayList and LinkedList
  6. ArrayList can be accessed Randomly while LinkedList can not.If item need to be insrted any where in the list then LinkedList are better.
    More on Difference between ArrayList and LinkedList
  7. Can there be an abstract class with no abstract methods in it?
  8. Yes
  9. Can an Interface be final?
  10. No
  11. Can an Interface have an inner class?
  12. Yes
    public interface abc
     static int i=0; void dd();
     class a1
      int j;
      System.out.println("Inside CLass");
      public static void main(String a1[])
       System.out.println("I am from Inside class of an interface");
  13. Can we define private and protected modifiers for variables in interfaces?
  14. No
  15. What is Externalizable?
  16. Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)
  17. What modifiers are allowed for methods in an Interface
  18. Only public and abstract modifiers are allowed for methods in interfaces.
  19. What is a local, member and a class variable?
  20. Variables declared within a method are “local” variables. Variables declared within the class i.e not within any methods are “member” variables (global variables).
    Variables declared within the class i.e not within any methods and are defined as “static” are class variables
  21. What are the different identifier states of a Thread?
  22. The different identifiers of a Thread are:R - Running or runnable thread
    S - Suspended thread
    CW - Thread waiting on a condition variable
    MW - Thread waiting on a monitor lock
    MS - Thread suspended waiting on a monitor lock
  23. What are some alternatives to inheritance?
  24. Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).
  25. Why isn’t there operator overloading?
  26. Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn’t even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().
  27. What does it mean that a method or field is “static”?
  28. Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class.
    Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That’s how library methods like System.out.println() work. out is a static field in the java.lang.System class.
  29. Difference between JRE/JVM/JDK?
  30. Why do threads block on I/O?
  31. Threads block on i/o (that is enters the waiting state) so that other threads may execute while the I/O operation is performed.
  32. What is synchronization and why is it important?
  33. With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors.
  34. Is null a keyword?
  35. The null value is not a keyword.
  36. Which characters may be used as the second character of an identifier,but not as the first character of an identifier?
  37. The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.
  38. What modifiers may be used with an inner class that is a member of an outer class?
  39. A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.
  40. What are wrapped classes?
  41. Wrapped classes are classes that allow primitive types to be accessed as objects.
  42. What restrictions are placed on the location of a package statement within a source code file?
  43. A package statement must appear as the first line in a source code file (excluding blank lines and comments).
  44. What is the difference between preemptive scheduling and time slicing?
  45. Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
  46. What is a native method?
  47. A native method is a method that is implemented in a language other than Java.
  48. What are order of precedence and associativity, and how are they used?
  49. Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left
  50. What is the catch or declare rule for method declarations?
  51. If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.
  52. Can an anonymous class be declared as implementing an interface and extending a class?
  53. An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.
  54. What is garbage collection? What is the process that is responsible for doing that in java?
  55. Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process
  56. What kind of thread is the Garbage collector thread?
  57. It is a daemon thread.
  58. What is a daemon thread?
  59. These are the threads which can run without user intervention. The JVM can exit when there are daemon thread by killing them abruptly.
  60. How will you invoke any external process in Java?
  61. Runtime.getRuntime().exec(….)
  62. What is the finalize method do?
  63. Before the invalid objects get garbage collected, the JVM give the user a chance to clean up some resources before it got garbage collected.
  64. What is mutable object and immutable object?
  65. If a object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an object, it is immutable object. (Ex., String, Integer, Float, …)
  66. What is the basic difference between string and stringbuffer object?
  67. String is an immutable object. StringBuffer is a mutable object.
  68. What is the basic difference between StringBuilder and stringbuffer object?
  69. Both are mutable object but StringBuffer is ThreadSafe while StringBuilder is not. Unless you need Thready safety, use StringBuilder.e.g Local variable should be StringBulder
  70. What is the purpose of Void class
  71. The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void.
  72. What is reflection?
  73. Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions.
  74. What is the base class for Error and Exception?
  75. Throwable
  76. What is a package?
  77. To group set of classes into a single unit is known as packaging. Packages provides wide namespace ability.
  78. What are the approaches that you will follow for making a program very efficient?
  79. By avoiding too much of static methods avoiding the excessive and unnecessary use of synchronized methods Selection of related classes based on the application (meaning synchronized classes for multiuser and non-synchronized classes for single user) Usage of appropriate design patterns Using cache methodologies for remote invocations Avoiding creation of variables within a loop and lot more.
  80. What is Locale?
  81. A Locale object represents a specific geographical, political, or cultural region
  82. Is JVM a compiler or an interpreter?
  83. Interpreter
  84. When you think about optimization, what is the best way to findout the time/memory consuming process?
  85. Using profiler
  86. What is the purpose of assert keyword used in JDK1.4.x?
  87. In order to validate certain expressions. It effectively replaces the if block and automatically throws the AssertionError on failure. This keyword should be used for the critical arguments. Meaning, without that the method does nothing.
  88. How will you get the platform dependent values like line separator, path separator, etc., ?
  89. Using Sytem.getProperty(…) (line.separator, path.separator, …)
  90. What is the final keyword denotes?
  91. final keyword denotes that it is the final implementation for that method or variable or class. You can’t override that method/variable/class any more.
  92. What is the major difference between LinkedList and ArrayList?
  93. LinkedList are meant for sequential accessing. ArrayList are meant for random accessing.
  94. What is nested class?.
  95. If all the methods of a inner class is static then it is a nested class.
  96. What is inner class?
  97. If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class.
  98. What is composition?
  99. Holding the reference of the other class within some other class is known as composition.
  100. What is aggregation?
  101. It is a special type of composition. If you expose all the methods of a composite class and route the method call to the composite method through its reference, then it is called aggregation.
  102. What is singleton?
  103. It is one of the design pattern. This falls in the creational pattern of the design pattern. There will be only one instance for that entire JVM. You can achieve this by having the private constructor in the class. For eg.,
     public class Singleton { 
           private static final Singleton s = new Singleton(); 
           private Singleton() { } 
           public static Singleton getInstance() { 
                return s; 
           // all non static methods … 
  104. What is a Marker Interface?
  105. An interface with no methods. Example: Serializable, Remote, Cloneable
  106. What interface do you implement to do the sorting?
  107. Comparable
  108. What is the eligibility for a object to get cloned?
  109. It must implement the Cloneable interface
  110. What is the purpose of abstract class?
  111. It is not an instantiable class. It provides the concrete implementation for some/all the methods. So that they can reuse the concrete functionality by inheriting the abstract class.
  112. What is a hashCode?
  113. hash code value for this object which is unique for every object(it should be same if Objects are equal
  114. What is a thread?
  115. Thread is a block of code which can execute concurrently with other threads in the JVM.
  116. What is the algorithm used in Thread scheduling?
  117. Fixed priority scheduling.
  118. What is hash-collision in Hashtable and how it is handled in Java?
  119. Two different keys with the same hash value. Two different entries will be kept in a single hash bucket to avoid the collision.
  120. What is the use of serializable?
  121. To persist the state of an object into any perminant storage device.
  122. What is the use of transient?
  123. It is an indicator to the JVM that those variables should not be persisted. It is the users responsibility to initialize the value when read back from the storage.
  124. What are the different level lockings using the synchronization keyword?
  125. Class level lock Object level lock
    Method level lock
    Block level lock
  126. Can a abstract method have the static qualifier?
  127. No
  128. What are the different types of qualifier and what is the default qualifier?
  129. public, protected, private, package (default)
  130. What do you mean by a Classloader?
  131. Classloader is the one which loads the classes into the JVM.
  132. What are the implicit packages that need not get imported into a class file?
  133. java.lang
  134. What are the ways in which you can instantiate a thread?
  135. Using Thread class By implementing the Runnable interface and giving that handle to the Thread class.
  136. What is a socket?
  137. A socket is an endpoint for communication between two machines.
  138. What are the threads will start, when you start the java program?
  139. Finalizer, Main, Reference Handler, Signal Dispatcher
  140. What is the purpose of finalization?
  141. The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
  142. What is the difference between the Boolean & operator and the && operator?
  143. If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.
  144. How many times may an object’s finalize() method be invoked by the garbage collector?
  145. An object’s finalize() method may only be invoked once by the garbage collector.
  146. What is the purpose of the finally clause of a try-catch-finally statement?
  147. The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.
  148. What is the difference between a break statement and a continue statement?
  149. A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.
  150. What must a class do to implement an interface?
  151. It must provide all of the methods in the interface and identify the interface in its implements clause.
  152. What is the difference between a static and a non-static inner class?
  153. A non-static inner class may have object instances that are associated with instances of the class’s outer class. A static inner class does not have any object instances.
  154. What is an object’s lock and which object’s have locks?
  155. An object’s lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object’s lock. All objects and classes have locks. A class’s lock is acquired on the class’s Class object.
  156. Can an object be garbage collected while it is still reachable?
  157. A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected.
  158. Does a class inherit the constructors of its superclass?
  159. A class does not inherit constructors from any of its superclasses.


  1. good collection, but instead of posting the answers directly below the question either hide them or keep them at the end. my 2 cents :)

  2. Hi Deepti, will look into some javascript for it,and will try that... thanks for .02 USD :)

  3. Thank you. Found it interesting and useful. Java is a general purpose, high-level, class-based and object-oriented programming language. And we provide Java training at Fita.