Advanced Java Interview Questions -8

Advanced Java Interview Questions -8

1. If an object is garbage collected, can it become reachable again?

Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.

2. What is the difference between the prefix and postfix forms of the ++ operator?

The prefix form performs the increment operation and returns the value of the increment operation.

The postfix form returns the current value all of the expression and then performs the increment operation on that value.

3. What are synchronized methods and synchronized statements?

Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method’s object or class.

Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

4. What is the purpose of a statement block?

A statement block is used to organize a sequence of statements as a single statement group.

5. What is a compilation unit?

A compilation unit is a Java source code file.

6. What interface is extended by AWT event listeners?

All AWT event listeners extend the java.util.EventListener interface.

7. What restrictions are placed on method overriding?

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.
The overriding method may not throw any exceptions that may not be thrown by the overridden method.

8. What are the two basic ways in which classes that can be run as threads may be defined?

A thread class may be declared as a subclass of Thread, or it may implement the Runnable interface.

9. What are the problems faced by Java programmers who don’t use layout managers?

Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system.

10. How are the elements of a GridBagLayout organized?

The elements of a GridBagLayout are of equal size and are laid out using the squares of a grid.

11  How does a try statement determine which catch clause should be used to handle an exception?

When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored.

12 Can an unreachable object become reachable again?

An unreachable object may become reachable again. This can happen when the object’s finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects.

13  When is an object subject to garbage collection?

An object is subject to garbage collection when it becomes unreachable to the program in which it is used.

14 What an I/O filter?

An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

15  How is it possible for two String objects with identical values not to be equal under the == operator?

The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory.

16  What is the purpose of the enableEvents() method?

The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event.
The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.

17  What Checkbox method allows you to tell if a Checkbox is checked?

18 What state is a thread in when it is executing?

An executing thread is in the running state.

19 What classes of exceptions may be thrown by a throw statement?

A throw statement may throw any expression that may be assigned to the Throwable type.

20. What are E and PI?

E is the base of the natural logarithm and PI is mathematical value pi.

21  Are true and false keywords?

The values true and false are not keywords.

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

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

23  What are three ways in which a thread can enter the waiting state?

A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object’s lock, or by invoking an object’s wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

24. Can an abstract class be final?

An abstract class may not be declared as final.

25  What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?

The exception propagates up to the next higher level try-catch statement (if any) or results in the program’s termination.

26  What is numeric promotion?

Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.

27  What is the relationship between a method’s throws clause and the exceptions that can be thrown during the method’s execution?

A method’s throws clause must declare any checked exceptions that are not caught within the body of the method.

28  What is the difference between the JDK 1.02 event model and the event-delegation model introduced with JDK 1.1?

The JDK 1.02 event model uses an event inheritance or bubbling approach. In this model, components are required to handle their own events. If they do not handle a particular event, the event is inherited by (or bubbled up to) the component’s container. The container then either handles the event or it is bubbled up to its container and so on, until the highest-level container has been tried.
In the event-delegation model, specific objects are designated as event handlers for GUI components. These objects implement event-listener interfaces. The event-delegation model is more efficient than the event-inheritance model because it eliminates the processing required to support the bubbling of unhandled events.

29 . What are the legal operands of the instanceof operator?

The left operand is an object reference or null value and the right operand is a class, interface, or arraytype.

30. What is casting?

There are two types of casting, casting between primitive numeric types and casting between object references.
Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values.
Casting between object references is used to refer to an object by a compatible class, interface, or arraytype reference.

30 What is the difference between a Scrollbar and a ScrollPane?

A Scrollbar is a Component, but not a Container. A ScrollPane is a Container.
A ScrollPane handles its own events and performs its own scrolling.

31 What is the difference between a public and a non-public class?

A public class may be accessed outside of its package.
A non-public class may not be accessed outside of its package.

32  To what value is a variable of the boolean type automatically initialized?

The default value of the boolean type is false.

33. Can try statements be nested?

Try statements may be tested.

34 What is a Java package and how is it used?

A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces.

Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.

35  what modifiers may be used with a top-level class?

A top-level class may be public, abstract, or final.

36  What are the Object and Class classes used for?

The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program..

37  What is the difference between a field variable and a local variable?

A field variable is a variable that is declared as a member of a class.

A local variable is a variable that is declared local to a method.

38  Under what conditions is an object’s finalize() method invoked by the garbage collector?

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

39  What method must be implemented by all threads?

All tasks must implement the run() method, whether they are a subclass of Thread or implement theRunnable interface.

40. What methods are used to get and set the text label displayed by a Button object?

getLabel() and setLabel().

41 Which Component subclass is used for drawing and painting?


