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?
- 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.
- 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.
- Things Every Programmer Should Know
- 10 Tips for Proper Application Logging
- Laws of Software Design
- Java Best Practices Series
- 9 Tips on Surviving the Wild West Development Process
- How to Do 100K TPS at Less than 1ms Latency
- Revving Up Your Hibernate Engine
values up to 128 are cached, and the JVM gives you the same objects (hence the reference comparison works). Above 128 it creates a new instance.