Incorrect Core Java Interview Answers

Overview

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.

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.

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

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

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
NEW
A thread that has not yet started is in this state.

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

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

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

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

TERMINATED
A thread that has exited is in this state.

Which is the base class for all classes?

java.lang.Object
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 guaranteed. 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 http://introcs.cs.princeton.edu/java/11precedence/ 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.

Links to this page

http://news.ycombinator.com/item?id=2789570

http://news.ycombinator.com/item?id=2793399

http://www.javacodegeeks.com/2011/07/incorrect-core-java-interview-answers.html

http://java.dzone.com/articles/incorrect-core-java-interview

http://www.dzone.com/links/15_incorrect_yet_popular_core_java_interview_answ.html?ref=ps

http://news.ycombinator.com/item?id=2789570

http://www.softwareservices.com/news/15833/incorrect-core-java-interview-answers/

http://www.dzone.com/links/rss/incorrect_core_java_interview_answers.html

Comments

  1. The uninstantiable placeholder java.lang.Void extends Object.

    ReplyDelete
  2. I've just added you to my idol list, that is currently made up of three top developers: Shamus young (see what he does at www.shamusyoung.com), Ben Alex (the creator of Spring security, formerly known as Acegi Security System) and Dark Alex (http://en.wikipedia.org/wiki/PlayStation_Portable_homebrew#Dark_AleX)

    ReplyDelete
  3. Howdy!

    I think it would be nice to add that the autoboxed Integer objects will be equal because of the 'integer pool' which size depends on the JVM's parameter like:
    -Djava.lang.Integer.IntegerCache.high

    http://www.javaspecialists.eu/archive/Issue191.html

    Cheers!
    Pedro

    ReplyDelete
  4. @dcbyron, You are right. Void.class is the "wrapper" for void.class. Void does extend Object but void does not.

    ReplyDelete
  5. @javier, cheers. I will have a look at the links. :)

    ReplyDelete
  6. @Pedro, Thank you for the suggestion. The reason I given a negative number as a false example is because this option doesn't change the number of negative values cached. There is another option for setting the cache size and I will include this.

    ReplyDelete
  7. under the hood of core java. keep it up

    ReplyDelete
  8. One point on method signatures:

    Signatures in Java include the method name. So if two methods have different signatures, they are different methods.(Sample is StringBuffer's append method's signature - java/lang/StringBuffer.append(Ljava/lang/String;)Ljava/lang/StringBuffer)
    Only parameters and their types make up for overloading(Obviously generic parameters impact the type of the actual parameter).

    ReplyDelete
  9. @JAlexoid, I has thought the same until resently. You can have two methods with the same name and no parameters which only differ by the generic (which is not used) and the return type.
    http://vanillajava.blogspot.com/2011/02/with-generics-return-type-is-part-of.html

    ReplyDelete
  10. 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.

    That post just shows how different the Eclipse JDT compiler really is...

    ReplyDelete

Post a Comment

Popular posts from this blog

Java is Very Fast, If You Don’t Create Many Objects

System wide unique nanosecond timestamps

Comparing Approaches to Durability in Low Latency Messaging Queues