Showing posts with label java interview. Show all posts
Showing posts with label java interview. Show all posts

Sunday, 29 September 2013

Java Interview Questions

// siddhu vydyabhushana // 1 comment
java interview questions
Q: What is the difference between an Interface and an Abstract class?
A: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.

Q: What is the purpose of garbage collection in Java, and when is it used?
A: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

Q: Describe synchronization in respect to multithreading.
A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors. 

Q: Explain different way of using thread?
A: The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.

Q: What are pass by reference and passby value?
A: Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed. 

Q: What is HashMap and Map?
A: Map is Interface and Hashmap is class that implements that.

Q: Difference between HashMap and HashTable?
A: The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.

Q: Difference between Vector and ArrayList?
A: Vector is synchronized whereas arraylist is not.

Q: Difference between Swing and Awt?
A: AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.

Q: What is the difference between a constructor and a method?
A: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

Q: What is an Iterator?
A: Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.

Q: State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
A: public : Public class is visible in other packages, field is visible everywhere (class must be public too)
private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package

Q: What is an abstract class?
A: Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.

Q: What is static in java?
A: Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

Q: What is final?
A: A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).
Read More

Wednesday, 24 July 2013

Java interview question and answers

// siddhu vydyabhushana // Leave a Comment

1. Java OOPS Concepts ?

Ans. Abstraction , Encapsulation , Inheritance and Polymorphism. 

2. Difference between Abstract and Concrete Classes ?

Ans. Abstract classes are only meant to be sub classed and not meant to be instantiated whereas concrete classes are meant to be instantiated.

3. Difference between Overloading and Overriding ?


Overloading - Similar Signature but different definition , like function overloading. 

Overriding - Overriding the Definition of base class in the derived class.

4. Types of Inner classes ?

Ans. Simple Inner Class, Local Inner Class, Anonymous Inner Class , Static Nested Inner Class.

5. Difference between TreeMap and HashMap ?

Ans. They are different the way they are stored in memory. TreeMap stores the Keys in order whereas HashMap stores the key value pairs randomly. 

6. Difference between List , Sets and Maps ?

Ans. Lists - Members are stored in sequence in memory and can be accessed through index. Sets - There is no relevance of sequence and index. Sets doesn't contain duplicates whereas multiset can have duplicates. Maps - Contains Key , Value pairs.

7. Difference between Private , Public and Protected ?

Ans. Private - Not accessible outside object scope. Public - Accessible outside object scope. Protected - Becomes private when inherited.

8. What is role of Synchronization in Java ?

Ans. Managing exclusive access of the code block to single thread at a time to maintain its integrity.

9. What is Default Access ?

Ans. Accessible only by the objects in the same package.

10. Difference between Vector and ArrayList ?

Ans. Vectors are synchronized whereas Array lists are not.

11. Difference between class and objects ?

Ans. Class is a template using which objects are created in memory.

12. Describe Garbage Collection in Java ?

Ans. Mechanism by which Java reclaims the memory inaccessible by the application.

13. What are the types of Polymorphism in Java ?

Ans. Static ( function overloading ) and Run time ( Virtual functions ) 

14. Different ways of using threads ?

Ans. Extending Thread class and implementing runnable interface.

15. Difference between Composition and Inheritence ?

Ans. Has a relationship vs Is a relationship.

16. What are Static variables ?

Ans. Correspond to class and not objects. All objects share that variable.

17. Difference between Interfaces and Abstract classes ?

Ans. Abstract classes have a body ( member elements ) where as Interfaces just have method declarations. 

18. Constructor ?

Ans. Its an operation that creates and initializes the object.

19. Dynamic Binding ?

Ans. Association of function call to function definition during run time.

20. Volatile ?

Ans. Volatile is a declaration that a variable can be accessed by multiple threads and hence shouldn't be cached.

21. Serialization ?

Ans. Storing the state of an object in a file or other medium.

22. Transient ?

Ans. keyword in Java is used to indicate that a field should not be serialized.

