2016-06-08

Java interviews Question and answers for new employees / advance programmer and for fresher programmers.

1. What is the GregorianCalendar class?

Answer: The GregorianCalendar provides support for traditional Western calendars

2. Can a constructor be made final?

Answer: No, this is not possible.

3. What do you mean by Access Modifier?

Answer: Java provides access modifiers to set access levels for classes, variables, methods and constructors. A member has package or default accessibility when no accessibility modifier is specified.

4. When is the ArrayStoreException thrown?

Answer: When copying elements between different arrays, if the source or destination arguments are not arrays or their types are not compatible, an ArrayStoreException will be thrown.

5. Explain Runtime Exceptions?

Answer: It is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.

6. According to Java Operator precedence, which operator is considered to be with highest precedence?

Answer: Postfix operators i.e () [] . is at the highest precedence.

7. What restrictions are placed on method overriding?

Answer: Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides.

8. Is there any limitation of using Inheritance?

Answer: Yes, since inheritance inherits everything from the super class and interface, it may make the subclass too clustering and sometimes error-prone when dynamic overriding or dynamic overloading in some situation.

9. Define canvas?

Answer: It is a simple drawing surface which are used for painting images or to perform other graphical operations.

10. What is a Socket?

Answer: Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.

11. Can you access non static variable in static context ?

Answer: A static variable in Java belongs to its class and its value remains the same for all its instances. A static variable is initialized when the class is loaded by the JVM. If your code tries to access a non-static variable, without any instance, the compiler will complain, because those variables are not created yet and they are not associated with any instance.

12. Why Vector class is used?

Answer: The Vector class provides the capability to implement a growable array of objects. Vector proves to be very useful if you don't know the size of the array in advance, or you just need one that can change sizes over the lifetime of a program.

13. Explain the use of sublass in a Java program?

Answer: Sub class inherits all the public and protected methods and the implementation. It also inherits all the default modifier methods and their implementation.

14. What is an applet?

Answer: An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because it has the entire Java API at its disposal.

15. What is a WAR file?

Answer: This is Web Archive File and used to store XML, java classes, and JavaServer pages. which is used to distribute a collection of JavaServer Pages, Java Servlets, Java classes, XML files, static Web pages etc.

16. What invokes a thread's run() method?

Answer: After a thread is started, via its start() method of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.

17. If a variable is declared as private, where may the variable be accessed?

Answer: A private variable may only be accessed within the class in which it is declared.

18. What is currentThread()?

Answer: It is a public static method used to obtain a reference to the current thread.

19. An applet extend which class?

Answer: An applet extends java.applet.Applet class.

20. What is the difference between inner class and nested class?

Answer: When a class is defined within a scope of another class, then it becomes inner class. If the access modifier of the inner class is static, then it becomes nested class.

21. What is the relationship between clipping and repainting under AWT?

Answer: When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting.

22. Can a class declared as private be accessed outside it's package?

Answer: No, it's not possible to accessed outside it's package.

23. What is Downcasting?

Answer: It is the casting from a general to a more specific type, i.e. casting down the hierarchy.

24. What is a static variable?

Answer: Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.

25. Why is the role of init() method under applets?

Answer: It initializes the applet and is the first method to be called.

26. What is function overloading?

Answer: If a class has multiple functions by same name but different parameters, it is known as Method Overloading.

27. Which Java operator is right associative?

Answer: The = operator is right associative.

28. Which package is used for pattern matching with regular expressions?

Answer: java.util.regex package is used for this purpose.

29. How Java enabled High Performance?

Answer: Java uses Just-In-Time compiler to enable high performance. Just-In-Time compiler is a program that turns Java bytecode, which is a program that contains instructions that must be interpreted into instructions that can be sent directly to the processor.

30. List primitive Java types?

Answer: The eight primitive types are byte, char, short, int, long, float, double, and boolean.

31. Can constructor be inherited?

Answer: No, constructor cannot be inherited.

32. What do you know about Java?

Answer: Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