42 What is the return type of a program’s main() method?

A program’s main() method has a void return type.

43. What is the difference between the File and RandomAccessFile classes?

The File class encapsulates the files and directories of the local file system.

The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

44. What happens when you add a double value to a String?

The result is a String object.

45 What is your platform’s default character encoding?

If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1.

46. Name four Container classes.

Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane.

47  What is the difference between a Choice and a List?

A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice.
A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items.

48  What class of exceptions are generated by the Java run-time system?

The Java runtime system generates RuntimeException and Error exceptions.

49  What class allows you to read objects directly from a stream?

The ObjectInputStream class supports the reading of objects from input streams.

50. What is the Set interface?

The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.

51 Which package is always imported by default?

The java.lang package is always imported by default.

52. What interface must an object implement before it can be written to a stream as an object?

An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.

53  How are this and super used?

this is used to refer to the current object instance.

super is used to refer to the variables and methods of the superclass of the current object instance.

54 How can a dead thread be restarted?

A dead thread cannot be restarted.

55. What is the ResourceBundle class?

The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program’s appearance to the particular locale in which it is being run.

55. What happens if an exception is not caught?

An uncaught exception results in the uncaughtException() method of the thread’s ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.

56 What is a layout manager?

A layout manager is an object that is used to organize components in a container.

57.What are Character streams?
Character streams, provide a convenient means for handling input and output of characters. They use Unicode, and therefore, can be internationalized.

58. Write note on FileOutputStream class.
FileOutputStream creates an OutputStream that you can use to write bytes to a file. Its most commonly used constructors are
  FileOutputStream(String filepath)
  FileOutputStream(File fileobj)
 FileOutputStream(String  filepath, Boolean append)
They can throw an IOException or a SecurityException.

59 What is an Adapter class?

An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface.

60.What are Comparators?

Comparator defines, in which order the elements in TreeSet or TreeMap has to be ordered. If you want to order elements a different way, then specify a Comparator object when you construct the set or map.

61.What are Servlets?

Servlets are small programs that execute on the server side of a Web connection.
Servlets dynamically extend the functionality of a Web server.

62. What are the advantages of Servelets over CGI?

Servlets are platform-independent, because they are written in Java.        
Performance is significantly better. Servlets execute within the address space of a Web server. Creating a separate process to handle each client request isn’t necessary.
The Java Security Manager on the server enforces a set of restrictions to protect the resources on a server machine.

63. Write note on the Life Cycle of a Servlet.

Three methods are central to the life cycle of a servlet : init(), service(), destroy().
       init() is invoked only when the servlet is first loaded into memory.
       service() method is called for each HTTP request.
       destroy() method is called when the servlet is uloaded from the memeory.

64. Write note on SingleThreadModel interface.
The SingleThreadModel interface is used to indicate that only a single thread should execute the service () method of a servlet. It defines no constants and declares no methods. If a servlet implements this interface, the server creates several instances of it.

65. What is Session Tracking?

HTTP is a stateless protocol, which means that each request is independent of the previous one. However, in some applications, it is necessary to save state information, so that information can be collected from several interactions between browser and a server.
Session Tracking helps to achieve this.

66. Write note on Collection class “Stack”.

Stack is a subclass of vector that implements a standard last-in, first-out stack. Stack only defines the default constructor, which creates empty stack. Stack includes all the methods defined by Vector, and adds several of its own.

67. What is the need for creating a CustomSocket?

The real goal of using a CustomSocket with RMI is to provide some additional functionality such as compression or security. Since the socket itself doesn’t do much good without a stream that provides the additional functionality, you must first define a stream for your purposes.

68.What is Remote Method Invocation (RMI)?

Remote Method Invocation (RMI) allows a Java Object that executes on one machine to invoke a method of a Java Object that executes on another machine.  This is an important feature, because it allows you to build distributed applications.

69 What are stubs and skeletons in RMI?

A stub is Java Object that resides on the client machine.  Its function is to present the same interfaces as the remote server.  Remote method calls initiated by the client are actually directed to the stub.

A skeleton is a Java Object that resides on the server machine.  It receives request, performs deserialization, and invokes the appropriate code on the server.

70.   What do you meant by Activation in RMI?

Activation in RMI has the capability to remotely activate an object.

The activator will check the status of the remote object and perform what ever initialization is necessary to get it running again.

71.What is object serialization?

Serialization is the process of writing the state of an object to a byte stream.  This is useful when you want to save the state of your program to a persistent storage area, such as a file.  At a later time, you may restore these objects by using the process of deserialization.          