23. Static Methods ?

Ans. Can only operates on static variables.

25. Final variable ?

Ans. Variable constant. Variable value can't be changed after instantiation.

26. Final Methods ?

Ans. Can't be overridden

27. Final Classes ?

Ans. Can't be sub classed.

28 Immutable Object ?

Ans. Object that can't be changed after instantiation.

29. checked and unchecked exceptions ?

Ans. For checked exceptions compiler throws a errors if they are not checked whereas unchecked exceptions and caught during runtime only and hence can't be checked.

30 Example of checked and unchecked exception ?

Ans. ClassNotFoundException is checked exception whereas NoClassDefFoundError is a unchecked exception.

31. Singleton Class ?

Ans. Using which only 1 object can be created.

32. Name few Java exceptions ?

Ans. IndexOutofBound , NoClassDefFound , OutOfMemory , IllegalArgument.

33. Name few Design Patterns used for designing Java applications ?

Ans. Singleton , Factory , Abstract Factory , Proxy , Command , Builder. 

34. Give an example of Runtime Polymorphism ?

Ans. Action Mapping in a web application , Generics.

35. Which of the following is tightly bound ? Inheritance or Composition ?

Ans. Composition.

36. Give an Example of Generics in Java 5 ?

Ans. List aList = new ArrayList < number> 

37. How can we make sure that a code segment gets executed even in case of uncatched exceptions ?

Ans. By putting it within finally.

38. Can we extend an interface ?

Ans. We implement the interface.

39. Does Java support multiple inheritence ?

Ans. We can't extend multiple classes but can implement multiple interfaces.

40. Can we use an interface reference for referring to an object ?

Ans Yes we can do it for object implementing that interface. 

41. What do you mean by return type Void  ?

Ans. Returns Nothing.

42. Is Java Compiled or an Interpreted language ?

Ans Both

43. What is a class file ?

Ans. Compiled Java files.

44. Why Java is a called a platform independent language ?

Ans. Java creates the pre compiled files ( class files ) which can then be interpreted on multiple platforms.

45. Native ?

Ans. Used in method declarations to specify that the method is not implemented in the same Java source file, but rather in another language

46. super ?

Ans. Used to access members of a class inherited by the class in which it appears.

47. What is "this" keyword used for ?

Ans. Used to represent an instance of the class in which it appears

48. Transient ?

Ans. Declares that an instance field is not part of the default serialized form of an object

49. What will happen if we declare a class abstract as well as final ?

Ans. Compile time error.

50 Encapsulation ?

Ans. Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse

Subscribe to Java News and Posts.
Get latest updates and posts on Java from
Enter your email address:

Delivered by FeedBurner

51. Inheritence ?

Ans. Inheritance is the process by which one object acquires the properties of another object.

52. Polymorphism ?

Ans. Polymorphism is the feature that allows one interface to be used for general class actions

53. Difference between assignment and initialization ?

Ans. Assignment can be done anytime but initialization can be done only once during object instantiation.

54. difference between boolean and Boolean ?

Ans. boolean is a primitive type whereas Boolean is a class.

55. Immutable ?

Ans. Objects that can't be changed after initialization ?

56. Give an example of immutable class ?

Ans. String

57. Casting ?

Ans. Process to convert one data type to another.

58. Finalize () ?

Ans. finalize() method is used just before an object is destroyed.

59. Marker Interfaces ?

Ans. These are the interfaces which have no declared methods.

60. Name few Java marker interfaces ?

Ans. Serializable and cloneable.

61. Is runnable a Marker interface ?

Ans. No , it has run method declared.

62 String and StringBuffer ?

Ans. String is an immutable class where StringBuffer is not.

63. Process and Thread ?

Ans. Process is a program in execution whereas thread is a separate path of execution in a program.

64. Thread states ?

Ans. ready, running, waiting and dead.

65. Deadlock ?

Ans. When two threads are waiting each other and can’t precede the program is said to be deadlock.