33. What are the supported platforms by Java Programming Language?

Answer: Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX/Linux like HP-Unix, Sun Solaris, Redhat Linux, Ubuntu, CentOS, etc.

34. What is runtime polymorphism or dynamic method dispatch?

Answer: Runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass.

35. Explain main thread under Thread class execution?

Answer: The main thread is created automatically and it begins to execute immediately when a program starts. It ia thread from which all other child threads originate.

36. Which are the two subclasses under Exception class?

Answer: The Exception class has two main subclasses : IOException class and RuntimeException Class.

37. What is the difference between the paint() and repaint() methods?

Answer: The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.

38. When a byte datatype is used?

Answer: This data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an int.

39. java.util.regex consists of which classes?

Answer: java.util.regex consists of three classes − Pattern class, Matcher class and PatternSyntaxException class.

40. What is Singleton class?

Answer: Singleton class control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes.

41. What's the difference between an interface and an abstract class? Also discuss the similarities.

Answer: Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes. Interface is a Java Object containing method declaration and doesn't contain implementation. The classes which have implementing the Interfaces must provide the method definition for all the methods Abstract class is a Class prefix with a abstract keyword followed by Class definition. Interface is a Interface which starts with interface keyword. Abstract class contains one or more abstract methods. where as Interface contains all abstract methods and final declarations Abstract classes are useful in a situation that Some general methods should be implemented and specialization behavior should be implemented by child classes. Interfaces are useful in a situation that all properties should be implemented. Differences are as follows: * Interfaces provide a form of multiple inheritance. A class can extend only one other class. * Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc. * A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class. * Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast. Similarities: * Neither Abstract classes or Interface can be instantiated.

42. What is a Local Variable?

Answer: Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and it will be destroyed when the method has completed.

43. What is Abstraction?

Answer: It refers to the ability to make a class abstract in OOP. It helps to reduce the complexity and also improves the maintainability of the system.

44. What is a Constructor, Constructor Overloading in Java and Copy-Constructor ?

Answer: A constructor gets invoked when a new object is created. Every class has a constructor. In case the programmer does not provide a constructor for a class, the Java compiler (Javac) creates a default constructor for that class. The constructor overloading is similar to method overloading in Java. Different constructors can be created for a single class. Each constructor must have its own unique parameter list. Finally, Java does support copy constructors like C++, but the difference lies in the fact that Java doesn’t create a default copy constructor if you don’t write your own.

45. What are the basic interfaces of Java Collections Framework ?

Answer: Java Collections Framework provides a well designed set of interfaces and classes that support operations on a collections of objects. The most basic interfaces that reside in the Java Collections Framework are: • Collection, which represents a group of objects known as its elements. • Set, which is a collection that cannot contain duplicate elements. • List, which is an ordered collection and can contain duplicate elements. • Map, which is an object that maps keys to values and cannot contain duplicate keys.

46. What are Transient and Volatile Modifiers?

Answer: Transient: The transient modifier applies to variables only and it is not stored as part of its object’s Persistent state. Transient variables are not serialized. Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.

47. Explain garbage collection in Java?

Answer: It uses garbage collection to free the memory. By cleaning those objects that is no longer reference by any of the program.

48. What is the difference between Swing and AWT components?

Answer: AWT components are heavy-weight, whereas Swing components are lightweight. Heavy weight components depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button.

49. What will be the default values of all the elements of an array defined as an instance variable?

Answer: If the array is an array of primitive types, then all the elements of the array will be initialized to the default value corresponding to that primitive type.

50. What is the default value of byte datatype in Java?

Answer: Default value of byte datatype is 0.

51. What is the difference between error and an exception?

Answer: An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. Exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist.

52. Why is String class considered immutable?

Answer: The String class is immutable, so that once it is created a String object cannot be changed. Since String is immutable it can safely be shared between many threads ,which is considered very important for multithreaded programming.

53. Why do we need wrapper classes?

Answer: We can pass them around as method parameters where a method expects an object. It also provides utility methods.

