Java Questions
Table of Contents

1. Java questions

2. More Java questions

validate(), invalidate() and revalidate()

It took me a while to figure out the difference between validate(), invalidate() and revalidate(). Here's my understanding of them so far. invalidate() marks a component and it's parent (and parent's parent) as dirty. It doesn't actually update the screen. revalidate() simply queues an invalidate() for a later time and get activated once all the events in the queue have been handled. Good thing about revalidate() is that you can call it multiple times and the invalidate() call placed in the queue causes any prior invalidate() in the queue to be removed so the component gets invalidated only once for a series of changes. validate() is really what updates everything and makes them valid. It is most often called for a container object which in turn validates all the contained components.

good interview questions

What is the difference between cloneable and serialization of an object?

weak reference, normal refereence, phantom reference.

What is the order of method invocation in an Applet ?

* public void init() : Initialization method called once by browser.
* public void start() : Method called after init() and contains code to start processing. If the user leaves the page and returns without killing the current browser session, the start () method is called without being preceded by init ().
* public void stop() : Stops all processing started by start (). Done if user moves off page.
* public void destroy() : Called if current browser session is being terminated. Frees all resources used by

Name the containers which uses Border Layout as their default layout?

Containers which uses Border Layout as their default are: window, Frame and Dialog classes.
Panel and Applet default use FlowLayout

abstract class vs interface

An interface is the same as an abstract class, but you cannot define any method implementations at all.

- Abstract classes allow having some method implementations. Method implementations cannot be defined when an interface is concerned.
- Interfaces are defined with the interface keyword. An interface doesn't need abstract and class keywords. Member variables are implicitly defined as public static final.
- An abstract class can have a constructor(s), but the constructor(s) must be implemented. An Interface must not have a constructor at all.

Inner class

excellent explaining:

  1. top-level class
  2. nested class

## nested top-level classes and interfaces
## inner class
### member classes (Non-static Inner Classes):
### local classes (within method/constructor)
### anonymous class

Top-level classes:
can only have public, abstract, and final modifiers, and it is also possible to not define any class modifiers at all. This is called default/package accessibility. Besides that, private, protected, and static modifiers cannot be used when declaring top-level classes.

member classes:
1) Member classes cannot have any static member unless it is a compile-time constant.
2) A member class can access all the fields and methods (even private) of an enclosing class.
3) A member class can be declared as public, protected, private, abstract, final.

local classes
1) can be defined in a static context (for example, in a static method) or not.
2) A local class can access all the fields and methods of the enclosing class but can only access final modifiers variables declared inside a method.
3)You cannot use public, protected, private, or static modifiers in a local class analogous to a local variable.

You can use the same modifiers for inner classes that you use for other members of the outer class. For example, you can use the access specifiers — private, public, and protected — to restrict access to inner classes, just as you do to other class members.

There are two additional types of inner classes. You can declare an inner class within the body of a method. Such a class is known as a local inner class. You can also declare an inner class within the body of a method without naming it. These classes are known as anonymous inner classes. You will encounter such classes in advanced Java programming.

A class defined within another class is called a nested class. Like other members of a class, a nested class can be declared static or not. A nonstatic nested class is called an inner class. An instance of an inner class can exist only within an instance of its enclosing class and has access to its enclosing class's members even if they are declared private.

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.

What is nested class?
If all the methods of a inner class is static then it is a nested class.

What is inner class?
If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class.

The following table shows the types of nested classes:

Types of Nested Classes Type Scope Inner
static nested class member no
inner [non-static] class member yes
local class local yes
anonymous class only the point where it is defined yes