66. Serialization and Deserialization ?

Ans. Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.

67. Difference between Java 1.4 and Java 5 ?

Ans. Generics , Autoboxing , Enum and Static Imports.

68. Autoboxing ?

Ans. Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes

69. Enum ?

Ans. An enum type is a special data type that enables for a variable to be a set of predefined constants

70. Wrapper Classes ?

Ans. A wrapper class is any class which "wraps" or "encapsulates" the functionality of another class or component.

71. Primitive Wrapper Classes ?

Ans. A Wrapper Class that wraps or encapsulates the primitive data type.

72. What is automatic conversion of primitive data type to its Wrapper class called ?

Ans. Autoboxing.

73. What Design pattern Wrapper Classes implement ?

Ans. Adapter.

74. Import ?

Ans. Enables the programmer to abbreviate the names of classes defined in a package.

75. Servlet Chaining ?

Ans. Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request.

76. What is the difference between set and list?

Ans. Set stores elements in an unordered way but does not contain duplicate elements, whereas list stores elements in an ordered way but may contain duplicate elements.

77. Difference between HashMap and HashTable ?

Ans. The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.

78. Iterator ?

Ans. Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn.

79. JVM ?

Ans. Java Virtual Machine or JVM is an abstract which provides the runtime environment for the Java byte code to run.

80. JDK ?

Ans. Java Development Kit or JDK is physical entity that comprises of JRE and Development Tools. 

81. JRE ?

Ans. Java Run Time Environment is the implementation of JVM.

82. different types of memory used by JVM ?

Ans. Class , Heap , Stack , Register , Native Method Stack.

83. Class Loader ?

Ans. Part of JVM which is used to load classes and interfaces.

84. Does Static Public Void instead of Public static Void gives compilation error ?

Ans. No

85. Does constructor returns any value ?

Ans. Yes , the current instance or object of the class.

86. Can we make constructor final ?

Ans. No

87. Why main method is static ?

Ans. Object needs to be created for calling non static methods.

88. Static Block ?

Ans. It is executed before main method at the time of class loading.

89. Can we execute program without mail method ?

Ans. Yes , one way is through static block.

90. Cloning ?

Ans. Keyword to create the exact copy of the object.

91. Can we overload main method ?

Ans. Yes.

92. Can we declare main method as final ?

Ans. Yes.

93. static binding ?

Ans. Associating function call and its definition during compile time.

94. Dynamic Binding ?

Ans. Associating function call and its definition during runtime.

95. Can we declare an interface method static ?

Ans. No

96. Can an interface be final ?

Ans. No

97. Can we define private , protected modifiers with variables in interface ?

Ans. No, they are implicitely public.

98. Static import ?

Ans. By static import , we can access the static members of a class directly without prefixing it with the class name.

99. Base class for Error and Exceptions ?

Ans. Throwable

100. StringBuffer and StringBuilder ?

Subscribe to Java News and Posts.
Get latest updates and posts on Java from
Enter your email address:

Delivered by FeedBurner

Ans. StringBuffer is synchronized whereas String Builder is not.

101. Default Package for Collection classes ?

Ans. Java.Util

102. Difference between List and Queue ?

Ans. In queue access can only happen at the ends whereas we can access any element of the list.

103. Difference between Vector and ArrayList ?

Ans. Vectors are synchronized whereas ArrayList are not.

104. Which is the base interface for all collection classes ?

Ans. Collection interface.

105. How can we make HashMap synchronized ?

Ans. Map m = Collections.synchronizedMap(hashMap);

106. Difference between Map and HashMap ?

Ans. Map is an interface where HashMap is the concrete class.

107. Property Class ?

Ans. The properties class is a subclass of Hashtable that can be read from or written to a stream.

108 Why Java is a preferred technology for Web Applications ?

Ans. Web application involves dealing with multiple requests and thread and hence deals with lot of memory allocation and de allocation. Hence Java with its intrinsic capability of Garbage collection offer a perfect platform.