54. What is structure of Java Heap ? What is Perm Gen space in Heap ?

Answer: The JVM has a heap that is the runtime data area from which memory for all class instances and arrays is allocated. It is created at the JVM start-up. Heap memory for objects is reclaimed by an automatic memory management system which is known as a garbage collector. Heap memory consists of live and dead objects. Live objects are accessible by the application and will not be a subject of garbage collection. Dead objects are those which will never be accessible by the application, but have not been collected by the garbage collector yet. Such objects occupy the heap memory space until they are eventually collected by the garbage collector.

55. What is the difference between the >> and >>> operators?

Answer: The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.

56. Give some features of Interface?

Answer: It includes −

Interface cannot be instantiated

An interface does not contain any constructors.

All of the methods in an interface are abstract.

57. Where and how can you use a private constructor?

Answer: Private constructor is used if you do not want other classes to instantiate the object and to prevent subclassing.T

58. What are Wrapper classes?

Answer: These are classes that allow primitive types to be accessed as objects. Example: Integer, Character, Double, Boolean etc.

59. What are pass by reference and pass by value ?

Answer: When an object is passed by value, this means that a copy of the object is passed. Thus, even if changes are made to that object, it doesn’t affect the original value. When an object is passed by reference, this means that the actual object is not passed, rather a reference of the object is passed. Thus, any changes made by the external method, are also reflected in all places.

60. What is an object's lock and which object's have locks?

Answer: 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.

61. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

Answer: The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.

62. What is the difference between a Window and a Frame?

Answer: The Frame class extends Window to define a main application window that can have a menu bar.

63. List any five features of Java?

Answer: Some features include Object Oriented, Platform Independent, Robust, Interpreted, Multi-threaded

64. When Abstract methods are used?

Answer: If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as abstract.

65. Difference between throw and throws?

Answer: It includes:

Throw is used to trigger an exception where as throws is used in declaration of exception.

Without throws, Checked exception cannot be handled where as checked exception can be propagated with throws.

66. Difference between Overloading and Overriding?

Answer: Method overloading increases the readability of the program. Method overriding provides the specific implementation of the method that is already provided by its super class parameter must be different in case of overloading, parameter must be same in case of overriding.

67. What is daemon thread?

Answer: Daemon thread is a low priority thread, which runs intermittently in the back ground doing the garbage collection operation for the java runtime system.

68. What is Polymorphism?

Answer: Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

69. Can try statements be nested?

Answer: Yes

70. Can a top level class be private or protected?

Answer: No, a top level class can not be private or protected. It can have either "public" or no modifier.

71. What is JAR file?

Answer: JAR files is Java Archive fles and it aggregates many files into one. It holds Java classes in a library. JAR files are built on ZIP file format and have .jar file extension.

72. What is the difference between the size and capacity of a Vector?

Answer: The size is the number of elements actually stored in the vector, while capacity is the maximum number of elements it can store at a given instance of time.

73. Where import statement is used in a Java program?

Answer: Import statement is allowed at the beginning of the program file after package statement.

74. Why deletion in LinkedList is fast than ArrayList?

Answer: Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.

75. What is Dynamic Binding(late binding)?

Answer: Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at run-time.

76. What is difference between Path and Classpath?

Answer: Path and Classpath are operating system level environment variales. Path is defines where the system can find the executables(.exe) files and classpath is used to specify the location of .class files.

77. How to add menushortcut to menu item?

Answer: If there is a button instance called b1, you may add menu short cut by calling b1.setMnemonic('F'), so the user may be able to use Alt+F to click the button.

78. How do you decide when to use ArrayList and LinkedList?

Answer: If you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList should be used. If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList should be used.

79. Under what conditions is an object's finalize() method invoked by the garbage collector?

Answer: The garbage collector invokes an object's finalize() method when it detects that the object has become unreachable.

80. Which number is denoted by leading 0x or 0X in java?

Answer: Hexadecimal Numbers are denoted by leading 0x or 0X in java, example − 0XF