context path, servlet path, and path info


  public class MultiHashMap {
   private Map map= new HashMap();
   public void put(Object key, Object value) {
      Set values= (Set)map.get(key);
      if (values == null)
         map.put(key, values= new HashSet());
   public Set get(Object key) {
      return map.get(key);

Anything that implements MAP interface can only have UNIQUE keys.

take a detail look here:

subclasses that implements MAP interface :
AbstractMap, Attributes, HashMap, Hashtable, IdentityHashMap, RenderingHints, TreeMap, WeakHashMap

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

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

In how many ways we can track the sessions?

Method 1) By URL rewriting

Method 2) Using Session object

Getting Session form HttpServletRequest object
HttpSession session = request.getSession(true);

Get a Value from the session

Adding values to session
cart = new Cart();
session.putValue(session.getId(), cart);

At the end of the session, we can inactivate the session by using the following command

Method 3) Using cookies

Method 4) Using hidden fields

Why we use enableEvents() method?

The enableEvents(long mask) method of java.awt.Component is used to enable processing of particular kinds of events by a Component. For example, a java.awt.Label component might not normally process
keyboard events, but with enableEvents() you can cause delivery of keyboard events to that component to occur.

Note that enableEvents() is a protected method, so it may only be called from code belonging to a subclass of the Component class. That is the typical use. For example, you might create a subclass of Label called "ActiveLabel", and use enableEvents() to cause mouse events to be delivered to it.

Can a GUI component handle its own events? If yes; then how?

Yes, any AWT or Swing GUI component can handle its own events. There are two basic ways override dispatchEvent(), or override some of the processXXXEvent methods. The latter approach is

Again, this kind of event processing is normally done only in Component subclasses.

singleton and Thread safe issue

what is the output

interface I
    void show(I i);
class A implements I
    int i=20;
    void show(I i)
public class SubClass extends A
    int i=30;
    public void show(A a)
public class Mytest
  public static void main(String args[])
    A a = new SubClass(); A());

What is the default value of the local variables?

The local variables are not initialized to any default value, neither primitives
nor object references

What will be the default values of all the elements of an array defined as an

instance variable?
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. e.g. All
the elements of an array of int will be initialized to 0, while that of boolean type will
be initialized to false. Whereas if the array is an array of references (of any type), all
the elements will be initialized to null.

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

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

What is the difference between yield() and sleep()?

When a object invokes yield() it returns to ready state. But when an object
invokes sleep() method enters to not ready state.

Thread contains ready, running, waiting and dead states

