Java Interview Questions - 21

Java Interview Questions - 21

1.In System.out.println(),what is System,out and println,pls explain? 

System is a predefined final class,out is a PrintStream object acting as a field member and println is a built-in overloaded method in the out object.

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

A. Yes. Add a main() method to the applet.

3.Can you make an instance of an abstract class? 

For example - java.util.Calender is an abstract class with a method getInstance() which returns an instance of the Calender class.
No! You cannot make an instance of an abstract class. An abstract class has to be sub-classed. If you have an abstract class and you want to use a method which has been implemented, you may need to subclass that abstract class, instantiate your subclass and then call that method.

4.Parsers? DOM vs SAX parser  

Parsers are fundamental xml components, a bridge between XML documents and applications that process that XML. The parser is responsible for handling xml syntax, checking the contents of the document against constraints established in a DTD or Schema.
1. Tree of nodes
2. Memory: Occupies more memory, preffered for small XML documents
3. Slower at runtime
4. Stored as objects
5. Programmatically easy
6. Ease of navigation
1. Sequence of events
2. Doesn't use any memory preferred for large documents
3. Faster at runtime
4. Objects are to be created
5. Need to write code for creating objects
6. Backward navigation is not possible as it sequentially processes the document

5.Can you declare a class as private?  

Yes, we can declare a private class as an inner class. For example,
class MyPrivate {
private static class MyKey {
String key = "12345";
public static void main(String[] args) {
System.out.println(new MyKey().key);//prints 12345

6.What's the difference between constructors and other methods?

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.

7.What is the output of x > y? a:b = p*q when x=1,y=2,p=3,q=4?

When this kind of question has been asked, find the problems you think is necessary to ask back before you give an answer. Ask if variables a and b have been declared or initialized. If the answer is yes. You can say that the syntax is wrong. If the statement is rewritten as: x

8.What is the difference between shallow copy and deep copy? 

Shallow copy shares the same reference with the original object like cloning, whereas the deep copy get a duplicate instance of the original object. If the shallow copy has been changed, the original object will be reflected and vice versa.

9.Can one create a method which gets a String and modifies it?  

No. In Java, Strings are constant or immutable; their values cannot be changed after they are created, but they can be shared. Once you change a string, you actually create a new object. For example:
String s = "abc"; //create a new String object representing "abc"
s = s.toUpperCase(); //create another object representing "ABC"

10.Why is multiple inheritance not possible in Java?  

It depends on how you understand "inheritance". Java can only "extends" one super class, but can "implements" many interfaces; that doesn't mean the multiple inheritance is not possible. You may use interfaces to make inheritance work for you. Or you may need to work around. For example, if you cannot get a feature from a class because your class has a super class already, you may get that class's feature by declaring it as a member field or getting an instance of that class. So the answer is that multiple inheritance in Java is possible.

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

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.

12.Why Java does not support pointers?

Because pointers are unsafe. Java uses reference types to hide pointers and programmers feel easier to deal with reference types without pointers. This is why Java and C-sharp shine.

13.What is the relationship between synchronized and volatile keyword?

The JVM is guaranteed to treat reads and writes of data of 32 bits or less as atomic.(Some JVM might treat reads and writes of data of 64 bits or less as atomic in future) For long or double variable, programmers should take care in multi-threading environment. Either put these variables in a synchronized method or block, or declare them volatile.

14.This class (IncrementImpl) will be used by various threads concurrently; can you see the inherent flaw(s)? How would you improve it?

public class IncrementImpl {
private static int counter = 0;
public synchronized void increment() {
public int getCounter() {
return counter;

15.The counter is static variable which is shared by multiple instances of this class. The increment() method is synchronized, but the getCounter() should be synchronized too. Otherwise the Java run-time system will not guarantee the data integrity and the race conditions will occur. The famous producer/consumer example listed at Sun's thread tutorial site will tell more.
one of solutions
public class IncrementImpl {
private static int counter = 0;
public synchronized void increment() {
public synchronized int getCounter() {
return counter;

16.What are the drawbacks of inheritance?

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. In addition, the inheritance may make peers hardly understand your code if they don't know how your super-class acts and add learning curve to the process of development.
Usually, when you want to use a functionality of a class, you may use subclass to inherit such function or use an instance of this class in your class. Which is better, depends on your specification.
Is there any other way that you can achieve inheritance in Java?
There are a couple of ways. As you know, the straight way is to "extends" and/or "implements". The other way is to get an instance of the class to achieve the inheritance. That means to make the supposed-super-class be a field member. When you use an instance of the class, actually you get every function available from this class, but you may lose the dynamic features of OOP

17.Two methods have key words static synchronized and synchronized separately. What is the difference between them?

Both are synchronized methods. One is instance method, the other is class method. Method with static modifier is a class method. That means the method belongs to class itself and can be accessed directly with class name and is also called Singleton design. The method without static modifier is an instance method. That means the instance method belongs to its object. Every instance of the class gets its own copy of its instance method.
When synchronized is used with a static method, a lock for the entire class is obtained. When synchronized is used with a non-static method, a lock for the particular object (that means instance) of the class is obtained.
Since both methods are synchronized methods, you are not asked to explain what is a synchronized method. You are asked to tell the difference between instance and class method. Of course, your explanation to how synchronized keyword works doesn't hurt. And you may use this opportunity to show your knowledge scope.

18.How do you create a read-only collection?

The Collections class has six methods to help out here:
1. unmodifiableCollection(Collection c)
2. unmodifiableList(List list)
3. unmodifiableMap(Map m)
4. unmodifiableSet(Set s)
5. unmodifiableSortedMap(SortedMap m)
6. unmodifiableSortedSet(SortedSet s)
If you get an Iterator from one of these unmodifiable collections, when you call remove(), it will throw an UnsupportedOperationException.

19.Can a private method of a superclass be declared within a subclass?

Sure. A private field or method or inner class belongs to its declared class and hides from its subclasses. There is no way for private stuff to have a runtime overloading or overriding (polymorphism) features.

20.Why Java does not support multiple inheritance ?

This is a classic question. Yes or No depends on how you look at Java. If you focus on the syntax of "extends" and compare with C++, you may answer 'No' and give explanation to support you. Or you may answer 'Yes'. Recommend you to say 'Yes'.
Java DOES support multiple inheritance via interface implementation. Some people may not think in this way. Give explanation to support your point.

21.What is the difference between final, finally and finalize?

final - declares constant
finally - relates with exception handling
finalize - helps in garbage collection
If asked to give details, explain:
final field, final method, final class
try/finally, try/catch/finally
protected void finalize() in Object class

22.Which containers use a border Layout as their default layout?

The window, Frame and Dialog classes use a border layout as their default layout.

23.Why do threads block on I/O?

Threads block on I/O (that is enters the waiting state) so that other threads may execute while the I/O Operation is performed.

24.What is the output from System.out.println("Hello"+null);?


25.What is shallow copy or shallow clone in array cloning?

Cloning an array invloves creating a new array of the same size and type and copying all the old elements into the new array. But such copy is called shallow copy or shallow clone because any changes to the object would be reflected in both arrays.

26.What is weak reference in Java

A weak reference is one that does not prevent the referenced object from being garbage collected. You might use them to manage a HashMap to look up a cache of objects. A weak reference is a reference that does not keep the object it refers to alive. A weak reference is not counted as a reference in garbage collection. If the object is not referred to elsewhere as well, it will be garbage collected.

27.When is the ArrayStoreException thrown?

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.

28.How to check two arrays to see if contents have the same types and 

contain the same elements?

One of options is to use the equals() method of Arrays class.
Arrays.equals(a, b);
If the array types are different, a compile-time error will happen.

29.Can you call one constructor from another if a class has multiple constructors?

Yes. Use this() syntax.

30.What are the different types of inner classes?

There are four different types of inner classes in Java. They are: a)Static member classes , a static member class has access to all static methods of the parent, or top-level, class b) Member classes, the member class is instance specific and has access to any and all methods and members, even the parent's this reference c) Local classes, are declared within a block of code and are visible only within that block, just as any other method variable. d) Anonymous classes, is a local class that has no name

31.In which case would you choose a static inner class?

Interesting one, static inner classes can access the outer class's protected and private fields. This is both a positive and a negative point for us since we can, in essence, violate the encapsulation of the outer class by mucking up the outer class's protected and private fields. The only proper use of that capability is to write white-box tests of the class -- since we can induce cases that might be very hard to induce via normal black-box tests (which don't have access to the internal state of the object). Second advantage,if I can say, is that, we can this static concept to impose restriction on the inner class. Again as discussed in earlier point, an Inner class has access to all the public, private and protected members of the parent class. Suppose you want to restrict the access even to inner class, how would you go ahead? Making the inner class static enforces it to access only the public static members of the outer class( Since, protected and private members are not supposed to be static and that static members can access only other static members). If it has to access any non-static member, it has to create an instance of the outer class which leads to accessing only public members.

32.What kind of security tools are available in J2SE 5.0?

There are three tools that can be used to protect application working within the scope of security policies set at remote sites.
keytool -- used to manage keystores and certificates.
jarsigner -- used to generate and verify JAR signatures.
policytool -- used for managing policy files.
There are three tools that help obtain, list and manage Kerberos tickets.
kinit -- used to obtain Kerberos V5 tickets.
tklist -- used to list entries in credential cache and key tab.
ktab -- used to help manage entries in the key table.

33.Why do we need to use getSystemResource() and getSystemResources() method to load resources?

Because we want to look for resources strictly from the system classpath, These methods use the system ClassLoader to locate resources, which gives you stricter control of the resources used by the application.

34.What's new with the stop(), suspend() and resume() methods in JDK 1.2?

The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

35.Can a lock be acquired on a class?

Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.

36.How to make an array copy from System?

There is a method called arraycopy in the System class. You can do it:
System.arraycopy(sourceArray, srcOffset, destinationArray, destOffset, numOfElements2Copy);
When you use this method, the destinationArray will be filled with the elements of sourceArray at the length specified.

37.Can we use System.arraycopy() method to copy the same array?

Yes, you can. The source and destination arrays can be the same if you want to copy a subset of the array to another area within that array.

38.Is null a keyword?

The null value is not a keyword.
What is the preferred size of a component?
The preferred size of a component is the minimum component size that will allow the component to display normally.

39.What is the List interface?

The List interface provides support for ordered collections of objects.

40.How does Java handle integer overflows and underflows?

It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
What is the Vector class?
The Vector class provides the capability to implement a growable array of objects

41.What is synchronization and why is it important?

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.

42.The following statement prints true or false, why?

byte[] a = { 1, 2, 3 };,
byte[] b = (byte[]) a.clone();
System.out.println(a == b);
The false will be printed out. Because the two arrays have distinctive memory addresses. Starting in Java 1.2, we can use java.util.Arrays.equals(a, b) to compare whether two arrays have the same contents.

43.What method is used to specify a container's layout?

The setLayout() method is used to specify a container's layout.

44.Which containers use a FlowLayout as their default layout?

The Panel and Applet classes use the FlowLayout as their default layout.


The ArithmeticException is thrown when integer is divided by zero or taking the remainder of a number by zero. It is never thrown in floating-point operations.

46.What is a transient variable?

A transient variable is a variable that may not be serialized.

47.What's the difference between the methods sleep() and wait()

The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

48.What state does a thread enter when it terminates its processing?

When a thread terminates its processing, it enters the dead state.
What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on collections of objects.

49.Which characters may be used as the second character of an identifier, but not as the first
character of an identifier?
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.

50.What modifiers may be used with an inner class that is a member of an outer class?

A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

51.How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?

Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

52.What is the difference between yielding and sleeping?

When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.

53,Which java.util classes and interfaces support event handling?

The EventObject class and the EventListener interface support event processing.

54.What is an Iterator interface?

The Iterator interface is used to step through the elements of a Collection.

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

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

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


57.Does garbage collection guarantee that a program will not run out of memory?

Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.

58.What restrictions are placed on the location of a package statement within a source code file?

A package statement must appear as the first line in a source code file (excluding blank lines and comments).

59.Can an object's finalize() method be invoked while it is reachable?

An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize() method may be invoked by other objects.

60.Is sizeof a keyword?

The sizeof operator is not a keyword.

61.What are wrapper classes?

Wrapper classes are classes that allow primitive types to be accessed as objects.

62.What is the immediate superclass of the Applet class?


63.To what value is a variable of the String type automatically initialized?

The default value of a String type is null.

64.What is the catch or declare rule for method declarations?

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.

65.What is the difference between preemptive scheduling and time slicing?

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.
Name three Component subclasses that support painting.
The Canvas, Frame, Panel, and Applet classes support painting.

66.What value does readLine() return when it has reached the end of a file?

The readLine() method returns null when it has reached the end of a file.

67.What is the immediate superclass of the Dialog class?


68.What is clipping?

Clipping is the process of confining paint operations to a limited area or shape.

69.What is a native method?
A native method is a method that is implemented in a language other than Java.

70.Can a for statement loop indefinitely?
Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ;

71.What are order of precedence and associativity, and how are they used?
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

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

A thread is in the ready state after it has been created and started.

73.Can an anonymous class be declared as implementing an interface and extending a class?

An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

74.When a thread blocks on I/O, what state does it enter?

A thread enters the waiting state when it blocks on I/O.

75.In which package are most of the AWT events that support the event-delegation model defined?

Most of the AWT-related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package.

76.What is the immediate super class of Menu?


77.What is the purpose of finalization?

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

78.Which class is the immediate super class of the MenuComponent class.


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

After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.
What is the difference between the Boolean & operator and the && operator?
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.

80.Name three subclasses of the Component class.

Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or TextComponent

81.What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars.

82.Which Java operator is right associative?

The = operator is right associative.

83.What is the Locale class?

The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.

84.Can a double value be cast to a byte?

Yes, a double value can be cast to a byte.

85.What is the difference between a MenuItem and a CheckboxMenuItem?

The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked.

86.What is a task's priority and how is it used in scheduling?

A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.

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

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.

88.What must a class do to implement an interface?

It must provide all of the methods in the interface and identify the interface in its implements clause.

89.What method is invoked to cause an object to begin executing as a separate thread?

The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread.

90.What class is the top of the AWT event hierarchy?

The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy.

91.What is the range of the short type?

The range of the short type is -(2^15) to 2^15 - 1.

92.What is the range of the char type?

The range of the char type is 0 to 2^16 - 1.

93.Name two subclasses of the TextComponent class.

TextField and TextArea

94.What is the advantage of the event-delegation model over the earlier event-inheritance model?

The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component's design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model.

95.Which containers may have a MenuBar?


96.How are commas used in the initialization and iteration parts of a for statement?

Commas are used to separate multiple statements within the initialization and iteration parts of a for statement.

97.Which Container method is used to cause a container to be laid out and redisplayed?


98.What is the purpose of the Runtime class?

The purpose of the Runtime class is to provide access to the Java runtime system.

99.How many times may an object's finalize() method be invoked by the garbage collector?

An object's finalize() method may only be invoked once by the garbage collector.

100.What is the purpose of the finally clause of a try-catch-finally statement? garbage collector?

The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.

101.What is the argument type of a program's main() method?

A program's main() method takes an argument of the String[] type.

102.What is the difference between a static and a non-static inner class?

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.

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

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.

104.What classes of exceptions may be caught by a catch clause?

A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.

105.How are the elements of a BorderLayout organized?

The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container.

106.What is the difference between the String and StringBuffer classes?

String objects are constants. StringBuffer objects are not.

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

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

108.If a class is declared without any access modifiers, where may the class be accessed?

A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.

109.What is the % operator?

It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.

110.When can an object reference be cast to an interface reference?

An object reference be cast to an interface reference when the object implements the referenced interface.

111.What are the high-level thread states?
The high-level thread states are ready, running, waiting, and dead.

112.How are Java source code files named?
A Java source code file takes the name of a public class or interface that is defined within the file. A source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is defined within a source code file, then the file must take on a name that is different than its classes and interfaces. Source code files use the .java extension.

113.What is the relationship between the Canvas class and the Graphics class?
A Canvas object provides access to a Graphics object via its paint() method.

114.What value does read() return when it has reached the end of a file?
The read() method returns -1 when it has reached the end of a file.

115.Can a Byte object be cast to a double value?
No, an object cannot be cast to a primitive value.

116.Which class is extended by all other classes?
The Object class is extended by all other classes.

117.What is the difference between a Window and a Frame?
The Frame class extends Window to define a main application window that can have a menu bar.

118.What is the Dictionary class?
The Dictionary class provides the capability to store key-value pairs.

119.What is the purpose of the wait(), notify(), and notifyAll() methods?
The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods.

120.What is an abstract method?
An abstract method is a method whose implementation is deferred to a subclass.

121.What is the difference between the Font and FontMetrics classes?
The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.

122.How is rounding performed under integer division?
The fractional part of the result is truncated. This is known as rounding toward zero.

123.Can an object be garbage collected while it is still reachable?
A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected..

124.What is the Map interface?
The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.

125.Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its super classes.

126.What happens when a thread cannot acquire a lock on an object?
If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.

127.Is the ternary operator written x : y ? z or x ? y : z ?

It is written x ? y : z.

128.What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar.

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

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

Also Read:


Post a Comment