81. What does the static keyword mean ? Can you override private or static method in Java ?

Answer: The static keyword denotes that a member variable or method can be accessed, without requiring an instantiation of the class to which it belongs. A user cannot overridestatic methods in Java, because method overriding is based upon dynamic binding at runtime and static methods are statically binded at compile time. A static method is not associated with any instance of a class so the concept is not applicable.

82. The immediate superclass of the Applet class?

Answer: Panel is the immediate superclass. A panel provides space in which an application can attach any other component, including other panels.

83. What is a Class Variable?

Answer: These are variables declared with in a class, outside any method, with the static keyword.

84. Define JIT compiler?

Answer: It improves the runtime performance of computer programs based on bytecode.

85. Explain the usage of this() with constructors?

Answer: It is used with variables or methods and used to call constructer of same class.

86. Is there any need to import java.lang package?

Answer: No, there is no need to import this package. It is by default loaded internally by the JVM.

87. When a thread is created and started, what is its initial state?

Answer: A thread is in the ready state as initial state after it has been created and started.

88. Why Generics are used in Java?

Answer: Generics provide compile-time type safety that allows programmers to catch invalid types at compile time. Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods or, with a single class declaration, a set of related types.

89. What are some advantages and disadvantages of Java Sockets?

Answer: Some advantages of Java Sockets: Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications. Sockets cause low network traffic. Unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request, Java applets can send only necessary updated information. Some disadvantages of Java Sockets: Security restrictions are sometimes overbearing because a Java applet running in a Web browser is only able to establish connections to the machine where it came from, and to nowhere else on the network Despite all of the useful and helpful Java features, Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.

90. What is difference between Array and ArrayList ? When will you use Array over ArrayList ?

Answer: The Array and ArrayListclasses differ on the following features: • Arrays can contain primitive or objects, while an ArrayList can contain only objects. • Arrays have fixed size, while an ArrayList is dynamic. • An ArrayListprovides more methods and features, such as addAll, removeAll, iterator, etc. • For a list of primitive data types, the collections use autoboxing to reduce the coding effort. However, this approach makes them slower when working on fixed size primitive data types.

91. What are the two ways in which Thread can be created?

Answer: Thread can be created by: implementing Runnable interface, extending the Thread class.

92. Explain TreeSet?

Answer: It is a Set implemented when we want elements in a sorted order.

93. What is the difference between Enumeration and Iterator interfaces ?

Answer: Enumeration is twice as fast as compared to an Iterator and uses very less memory. However, the Iterator is much safer compared to Enumeration, because other threads are not able to modify the collection object that is currently traversed by the iterator. Also, Iteratorsallow the caller to remove elements from the underlying collection, something which is not possible with Enumerations.

94. Does it matter in what order catch statements for FileNotFoundException and IOException are written?

Answer: Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.

95. Is it necessary that each try block must be followed by a catch block?

Answer: It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block or a finally block.

96. Which class represents the socket that both the client and server use to communicate with each other?

Answer: java.net.Socket class represents the socket that both the client and server use to communicate with each other.

97. What kind of variables a class can consist of?

Answer: A class consist of Local variable, instance variables and class variables.

98. Which object oriented Concept is achieved by using overloading and overriding?

Answer: Polymorphism

99. What is finalize() method?

Answer: It is possible to define a method that will be called just before an object's final destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly.

100. What is the purpose of default constructor?

Answer: The java compiler creates a default constructor only if there is no constructor in the class.

101. Can you write a Java class that could be used both as an applet as well as an application?

Answer: Yes, just add a main() method to the applet.

102. Why is StringBuffer called mutable?

Answer: The String class is considered as immutable, so that once it is created a String object cannot be changed. If there is a necessity to make alot of modifications to Strings of characters then StringBuffer should be used.

103. What are the restriction imposed on a static method or a static block of code?

Answer: A static method should not refer to instance variables without creating an instance and cannot use "this" operator to refer the instance.

104. What's the difference between constructors and normal methods?