What are the main differences between Java and C++?

  • java is paltform independent;
  • There are no destructors in Java.(automatic garbage collection);
  • Java does not support conditional compile(#ifdef/#ifndef type).
  • Java does not support default arguments.
  • There’s no "goto " statement in Java.
  • Java doesn’t provide multiple inheritance (MI),
  • Thread support is built into java but not in C++.

What is the difference between a Vector and an Array. Discuss the advantages and disadvantages of both?

  • Vector can contain objects of different types whereas array can contain objects only of a single type.
  • Vector can expand at run-time, while array length is fixed.
  • Vector methods are synchronized while Array methods are not

what is java beans?

JavaBeans are usual Java classes which adhere to certain coding conventions:
• Implements interface
• Provides no argument constructor
• Provides getter and setter methods for accessing it’s properties

final variable

A final variable cannot be reassigned, but it is not constant. For instance,
final StringBuffer x = new StringBuffer()
is valid.X cannot have a new value in it, but nothing stops operations on the
object that it refers

What is the volatile modifier for?

The volatile modifier is used to identify variables whose values should not be optimized by the Java Virtual Machine, by caching the value for example. The volatile modifier is typically used for variables that may be accessed or modified by numerous independent threads and signifies that the value may change without

it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of
the program.

How could Java classes direct program messages to the system console, but

error messages, say to a file?
The class System has a variable out that represents the standard output, and
the variable err that represents the standard error device. By default, they both point
at the system console. This how the standard output could be re-directed:
Stream st = new Stream (new FileOutputStream ("techinterviews_com.txt"));

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.

What is the difference between set and list?

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

What is a stream and what are the types of Streams and classes of the

A Stream is an abstraction that either produces or consumes information.
There are two types of Streams and they are: Byte Streams: Provide a convenient
means for handling input and output of bytes. Character Streams: Provide a
convenient means for handling input & output of characters. Byte Stream classes are
defined by using two abstract classes, namely InputStream and OutputStream.
Character Stream classes are defined by using two abstract classes, namely Reader
and Writer.

What are the types of statements in JDBC?

Statement: to be used createStatement() method for executing single SQL
PreparedStatement: Use preparedStatement() method for executing same
SQL statement over and over
CallableStatement: Use prepareCall() method for multiple SQL statements
over and over.

What modifiers may be used with an interface declaration?

An interface may be declared as public or abstract.

What modifiers can be used with a local inner class?

A local inner class may be final or abstract.

Which non-Unicode letter characters may be used as the first character of

an identifier?
The non-Unicode letter characters $ and _ may appear 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.

++++What restrictions are placed on method overloading?
Two methods may not have the same name and argument list but different
return types.

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 array type reference.

an object cannot be cast to a primitive value.

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.

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.

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.

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.

What is the range of the short type?

The range of the short type is -(2^15) to 2^15 - 1. because one bit is used for sign

What happens to a static var that is defined within a method of a class ?

Can’t do it. You’ll get a compilation error

Describe what happens when an object is created in Java?

Several things happen in a particular order to ensure the object is constructed

Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implemenationspecific data includes pointers to class and method data.

The instance variables of the objects are initialized to their default values. The constructor for the most
derived class is invoked. The first thing a constructor does is call the consctructor for its superclasses. This process continues until the constrcutor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java.

Before the body of the constructor is executed, all instance variable initializers and initialization blocks
are executed. Then the body of the constructor is executed.

Thus, the constructor for the base class completes first and constructor for the most derived class completes

What is the difference between instanceof and isInstance?

I made my class Cloneable but I still get Can’t access protected method

clone. Why?
Some of the Java books imply that all you have to do in order to have your
class support clone() is implement the Cloneable interface. Not so. Perhaps that was
the intent at some point, but that’s not the way it works currently. As it stands, you
have to implement your own public clone() method, even if it doesn’t do anything
special and just calls super.clone().

The interface Cloneable declares no methods.

What is the fastest type of JDBC driver?

This means that Type 1 and Type 3
drivers will be slower than Type 2 drivers (the database calls are make at least three
translations versus two), and Type 4 drivers are the fastest (only one translation).

Does a class inherit the constructors of its superclass?

A class does not inherit constructors from any of its superclasses.

How will you invoke any external process in Java?


How will you load a specific locale?

Using ResourceBundle.getBundle(…);

What is the purpose of Void class?

The Void class is an uninstantiable placeholder class to hold a reference to the
Class object representing the primitive Java type void

What is the base class for Error and Exception?


What is the major difference between LinkedList and ArrayList?

LinkedList are meant for sequential accessing. ArrayList are meant for
random accessing.

What is a Marker Interface?

An interface with no methods. Example: Serializable, Remote, And Cloneable

What interface do you implement to do the sorting?


What is the algorithm used in Thread scheduling?

Fixed priority scheduling.

What is hash-collision in Hashtable and how it is handled in Java?

Two different keys with the same hash value. Two different entries will be
kept in a single hash bucket to avoid the collision.

Can a abstract method have the static qualifier?


What is the super class of Hashtable?


java char is 16 bits

char : 0~2^16-1,
int 32 bits,
long 64 bits

When are static and non static variables of the class initialized?

The static variables are initialized when the class is loaded. Non static variables are initialized just before the constructor is called

When are automatic variable initialized?

Automatic variable have to be initialized explicitly

What values of the bits are shifted in after the shift?

In case of signed left shift » the new bits are set to zero. But in case of
signed right shift it takes the value of most significant bit before the shift, that is if
the most significant bit before shift is 0 it will introduce 0, else if it is 1, it will
introduce 1

What are the rules for overriding?

Private method can be overridden by private, friendly, protected or public
Friendly method can be overridden by friendly, protected or public methods.
Protected method can be overridden by protected or public methods.
Public method can be overridden by public method

When you extend a class and override a method, can this new method throw

exceptions other than those that were declared by the original method?
No it cannot throw, except for the subclasses of those exceptions


Using the same method name with identical arguments and return type is know as overriding

If the method to be overridden has access type protected, can subclass have

the access type as private?
No, it must have access type as protected or public, since an overriding
method must not be less accessible than the method it overrides

What are the rules of anonymous class?

The class is instantiated and declared in the same place
The declaration and instantiation takes the form
new Xxxx () {// body} Where Xxxx is an interface name.
An anonymous class cannot have a constructor. Since you do not specify a
name for the class, you cannot use that name to specify a constructor

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

What is the range of priority integer?

It is from 1 to 10. 10 beings the highest priority and 1 being the lowest
The default priority is 5

What is Collection API?

The Collection API is a set of classes and interfaces that support operation on
collections of objects. These classes and interfaces are more flexible, more powerful,
and more regular than the vectors, arrays, and hashtables if effectively replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.

different types of collections:

  • A collection has no special order and does not reject duplicates
  • A list is ordered and does not reject duplicates
  • A set has no special order but rejects duplicates
  • A map supports searching on a key field, values of which must be unique

What is the difference between Hashtable and HashMap?

Hashtable does not store null value, while HashMap does. Hashtable is synchronized, while HashMap is not

What are the rules of serialization?

  • Static fileds are not serialized because they are not part of any one particular object
  • Fileds from the base class are handled only if hose are serializable
  • Transient fileds are not serialized

What is the difference between procedural and object oreinted language?

  • In procedural programming the instructions are executed one after another and the data is exposed to the whole program.
  • In OOPs programming the unit of program is an object which is nothing but combination of data and code and the data is not exposed outside the object

Where does java thread support reside?

It resides in three places
The java.lang.Thread class (Most of the support resides here)
The java.lang.Object class
The java language and virtual machine

What are different types of statements in JDBC?

  • java.sql.Statement: Top most interface which provides basic methods useful for executing SELECT, INSERT, UPDATE and DELETE SQL statements.
  • java.sql.PreparedStatement: An enhanced verion of java.sql.Statement which allows precompiled queries with parameters. It is more efficient to use java.sql.PreparedStatement if you have to specify parameters to your SQL queries. If you want to execute a Statement object many times, it will normally reduce execution time to use a PreparedStatement object instead.
  • java.sql.CallableStatement: Allows you to execute stored procedures

within a RDBMS which supports stored procedures (MySQL doesn't support stored
procedures at the moment).


Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery(”SELECT NAME, SALARY FROM EMPLOYEES”);

The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY,TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE.

The second argument is one of two ResultSet constants for specifying whether a result set is read-only or
updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE. Make sure that when you specify a type, you must also specify whether it is read-only or updatable.

Specifying the constant TYPE_FORWARD_ONLY creates a nonscrollable result set, that is, one in which the cursor moves only forward. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.


You will get a scrollable ResultSet object if you specify one of these ResultSet constants.The difference between the two has to do with whether a result set reflects changes that are made to it while it is open and whether certain methods can be called to detect these changes. Generally speaking, a result set that is
TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does.

What is an intern() method in the String class?

A pool of Strings is maintained by the String class. When the intern() method is invoked equals(…) method is invoked to
determine if the String already exist in the pool. If it does then the String from the pool is returned. Otherwise, this String
object is added to the pool and a reference to this object is returned. For any two Strings s1 & s2, s1.intern() ==
s2.intern() only if s1.equals(s2) is true.

What are the threads will start, when you start the java program?

Finalizer, Main, Reference Handler, Signal Dispatcher

java dynamic class loading

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License