Peter is a DZone MVB and is not an employee of DZone and has posted 161 posts at DZone. You can read more from them at their website. View Full User Profile

Incorrect Core Java Interview Answers

  • submit to reddit

On the internet, Java interview questions and answers get copied from one web site to another. This can mean that an incorrect or out of date answer might never be corrected. Here are some questions and answer which are not quite correct or are now out of date. i.e. are pre Java 5.0.

How many ways can an argument be passed to a subroutine and explain them?

An argument can be passed in two ways. They are passing by value and passing by reference. Passing by value: This method copies the value of an argument into the formal parameter of the subroutine. Passing by reference: In this method, a reference to an argument (not the value of the argument) is passed to the parameter.
Java only supports Pass-By-Value. You can pass a reference by value, but you cannot pass by reference in Java. Java references can be described as Call By Sharing but this is not commonly used.

What is Garbage Collection and how to call it explicitly?

When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection. System. gc() method may be used to call it explicitly.
An object is eligible for cleanup when it no longer has a strong reference from a Root context. An object which has a weak or soft reference can be cleaned up. An object without a strong reference might not be cleaned up (i.e. there is no guarentee a GC will be run and a minor GC will not clean up tenured objects)

System.gc() is a hint that a Full GC should be run. This can be disabled using a command line option.

What are Transient and Volatile Modifiers?

Transient: The transient modifier applies to variables only and it is not stored as part of its object’s Persistent state. Transient variables are not serialized. Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.
transient can only be applied to fields and cannot be applied to local variables. It can be applied to static variables but will be generally ignored. Transient fields are not serialized automatically, but can be serialized by custom serialization e.g. writeObject and readObject()

volatile can only be applied to fields and the tell the JIT rather than the compiler that every access must get a cache coherent copy of the field. (Notionally from "main" memory)

Explain the usage of the keyword transient?

This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).
This keyword means the field cannot be serialized automatically. It is not de-serialized automatically leaving the default value for the field. The default for Integer is null. The default for int is 0

What is method overloading and method overriding?

Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading. Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding.
Method overloading occurs when two methods have the same name but different signatures. The signature includes the parameter types and generic type. A single method can be called with different arguments and two overloaded methods can be called with the same arguments. i.e. its the signature not the arguments which matter.

Method overriding only occurs when a sub-class has the same signature as a method in a parent class.

What is the difference between Integer and int

a) Integer is a class defined in the java. lang package, whereas int is a primitive data type defined in the Java language itself. Java does not automatically convert from one to the other. b) Integer can be used as an argument for a method that requires an object, whereas int can be used for calculations.
An Integer is a reference to an object which wraps an int The key difference since autoboxing and unboxing was added is that an Integer can be null and the == operator compares references for Integer and the actual values for an int type.
Integer i1 = 1;
Integer i2 = 1;
// true as the same autoboxed Integer is used.
System.out.println(i1 == i2); 

Integer i3 = -200;
Integer i4 = -200;
// false as different autoboxed Integer objects are used.
System.out.println(i3 == i4);

Note: On the Sun/Oracle JVM the maximum value of integer cached defaults to 127, however it can be increased with the -XX:AutoBoxCacheMax= or -Djava.lang.Integer.IntegerCache.high= options. Thank you @Pedro Kowalski.

What are the different states of a thread ?

The different thread states are ready, running, waiting and dead.
Since Java 5.0, which should be most Java systems under development, the Thread.State class lists the threads possible states as
A thread that has not yet started is in this state.

A thread executing in the Java virtual machine is in this state.

A thread that is blocked waiting for a monitor lock is in this state.

A thread that is waiting indefinitely for another thread to perform a particular action is in this state.

A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.

A thread that has exited is in this state.

Which is the base class for all classes?

This is true for custom classes. For primitive types such as int.class, void.class and Object itself have no super class.
Class parent = boolean.class.getSuperclass(); // returns null

What is daemon thread?

Theards [sic] which are running on the background are called deamon threads. daemon thread is a thread which doesn't give any chance to run other threads once it enters into the run state it doesn't give any chance to run other threads.
A Daemon thread is any thread which will not prevent the JVM from shutting down. Any thread can be considered a "background" thread. Daemon threads are given the same priority as non-Daemon threads (based on their priority) When a daemon thread is running it doesn't prevent another thread from running any differently from a non-daemon thread running.

Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system.

The garbage collector is an example of a daemon thread. A daemon thread can have a high priority and it can run all the time.

What are the restrictions placed on the values of each case of a switch statement?

At compile time, each case values of switch statement must evaluate to a an int value
From Java 5.0, switching on an enum is supported and from Java 7, switching on a String is supported.

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.
IMHO: This answer is vague and could be talking about anything.

A Java Bean is a "Java Object that is serializable, has a nullary constructor, and allows access to properties using getter and setter methods."

Why would you use a synchronized block vs. synchronized method?

