Friday, March 14, 2008

Java Interview Questions

Overview

These are some of the trickier 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()

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?

Answers

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.

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  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: Cloneable does guarantee a deep copy depending on the implementation in each object, 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 you change the reference of the final object?

simple: no.

intermediate: With reflections, yes. 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.

Coding questions.

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();
}
}

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

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 the old Thread as the Runnable for the new Thread.

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

Don't try this at home

0 comments: