Java Interview Questions

Overview

These are some IAQ (Infrequently Asked Questions) you probably shouldn't ask in an interview.

Accidentally advanced questions

These questions come from posted interview questions where the question is confused but might have an interesting answer.

How do you free memory in Java?

simple: You can't, the GC cleans up free objects.

intermediate: You can set known references to null and call System.gc() . This later doesn't guarantee a clean up, but Sun's JVM does actual do a GC each time this is called.

advanced: the sun.misc.Unsafe class allows you to allocate, reallocate and free a block of memory. This type of memory has to be explicitly freed with freeMemory()

What is an Object?

simple: An object is an entity which has fields and methods.

intermediate: In Java, an Object is an instance of Class. The Object records the values of fields, a reference to its Class, a reference counter for the incremental GC and a lock for basic locking support. e.g. synchronized, wait(), notify().

advanced: Fields of an Object can be accessed directly using the Unsafe class, knowing the offset of the field. This approach is about 2-3x faster than the builtin reflection but comes with less protection. i.e. misuse can case the JVM to die horribly.

What is a Class?

simple: A class is a collection of attributes and behaviours of objects with certain similarities and an instance of a class is represented by an object.

intermediate: In Java, a class defines fields and methods associated with instances of a class or static fields and methods associated with the class itself.

advanced: In Java, a class is associated with a ClassLoader. All classes are instances of the Class class. (Even Class itself) Each ClassLoader can have its own instance of a Class (even with the same name), in which case these classes are different (neither == or equals()) even if they have the same name and definition. A class can be created from byte-code by a ClassLoader

Can you instantiate the Math class.

simple: No. The constructor for Math is private and all its methods are static.

intermediate: Yes. You can create an instance of a Math class using reflections. However, you cannot instantiate an object which is the Math class using reflections. Note: Class has a private constructor but reflections won't allow you to construct a class this way.

advanced: You can create a class from byte-code by using reflection to call the defineClass method on the ClassLoader. Each ClassLoader can have only one class for a given name, but you can have any number of ClassLoaders . In this way you can instantiate multiple Math class objects.
However you shouldn't want to.

Is there a sizeof operator in Java?

simple: No, sizeof is not a keyword, nor is there a keyword replacement.

intermediate: You can estimate the size of an object by looking at the amount of memory used before and after an object is created. The GC can make this process a bit random but if you do this enough times you can work it out. (The median is usually right)

advanced: The Instrumentation.getSizeOf() will do this for you. It a bit tricky to setup because you have to have a premain (called before main)

Which class is the superclass of every class?

simple: Object

intermediate: The superclass of Object is null.

advanced: The super class of primitives, interfaces and void is null.

If all methods of a class are synchronized what are the ways you can have more than one thread in methods of a class.

simple: Objects are locked, not methods so different objects can be accessed by different threads. static methods synchronize on the class objects so even if you have one object you can have two threads in different methods.

intermediate: When wait() is called, the lock on an object is released. So while a threads are wait'ing another threads can be holding the lock.

advanced: the sun.misc.Unsafe class can be used to discretely release a lock with exitMonitor() and re-acquire it with enterMonitor(). However using two or more synchronized blocks would be clearer and safer. Another option would be to use a Lock which can be acquired and released without a block.

Can you change the reference of the final object?

simple: The reference cannot be changed, but the data in that object can be changed.

intermediate: A field or variable can be final, but the object cannot be described as final. For example, you can have a final field refer to an object and have a non-final field also refer to the same object.

However, some final constants have optimised such that they are no longer used directly so changing it won't do what you think it might.

advanced: You can change a final field using reflection. There are only limited occasions where this is useful. You should be very careful doing this (or don't do it at all) An alternative to reflection is the use the Unsafe class for setting fields (getting as well) However this is faster (about 2.5x) by bypassing some of the checks which prevent you from shooting yourself in the foot. Misuse can result in surprising exceptions much later in the code or even a dump of the JVM. e.g. Unsafe allows you to set a String field with an Integer or worse, an int value!

There are occasions when you can replace a final variable with a wrapper which implements the same interface or a sub class. This allows you to change the underlying behaviour and can be useful in unit tests as you can using this replaced implementation to check that not only appears to be functionally correct but achieves the outcome in the manner expected.

How can one prove that the array is not null and empty?

simple: array != null && array.length == 0

intermediate: Say you have a method where you want to be able to test int[] or Object[]

public static <ArrayType> boolean isEmpty(ArrayType array) {
   return array != null && Array.getLength(array) == 0;
}

Note: the use of the generic ArrayType is just syntactic sugar

Are methods in Java virtual?

simple: By default methods work in a similar way to C++ virtual methods and abstract methods work like C++ pure virtual methods.

intermediate: static methods can be hidden but not overridden. final methods cannot be overridden and only virtual if the override a super classes method or implement an interface.

advanced: By generating byte code, the implementation of a method can be determined/optimised at runtime. In this way you can have an interface with no implementations and still create an instance at runtime.

How do you take a deep copy of an Object.

simple: If it is Cloneable call clone().

intermediate: Object.clone() by convention calls for a deep copy of immutable objects (a deep , however you can Serialize and then deserialize the object to get a deep copy.

advanced: If the object is neither Cloneable nor Serializable, you can use reflections to extract each field, descending into object to copy the whole structure. Watch out for recursive references! Note: sun.misc.Unsafe.allocateInstance() creates an object without calling a constructor. (used by ObjectInputStream).

Can an inner class be defined inside a method?

simple: yes. It can be defined inside a method and it can access data of the enclosing methods or a formal parameter if it is final.

intermediate: An "inner" class, is a member class of another class. Classes defined in a method are called "method" classes. One thing which distinguished an "inner" classes from "nested" classes is that the former can reference member fields. However, a "method" class defined in a static method does not have this access. "Method" classes can be thought of as "anonymous" classes with a name.

advanced: You cannot defined a top level "inner" class in a method but you can defined an "inner" class inside a "method" class inside a method.

How is a Java object locked for exclusive use by a given thread?

simple: A Java object can be locked for an exclusive use of a thread by making it available via a 'synchronized' block or method.

intermediate: Using synchronized uses a lock on the object to ensure only one thread is active in a synchronized block for that object. Note 1) A thread can release the lock temporarily with a wait() on the object, 2) if there is code which accesses the object without a synchronized block, it is not prevented from doing so and can access the object concurrently.

List built in Java types giving their size in bytes and their wrappers

type size in bytes wrapper types
boolean 1 Boolean
byte 1 Byte
char 2 Character
short 2 Short
int 4 Integer
long 8 Long
float 4 Float
double 8 Double
void 0 Void
Object[] ~18 ArrayList

Coding questions.

What is a simple way to have a thread pool with a dynamic thread pool size AND a work queue?

In the standard Java 5 thread pools you can have either a Thread pool with a work queue e.g. Executors.newFixedThreadPool() or a dynamic thread pool but no queue. Executors.newCachedThreadPool()

Often what you really need is a pool with a modest pool size so you don't consume to many resources but can handle bursts of activity efficiently.

The solution is to extends the ScheduledThreadPoolExecutor with the following methods. getCorePoolSize() to calculate a desired thread pool size, based on the queues length for example. This can be used to increase the pool size by say the sqrt(getQueue().size()) and override the afterExecute method to reduce the pool size. I suggest taking a delaying average of the queue length and reducing the number of threads if you have more threads than this.

Additionally you can;

  • count the number of threads you have State.BLOCKED, WAITING or TIMED_WAITING and add this to the queue length for the above calculation.
  • consider the number of processors and scale the number of threads more freely on a machine with more processors. See ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors()
sample getCoreSize()
public int getCorePoolSize() {
    int count = getThreadsBlockingOrWaiting() + getQueue().size() + 1;
    int poolSize = getPoolSize();
    if (count * PROCESSORS >= poolSize * poolSize)
        increasePoolSize(++poolSize);
    return poolSize;
}

What is a simple thread safe way to lazily construct a singleton without using synchronized or locks.

Use an inner class to create the instance. The class isn't loaded until it is referenced and JVM guarantees the class will be loaded only once.

public class Singleton {
    static class SingletonHolder {
        static final Singleton SINGLETON = new Singleton();
    }

    private Singleton() {
        System.out.println("new Singleton()");
    }

    public static Singleton getSingleton() {
        return SingletonHolder.SINGLETON;
    }

    public static void main(String... args) {
        System.out.println("main() started.");
        getSingleton();
    }
}

What are three things you can define in an interface?

  1. public abstract methods.
  2. public static final constants.
  3. public nested enum, annotation, interfaces and classes.

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

Before a thread is started its state is State.NEW.
After a thread is started its state is either, State.RUNNABLE, BLOCKED, WAITING or TIMED_WAITING.
Finally its state is State.TERMINATED.

Can a public class MyClass be defined in a source file named YourClass.java?

MyClass cannot be a public top level class, but can be a nested or inner class of YourClass.

If an abstract class is public what modifier should its constructor have?

The best choice is likely to be protected. The constructor for an abstract class can only be called by a subclass or another constructor in the same class. i.e. using the this() notation.
Abstract classes can have public constructors but this is effectively the same as protected.

Can an application have more than one main method?

yes. A main method can also call any number of other main(String...) methods.

Can I have multiple main methods in the same class

Yes, but that have to have different signatures, This may be confusing, but legal.

Do I need to import java.lang package any time?

Generally not. The compiler implicitly adds an import for java.lang and any class in the current package if an explicit import is not given.
You only need to include a class in java.lang if you have imported a package which defines a class with the same name as a standard class.

import for a java.lang class
import javax.jms.*; // contains javax.jmx.IllegalStateException
import java.lang.IllegalStateException; // so the reference is not ambiguously.

The moral of the story is don't define a class or interface with the same name as a java.lang class.

The JVM requires all class references to be fully qualified and it doesn't include any package by default. (The compile does this for you)

Can I import same package/class twice? Will the JVM load the package twice at runtime?

Imports are used by the compiler to fully qualify the package for each class. The JVM has no idea what you imported. This information does not appear in the .class file.
The JVM loads classes as required, so there is no guarantee that imported classes will be loaded. E.g. an unused import will not be loaded.

Give a simplest way to find out the time a method takes for execution without using any profiling tool?

long start = System.nanoTime();
methodCall();
long time = System.nanoTime() - start;

Note: System.currentTimeMillis() has an accuracy of about 1/60 sec on Windows. System.nanoTime() is about 16,000x more accurate.

How does an exception permeate through the code?

All throwables permeate the same way. Checked Exceptions are a feature of the compiler, the JVM does not treat them any differently. When a throwable is thrown, there is catch block information attached to the method which notes which code should be executed if throwable or a sub-class is thrown.

If there is no matching catch block in the method, the calling method is checked and so on.

If the throwable is not caught, it is passed to the uncaughtException method of the ThreadGroup which passes the throwable (by default and if defined) to the UncaughtExceptionHandler of the Thread.

If no handler is definded, the default behaviour here is to print throwables to System.err, (except for ThreadDeath which is consumed silently)  Note: the main thread works this way too.

The program will only terminate if the last non-deamon thread dies (or System.exit() is called)

If I write return in a try { } block, will the finally block still execute?

If an exception is thrown or return is called, the finally block is still called. After the finally block, the original return value is returned or exception thrown, unless the finally block calls return or throws an exception.  The finally block is actually appended to each block exit point in your code, so having a large finally block and many return points can bloat your code.

Edge cases.

For which values of x is this true x == -x && x != 0

Byte.MIN_VALUE, Short.MIN_VALUE, Integer.MIN_VALUE, Long.MIN_VALUE. In these cases, the - operator causes an overflow which results in the same value.

When is this true; x + 0 != x

When x is a String, or Float.NaN or Double.NaN.

Why is (Integer) 0 == (Integer) 0 but (Integer) 128 != (Integer) 128.

In this case we are comparing object references, not values. The first case works because autoboxing is performed by the Integer.valueOf() method which caches small values, so the references are the same. However 128 is not cached so the references are different.

What will this do for(int i = Integer.MIN_VALUE; i <= Integer.MAX_VALUE; i++) /* something */ do?

Loop forever. i <= Integer.MAX_VALUE is always true.
The alternative is

int i = Integer.MIN_VALUE;
do {
/* something */
} while (i++ < Integer.MAX_VALUE);

Note: this takes less than 6 seconds on a fast PC.

Java Trivia

Are true, false and null keywords.

No, they are reserved words and literals not keywords.
http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.9

Are there any keywords which don't do anything?

const and goto are keywords but cannot be used.
http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.9

Why is the serialVersionUID generation feature more useful in Eclipse than other IDEs.

Eclipse uses IBM's JRE which has a number of differences with Sun's JRE. One important difference is IBM's JRE generates a serialVersionUID which is sometimes different to Sun's JRE. This means that serialized data exchanged between applications where one is Sun's JRE could fail to deserialise without serialVersionUID being explicitly defined.
This is less of an issue if all the system are running the same JRE, however with systems developed under Eclipse it is common to have a mixture of JREs.

Corrected answers

Here are what I believe are the correct answers to the following questions.

How could Java classes direct program messages to the system console, but error messages, say to a file?

http://java.sys-con.com/read/48839.htm

System.setErr(new PrintStream("error.log"));

There is no Stream class and setting System.setOut() will means program messages will go the file not the console.

If a class is located in a package, what do you need to change in the OS environment to be able to use it?

Nothing. The classpath is typically set on the command line with the -cp option.

How many ways can one write an infinite loop ?

http://interviewjava.blogspot.com/2007/04/can-you-change-reference-of-final.html

There is very large, but finite number of infinite loops. A method is limited to 64KB of byte code, so less than 256^65536 possible infinite loops.

The simplest ones are
for(;; );
while(true);
do { } while(true);

How a dead thread can be started?

simple:
There is no dead state for a thread.
For a terminated Thread, isAlive() = false, getState() == State.TERMINATED.

intermediate:
You can start a new thread with the same name using the same Runnable object, or uglier option is to reuse the old Thread as the Runnable for the new Thread.

Thread newThread = new Thread(oldThread, oldThread.getName());

Don't try this at home.

Further Reading.

http://norvig.com/java-iaq.html
http://www.roseindia.net/interviewquestions/
http://java.sun.com/docs/hotspot/HotSpotFAQ.html
http://interviewjava.blogspot.com/2007/06/master-list-of-core-java-questions.html

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.