Synchronized blocks place locks for shorter periods than synchronized methods.
This can be true but is not guarenteed. Often synchronized blocks are used to hold a lock over multiple calls to an object with synchronized methods. IMHO the most common use for synchronized blocks is locking on another object other than this
Map<Key, Value> map = Collections.synchronizedMap(new LinkedHashMap<Key, Value>());
// perform multiple operations in a thread safe manner
synchronized(map) {
    Value value = map.get(key);
    if (value == null)
        map.put(key, value = new Value(key));
    return value;

Which one is faster in Java ?

for(int i = 100000; i > 0; i--) {}
for(int i = 1; i < 100001; i++) {}

Answer: Which ever is run second with be fastest. The server JVM can detect and eliminate loops which don't do anything. A method with either loop is compiled when the loop iterates about 10,000 times. (Based on -XX:CompileThreshold=10000) The first loop will take time to detect it doesn't do anything, however the second will have been compiled.

Which Java operator is right associative?

The = operator is right associative.
According to the list of right to left associative operators are. (A lot more than one)
  • ( ) cast
  • new Object
  • ? :
  • assignment   =   +=   -=  *=   /=   %=   &=   ^=   |= <<=   >>=   >>>=

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

The Java runtime system generates RuntimeException and Error exceptions.
IMHO: This an answer to a different question. This is an answer to; what are the super classes of runtime, unchecked exceptions?

The Java runtime can generate an Error, Exception or RuntimeException.



Published at DZone with permission of Peter Lawrey, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)


Keith Barret replied on Thu, 2011/07/21 - 4:16am

Nice "quiz". Had fun on reading :-) Thank you Peter!

Nicolas Bousquet replied on Thu, 2011/07/21 - 1:38pm

Synchronized blocks: This is not only synchronize of another lock than this. Synchronized block allow a finer grained locking. The general rule is that you shall lock as few line as possible, not only to improve performance but to minimize the risk of dead locks. Just synchronizing method is a somewhat limited way of trying to ensure thread safety and will not work most of the time.

Which one is faster in Java: This kind of question is really not interresting. It is dependant of lot of thing like the JVM version and current options, where the code is placed...


Chris Arthur replied on Thu, 2011/07/21 - 1:39pm

I can agree the issue about What is Garbage Collection to some degree although I find it more than a little nitpicky and would take issue in an interview. However, the meaning of the word explicit has nothing whatsoever to do with the result. It means, fully and clearly expressed or demonstrated; leaving nothing merely implied; unequivocal. Using System.gc() is exactly that and therefore is indeed the explicit way of calling the garbage collector. You cannot MAKE the garbage collection happen from inside the language, but you absolutely, positively CAN make an explicit call to that subsystem and tell it to run. It just doesn't have to listen. I've said it before and I guess I'll probably continue to say it, badly worded or misleading questions are the fault of the interviewer not the interviewed. Trick questions serve very little purpose except making the person asking feel smarter and more important than the person being asked. This is not the way to start a professional relationship. I'd like to close by apologizing, you just happened to reprint a question and the "incorrect" answer that is a person pet peeve of mine.

Denis Zhdanov replied on Fri, 2011/07/22 - 3:20am

Method overriding only occurs when a sub-class has the same signature as a method in a parent class.
This definition doesn't take into consideration covariant return types.

Sudheer Krishna replied on Fri, 2011/07/22 - 4:04am

Integer i3 = -200;07.Integer i4 = -200;08.// false as different autoboxed Integer objects are used.09.System.out.println(i3 == i4); Is this correct ? Did u mean new Integer (-200) . Else it wouldnt be false.

Michael Bischoff replied on Fri, 2011/07/22 - 4:30am

"volatile can only be applied to fields and the tell the JIT rather than the compiler that every access must get a cache coherent copy of the field."
And how is this suppose to work in VM's that don't have a JIT?

I think that all parts have to make sure they don't break the guaranty that volatile gives. And depending on how the optimization techniques are implemented volatile is taken into account then and there. I'm not sure even the insertion of memory barriers to ensure cache coherency is mandated to be at a specific place and that the JVM implementer has some leeway here.

I agree with Chris Arthur that follow up questions are key and if either prospect or interviewer are not hearing the question they expect should follow up on it.

Peter Lawrey replied on Sat, 2011/07/23 - 12:59pm in response to: Denis Zhdanov

It is worth clarifying that the return type is not part of the signature in Java.  At the JVM level it is and covariant return types are implemented with generated method.

Peter Lawrey replied on Sat, 2011/07/23 - 1:03pm in response to: Sudheer Krishna

i3 == i4 is false as new Integer(int) is called by Integer.valueOf(int) which does the autoboxing.

Lund Wolfe replied on Sat, 2011/07/23 - 3:50pm

The original questions and answers are good enough, though crude and incomplete , except for the daemon answer which is just wrong. More importantly, these are terrible Java developer interview questions. Except for the value vs reference, daemon thread, and syncronized block vs method questions, you won't get any useful information to distinguish good and bad candidates.

Asking bad questions is risky behavior, even if the good candidates give better answers, because the interviewee is judging you at the same time as you are judging them.

Tom Schindl replied on Mon, 2011/07/25 - 5:52am

Java Bean Definition: I think your definition is more the one of POJO whereas to me the really important difference of bean to a pojo is that a bean notifies about property changes

Sirikant Noori replied on Sun, 2012/01/15 - 10:03am

Well, as long as the compiler can uniquely identify the method, then I think that that behaviour is logical.
The generic part allows the compiler to identify the unique method to call and the return type difference allows no two methods to actually have identical signature.

Peter Lawrey replied on Tue, 2012/01/31 - 3:54am in response to: Sirikant Noori

There was a bug in Java 6 where you could create multiple methods with the same signature.

With generics, the return type is part of the method signature.

This was fixed in Java 7, some what to my disappointment. ;)

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.