Thursday, 14 July 2011

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.

Every provided question is followed by two sections. The first section in italics dictates the incomplete/wrong answer. The last section in plain format provides the complete/correct answer.

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?
  1. 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.
  2. 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);

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


Reference: Incorrect Core Java Interview Answers from our JCG partner Peter Lawrey at the Vanilla Java.


Related Articles:



14 comments:

  1. boolean.class.getClass().getSuperclass() will return java.lang.Object (as it should be)

    boolean.class.getSuperclass() returns s null

    ReplyDelete
  2. To be a little more precise, Java supports both call by value for primitive type values and call by sharing for class derived instances.

    ReplyDelete
  3. @iskorn, @Enrico Thank you for your suggestions. I have updated my blog.

    ReplyDelete
  4. It's interviews like this that make me hate Java. Go use assembly if you care about low-level stuff. Or at least, don't blame a developer for not knowing these nuances of a language. IMO, though it depends on what the job task is I suppose....

    ReplyDelete
  5. Yeah: if this level of details is important to employers, why don't they just state that all applicants must have Java certification?

    Then they won't have to waste everyone's valuable time asking and grading these questions...

    ReplyDelete
  6. @Martin, I don't know anyone who has Java certification. IMHO, Its commercial experience which is usually more valuable. ;)

    ReplyDelete
  7. @bootz15, I would rather someone admit they don't know the answer and look it up than believe the wrong answer to be right.

    If you want to go lower than Java, C/C++ might be a good next step. You can go pretty low level without leaving Java IMHO.

    ReplyDelete
  8. any self respecting Java developer should know correct answers to _all_ of these questions. Java is not voodo magic, it's a language based on specs and the better you know the specs, the better code you can write. Any monkey can write substandard code in PHP if all you want is to get the job done quickly.

    ReplyDelete
  9. Confession: Newbie here. OK, maybe I am dense, but the two sections of code in:

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

    Well they look the same to me. What am I missing? I figure one section would use int and the other Integer, but no, they both use Integer. What am I missing here?

    ReplyDelete
  10. If integer is the same as BigDecimal, 0 and 1, at least are already autoboxed and stored as static fields (and the same instance is always used), since they are quite common. The rest must be instanced adhoc and that's why they are different.

    ReplyDelete
  11. Sorry, but I have been writing Java apps professionally for over ten years, and developing software for longer than that, and knowing most of those details don't matter for most Java codebases.

    I don't need to know the constants that enumerate the state of threads, I look them up in the Javadocs if I need to mess with them, or I let the auto-completion of my editor find them for me. I have never messed with the garbage collector and probably never will - yet I see and hear a variation of that question about every other interview.

    I should know the difference between transient and volatile, but more importantly I should know when to use them and when not to use them.

    A job candidate can google the answers to questions like these and ace them in an interview and have never written a line of Java code in his/her life - and that would be okay; because I am more interested in how they would solve a problem in whatever language they chose. I would rather hire a developer who writes good C# code and knows nothing of Java than someone who can answer all the little language lawyer interview questions and writes crap code in any language - and believe me, I have seen a LOT of code that is just plain crap.

    Questions like those above will tell you little more than how well a person can google such questions and remember them in an interview setting. Show me the code and explain to me how it solves the intended problem. Tell me what the pros and cons are of the approach you took, and how you would do it differently if you could do it again.

    Such questions are used by those who can't interview applicants very well and need *something* to ask them because they have nothing else. For many interviewers this is nothing more than a rite of passage that they went through so they are subjecting candidates to that same rite. It serves no useful purpose.

    ReplyDelete
  12. @Developer Dude, What scares me more than someone just googling the answers, is some one memorizing incorrect answers.

    ReplyDelete
  13. Asking the right questions is more important than having the right answers to the wrong questions.

    ReplyDelete
  14. @Developer Dude, I totally agree with you, while it is nice to know the questions and these answers but these are absolutely not the most used features of the language. Nice questions I have seen these questions many times but I think I am still stupid. I never used a volatile or a transient variable. I have seen designs patterns are useful, they work for all languages. Language specific design patterns are even more useful but these questions appear to be small tricks and might get changed in future versions like strings got introduced in case statements , and lambdas will get introduced by closures...

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...