109. What are concepts introduced with Java 5 ?

Ans. Generics , Enums , Autoboxing , Annotations and Static Import.

110. Difference between get and post ?

Ans. Request parameters in get are passed within url whereas with post these are passed within post body as object.

111. Difference between C++ and Java ?

Ans. We have pointers in C++ , We have garbage collection in Java.

112. Name few Design Patterns ?

Ans. Singleton , Adapter , Factory , Abstract Factory , Builder , Facade , Observer , Proxy , Prototype.

113. Give an Example of Factory Design Pattern ?

Ans. Action Mapping within Web Application. 

114. Give an example of Adapter design pattern ?

Ans. Wrapper Classes.

115. Can we override static methods ?

Ans. Yes , static methods can be overridden by static methods in sub class.

116. What precaution should be used while dealing with static variables ?

Ans. Static variables are shared by all objects of the class and hence each instance may update it with its local value.

117. Can we override main method ?

Ans. No

118. Difference between server side and client side validation ?

Ans. Client side validation is done using scripting technologies like javascript before the form is submitted to server whereas server side validation is done after the form is submitted to server.

119. Difference between sleep and wait ? 

Ans. Sleep puts thread aside for exactly the time specified. Wait causes a wait of up to time specified. A thread could stop waiting earlier if it receives the notify() or notifyAll() call.

120. Name Wrapper classes available for primitive types ?


boolean  - java.lang.Boolean
byte - java.lang.Byte
char - java.lang.Character
double - java.lang.Double
float - java.lang.Float
int - java.lang.Integer
long - java.lang.Long
short - java.lang.Short
void - java.lang.Void

121. Explain System.out.println ?

Ans. System is the class having static variable out that defaults to system console and println is the overloaded method.

122. Explain public static void main() ?

Ans. public means it has public access, static means that the method can be invoked without instantiating the object, void means it returns nothing. 

123. What is Java Byte Code ?

Ans. Java bytecode is the form of instructions that the Java virtual machine executes.

124. What is the relation between class file and byte code ?

Ans. Class files holds the instructions in byte code.

125. How can we make the object immutable ?

Ans. By making it a final class and making all members as private with those being initialized through constructor.

126. What is the purpose of making an object immutable ?

Ans. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.

127. Explain the scenerios to choose between String , StringBuilder and StringBuffer ?

  • If the Object value will not change in a scenario use String Class because a String object is immutable.
  • If the Object value can change and will only be modified from a single thread, use a StringBuilder because StringBuilder is unsynchronized(means faster).
  • If the Object value may change, and can be modified by multiple threads, use a StringBuffer because StringBuffer is thread safe(synchronized).
128. Explain java.lang.OutOfMemoryError ?

Ans. This Error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

129. Difference between arraylist and linkedlist ?

Ans. Array list maintains indices like array whereas Linked List maintain pointers to the next element. 

130. Difference between hashtable and hashmap ?

Ans. Hashtable are synchronized whereas hashmaps are not. Hashtable doesn't allow null values whereas HashMaps allows null values.

131. Can we have multiple servlets in a web application and How can we do that ?

Ans. Yes by making entries in web.xml

132. Are static members serialized ?

Ans. Static members don't belong to a object and hence are not serialized.

133. How can we manage Error Messages in the web application ?

Ans. Within file.

134. What is the use of Market interface if they don't hold anything ?

Ans. As the name suggest , They just mark a class and just indicate something to compiler and JVM.

135. Is JVM, a compiler or interpretor ?

Ans. Its an interpretor.

136. Is Synchronization an overhead ?

Ans. Synchronization has relevance only if a code segment can be accessed by multiple threads and hence may result in ambiguity. Yes Its an overhead if simultaneous access doesn't pose any problem.

137. Difference between implicit and explicit type casting ?

Ans. An explicit conversion is where you use some syntax to tell the program to do a conversion whereas in case of implicit type casting you need not provide the data type. 
Read More