72. What is Synchronization?
   When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization.
       The general form of the synchronized statement is
                           synchronized (object){
                               // statements to be synchronized

73. In multithreading, When does a deadlock situation occur?
Deadlock situation occurs, when two threads have a circular dependency on a pair of synchronized objects.

74. What is the need of Thread Priorities?

Thread priorities are used by the thread scheduler to decide when each thread be allowed to run. Higher-priority threads get more CPU time than lower-priority threads.
To set a thread’s priority, use the setPriority() method, which is a member of Thread.
final void setPriority(int level)
75.Write note on ArrayList collection class.

The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed. ArrayList can dynamically increase or decrease in size.
                               ArrayList has the constructors:
                                         ArrayList(Collection c)
                                         ArrayList(int capacity)
76.Write note on TreeSet collection class.
              In TreeSet, objects are stored in sorted, ascending order. Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information.
                         The constructors are:
                                 TreeSet(Collection c)
             TreeSet(Comparator comp)
              TreeSet(SortedSet ss)

77. What are Maps?
             A map is an object that stores associations between keys and values or key/value pairs. Given a key, you can find its value .Both keys and values are objects.

78. Write note on Collection Algorithms.
                 The Collections framework defines several algorithms that can be applied to collections and maps. These algorithms are defined as static methods within the collections class.
                           Several of the methods can throw a ClassCastException, which occurs when an attempt is made to compare incompatible types, or an UnSupportedOperationException, which occurs when an attempt is made to modify an unmodifiable collection.

79 What is Java Streaming?
Java streaming is nothing more than a flow of data. There are input streams that direct data from the outside world from the keyboard, or a file for instance, into the computer; and output streams that direct data toward output devices such as the computer screen or a file. 
80 what are Byte streams?

Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used for example when reading or writing binary data.

81 List some Byte Stream supported classes.

82. Write note on FileInputStream class.
               The FileInputStream class creates an InputStream that you can use to read bytes from a file. Its two most common constructors are
                            FileInputStream(String filepath)
                            FileInputStream(File fileobj)

83. List some Character Stream supported classes.
    CharArrayReader    CharArrayWriter    FileReader

84. What is the use of the class “ByteArrayInputStream”?
ByteArrayInputStream is an implementation of an input stream that uses a byte array as the source. This class has two constructors, each of which requires a byte array to provide the data source:
                            ByteArrayInputStream(byte array[])
                             ByteArrayInputStream(byte array[], int start, int numbytes)

85. Write note on the class “SequenceInputStream”.
The SequenceInputStream class allows you to concatenate multiple InputStreams. A  SequenceInputStream constructor uses either a pair of InputStreams or an Enumeration of InputStreams as its argument:
                     SequenceInputStream(InputStream first, InputStream second)
                     SequenceInputStream(Enumeration streamEnum)
86. Write note on the class “PushbackReader”.

The PushbackReader class allows one or more characters to be returned to the input stream.This allows you to look ahead in the input stream. Its constructors are
                        PushbackReader(Reader inputstream)
                        PushbackReader(Reader inputstream, int bufsize)

87.What is an Event?

An event is an object that describes a state change in a source. It can be generated as a consequence of a person interacting with the elements in a graphical user interface. Some of the activities that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list and clicking the mouse.
88. What is an Event Listener?

A Listener is an object that is notified when an event occurs. Only the types of events, which are registered with an event listener will be received by that listener.

89.When does an ActionEvent generate?

An ActionEvent is generated when a button is pressed, a list-item is double-clicked, or a menu item is selected.
                   You can obtain the command name for the invoking ActionEvent object by using the getActionMethod() method.
                           String getActionCommand()
90.When is Component Event  generated?
                       A ComponentEvent is generated when the size, position, or visibility of a component is changed.
              The getComponent() method of ComponentEvent returns the component that generated the event.

91 Define Multithread Programming.

A multithreaded program contains two or more parts that can run concurrently. Each part of such program is called a thread, and each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking.

92   write note on the interface Serializable?

An object that implements the serializable interface can be saved and restored by the serialization facilities.  The Serializable interface defines no members. It is simply used to indicate that a class may be serialized.  If a class is serializable, all of its subclasses are also serializable.

93.    Write note on Trees in Swings.

A tree is a component that presents a hierarchical view of data.  A user has he ability to expand or collapse individual subtrees in this display.   Trees are implemented in Swing by the JTree class, which extends JComponent.  Some of its constructors are :

JTree (Hastable ht)
JTree (Object obj[])
JTree (TreeNode tn)
JTree (Vector v)

94. What is Bean Customizer?

A Bean Customizer is nothing but a wizard that can be used to provide values to a bean.  A Customizer can be created in the same way as any other Java program and can then be attached to the bean with the help of BeanInfo file.

95 How we can include tables in Swing applications?

Swing provides a structure called the JTable which is capable of displaying the data in a tabular format.  For creating a JTable you need to create an array that contains the column names and another array that contains the row and column contents.  The constructors to create a JTable are given below :

    JTable ( )
    JTable (int numRows, int numColumns)
    JTable (Object [] [] rowData, Object [] columnNames)
    JTable (TableModel dm)

96. Define the term persistence in a Bean.

Persistence is the ability to save a Bean to nonvolatile storage and retrieve it at a later time.  The information that is particularly important are the configuration settings. 

97 what is Introspection?

Introspection is the process of analyzing a Bean to determine its capabilities.  The java . beans . Introspector class, does all the pattern analysis to expose the properties, methods and events that a component has.

98 What do you meant by Bound Properties in a Bean?

A Bean that has a bound property generates an event when the property is changed.  The event is of type PropertyChangeEvent and is sent to objects that previously registered an interest in receiving such notifications.

99 List some Layout Managers supported by Swing.

The most common Layout Managers supported by Swing are

Box Layout
Grid Layout
GridBag Layout
Border Layout

100 What are JAR files?

A JAR file allows you to efficiently deploy a set of classes and their associated resources.  Elements in a JAR file are compressed, which makes downloading a JAR file much faster than separately downloading several uncompressed files.

101 Write note on Interface Definition Language?

IDL is part of a language neutral strategy provided by CORBA.  Every language has a mapping to and from IDL.  These IDL interfaces represent a method calling API that can be used to access your object from other languages, such as c++.

102 Write note on manifest file in Java Beans.

Manifest file is used to indicate which of the components in a JAR file are Java Beans.
    A manifest file may reference several . class file .  If a .class file is a Java Bean, its entry must be immediately followed by the line “Java Bean : True”.

103 What is the use of Layout Managers in Swing?

The Layout Managers are used to place the components in a predefined manner relative to each other.  The layout manager puts the components in a queue and arranges them one after the other rather then placing the components according to the coordinates.  This helps in achieving platform independence.

104 What is CORBA?

The CORBA is essentially a remote method invocation facility.  The ORB is language –neutral, meaning you can create objects in any language and use the ORB to invoke methods in those objects.

105 What is a Java Bean?

A Java Bean is a software component that has been designed to be reusable in a variety of different environments.  There is no restriction on the capacity of a Bean.

106 Write the design patterns for simple properties in Bean.

A simple property has a single value.  It can be identified by the following design patterns, where N is the name of the property and T is its type.

107 What do you meant by constrained properties in a Bean?

A Bean that has a constrained property generates an event when an attempt is made to change its value.  The event is of type PropertyChangeEvent.

108 What are the design patterns for Boolean properties in a Bean?

A Boolean property has a value of true or false.  It can be identified by the following design, patterns, where N is the name of the property ;

public boolean  is N( );
public boolean get N(); 
public void setN(boolean value);

109 What is distributed garbage collection?

Freeing up the memory space in the server is called Distributed garbage collection.

The java.rimi.dgc package defines the interfaces and classes to implement the distributed garbage collection algorithm.

110 List some advantages of Java Beans.

A Bean obtains all the benefits of Java’s “Write – Once, run-anywhere” paradigm.
The configuration settings of a Bean can be saved in persistent storage and restored at a later time.
A Bean may register to receive events from other objects and can generate events that are sent to other objects.

public T get N( );
public void set N(T arg); 

111 Write note on interfaces in IDL.

An IDL interface contains a set of method definitions, just like a Java interface.  Like Java interfaces, an IDL interface may inherit from other interfaces.

Sample IDL interface is
interface MyInterface    {

    void myMethod (in long param1);

112 What's the difference between J2SDK 1.5 and J2SDK 5.0?

There's no difference, Sun Microsystems just re-branded this version.

113 You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use:

ArrayList or LinkedList?


114 What's the difference between J2SDK 1.5 and J2SDK 5.0?

There's no difference, Sun Microsystems just re-branded this version.

115 What comes to mind when you hear about a young generation in Java?

Garbage collection. 

Also Read:
Advanced Java Interview Questions -1

Advanced Java Interview Questions -2

Advanced Java Interview Questions -3

Advanced Java Interview Questions -4

Advanced Java Interview Questions -5

Advanced Java Interview Questions -6

Advanced Java Interview Questions -7

Advanced Java Interview Questions -8

Advanced Java Interview Questions -9

Advanced Java Interview Questions -10

Advanced Java Interview Questions -11

Advanced Java Interview Questions -12

Advanced Java Interview Questions -13

Advanced Java Interview Questions -14        


Post a Comment