Answer: Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times and it can return a value or can be void.

105. Define Network Programming?

Answer: It refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.

106. When super keyword is used?

Answer: If the method overrides one of its superclass's methods, overridden method can be invoked through the use of the keyword super. It can be also used to refer to a hidden field.

107. What is the importance of hashCode() and equals() methods ?

Answer: A HashMap in Java uses the hashCode and equals methods to determine the index of the key-value pair. These methods are also used when we request the value of a specific key. If these methods are not implemented correctly, two different keys might produce the same hash value and thus, will be considered as equal by the collection. Furthermore, these methods are also used to detect duplicates. Thus, the implementation of both methods is crucial to the accuracy and correctness of the HashMap.

108. What is dot operator?

Answer: The dot operator(.) is used to access the instance variables and methods of class objects.It is also used to access classes and sub-packages from a package.

109. List two Java IDE’s?

Answer: Netbeans, Eclipse, etc.

110. Disadvantages of Java Sockets?

Answer: Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.

111. What are synchronized methods and synchronized statements?

Answer: Synchronized methods are methods that are used to control access to an object. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

112. Explain the available thread states in a high-level?

Answer: During its execution, a thread can reside in one of the following states: • Runnable: A thread becomes ready to run, but does not necessarily start running immediately. • Running: The processor is actively executing the thread code. • Waiting: A thread is in a blocked state waiting for some external processing to finish. • Sleeping: The thread is forced to sleep. • Blocked on I/O: Waiting for an I/O operation to complete. • Blocked on Synchronization: Waiting to acquire a lock. • Dead: The thread has finished its execution.

113. Which method of the Component class is used to set the position and size of a component?

Answer: setBounds() method is used for this purpose.

114. How HashMap works in Java ?

Answer: A HashMap in Java stores key-value pairs. The HashMap requires a hash function and useshashCode and equals methods, in order to put and retrieve elements to and from the collection respectively. When the put method is invoked, the HashMap calculates the hash value of the key and stores the pair in the appropriate index inside the collection. If the key exists, its value is updated with the new value. Some important characteristics of a HashMap are its capacity, its load factor and the threshold resizing.

115. What is the difference between StringBuffer and StringBuilder class?

Answer: Use StringBuilder whenever possible because it is faster than StringBuffer. But, if thread safety is necessary then use StringBuffer objects.

116. What is the difference between a break statement and a continue statement?

Answer: 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.

117. Why Packages are used?

Answer: Packages are used in Java in-order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations, etc., easier.

118. What is Comparable Interface?

Answer: It is used to sort collections and arrays of objects using the collections.sort() and java.utils. The objects of the class implementing the Comparable interface can be ordered.

119. What is the Collections API?

Answer: The Collections API is a set of classes and interfaces that support operations on collections of objects.

120. Life cycle of an applet includes which steps?

Answer: Life cycle involves the following steps −

Initialization

Starting

Stopping

Destroying

Painting

121. Explain Set Interface?

Answer: It is a collection of element which cannot contain duplicate elements. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.

122. What is function overriding?

Answer: If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding.

123. Which method is used to create the daemon thread?

Answer: setDaemon method is used to create a daemon thread.

124. Variables used in a switch statement can be used with which datatypes?

Answer: Variables used in a switch statement can only be a string, enum, byte, short, int, or char.

125. Explain suspend() method under Thread class>

Answer: It is used to pause or temporarily stop the execution of the thread.

126. How you can force the garbage collection?

Answer: Garbage collection automatic process and can't be forced. You could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately. Garbage collection is one of the most important feature of Java, Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program can't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.

127. Which arithmetic operations can result in the throwing of an ArithmeticException?

Answer: Integer / and % can result in the throwing of an ArithmeticException.

128. What is JVM ? Why is Java called the Platform Independent Programming Language ?

Answer: A Java virtual machine (JVM) is a process virtual machine that can execute Java bytecode. Each Java source file is compiled into a bytecode file, which is executed by the JVM. Java was designed

Show more