Categories: Career Interviews

10 Java Interview Questions And Answers

Java to most non-tech folks is just a good cup of coffee. But if you are in the tech world, you know that it is also the most popular computer-programming language. Java developers are in high demand. If you want to enter that field, you’ll need to ace your interview. Here are ten Java interview questions and answers, from a variety of top sources, to help you through the gauntlet. Before you go in, of course, make sure you read up on Ploymint about how to deal with job interviews.

The blog Java67 is one of the best ones out there for tutorials and Java interview questions and answers. Here are two from this post:

Question: What does the following Java program print?

public class Test {
    public static void main(String[] args) {
        System.out.println(Math.min(Double.MIN_VALUE, 0.0d));
    }
}

Answer: The Double.MIN_VALUE is 2^(-1074), a double constant whose magnitude is the least among all double values. This program will print 0.0 because Double.MIN_VALUE is greater than 0.

Question: What does the expression 1.0 / 0.0 return? Will it throw Exception? Any compile time error?

Answer: This is another tricky question from double class. Though a Java developer knows about the double primitive type and double class, while doing floating-point arithmetic they don’t pay enough attention to Double.INFINITY, NaN, and -0.0 and other rules that govern the arithmetic calculations involving them. The simple answer to this question is that it will not throw ArithmeticException and return Double.INFINITY. Also, note that the comparison x == Double.NaN always evaluates to false, even if x itself is a NaN. To test if x is a NaN, one should use the method call Double.isNaN(x) to check if given number is NaN or not. If you know SQL, this is very close to NULL there.

Toptal is “an exclusive network of the top freelance software developers and designers in the world.” Here are two Java interview questions and answers they suggest:

Question: Describe and compare fail-fast and fail-safe iterators. Give examples.

Answer: The main distinction between fail-fast and fail-safe iterators is whether or not the collection can be modified while it is being iterated. Fail-safe iterators allow this; fail-fast iterators do not.

  • Fail-fast iterators operate directly on the collection itself. During iteration, fail-fast iterators fail as soon as they realize that the collection has been modified (i.e., upon realizing that a member has been added, modified, or removed) and will throw a ConcurrentModificationException Some examples include ArrayList, HashSet, and HashMap (most JDK1.4 collections are implemented to be fail-fast).
  • Fail-safe iterates operate on a cloned copy of the collection and therefore do not throw an exception if the collection is modified during iteration. Examples would include iterators returned by ConcurrentHashMap or CopyOnWriteArrayList.

Question: ArrayList, LinkedList, and Vector are all implementations of the List interface. Which of them is most efficient for adding and removing elements from the list? Explain your answer, including any other alternatives you may be aware of.

Answer: Of the three, LinkedList is generally going to give you the best performance. Here’s why:

ArrayList and Vector each use an array to store the elements of the list. As a result, when an element is inserted into (or removed from) the middle of the list, the elements that follow must all be shifted accordingly. Vector is synchronized, so if a thread-safe implementation is not needed, it is recommended to use ArrayList rather than Vector.

LinkedList, on the other hand, is implemented using a doubly linked list. As a result, an inserting or removing an element only requires updating the links that immediately precede and follow the element being inserted or removed.

However, it is worth noting that if performance is that critical, it’s better to just use an array and manage it yourself, or use one of the high performance 3rd party packages such as Trove or HPPC.

The great site Java Hungry gives us these common Java interview questions and answers:

Question: What is the difference between creating String as new() and literal?

Answer: When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.

String s = new String(“Test”);

This does not put the object in String pool, so we need to call on the String.intern() method which is used to put  them into String pool explicitly. It’s only when you create String object as String literal e.g. String s = “Test” Java automatically puts that into String pool.

Question: Can you access non-static variable in static context?

Answer: No, you cannot access static variable in non-static context in Java.

The ever-popular FromDev suggests these great additions to your list of Java interview questions and answers:

Question: What is an immutable object in Java? Can you change values of an immutable object?

Answer: A Java object is considered immutable when its state cannot change after it is created. Use of immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. java.lang.String and java.lang.Integer classes are the examples of immutable objects from the Java Development Kit. Immutable objects simplify your program due to following characteristics :

  • Immutable objects are simple to use test and construct.
  • Immutable objects are automatically thread-safe.
  • Immutable objects do not require a copy constructor.
  • Immutable objects do not require an implementation of clone.
  • Immutable objects allow hashCode to use lazy initialization, and to cache its return value.
  • Immutable objects do not need to be copied defensively when used as a field.
  • Immutable objects are good Map keys and Set elements (Since state of these objects must not change while stored in a collection).
  • Immutable objects have their class invariant established once upon construction, and it never needs to be checked again.
  • Immutable objects always have “failure atomicity” (a term used by Joshua Bloch) : if an immutable object throws an exception, it’s never left in an undesirable or indeterminate state.

Question: What is the difference between String, StringBuffer, and StringBuilder? When do you use them?

Answer: The main difference between the three most commonly used String classes as follows.

  • StringBuffer and StringBuilder objects are mutable whereas String class objects are immutable.
  • StringBuffer class implementation is synchronized while StringBuilder class is not synchronized.
  • Concatenation operator “+” is internally implemented by Java using either StringBuffer or StringBuilder.

Criteria to choose among String, StringBuffer and StringBuilder

  • If the Object value will not change in a scenario use String Class because a String object is immutable.
  • If the Object value can change and will only be modified from a single thread, use a StringBuilder because StringBuilder is unsynchronized(means faster).
  • If the Object value may change, and can be modified by multiple threads, use a StringBuffer because StringBuffer is thread safe(synchronized).

Javarevisited throws these two Java interview questions and answers our way:

Question: What is the difference between Hashtable and HashMap in Java?

Answer: The former is thread-safe and doesn’t allow null. The later is not thread-safe. The former is also slow because of whole locking of Map, while HashMap is fast because of no locking.

Question: What is the difference between ArrayList and LinkedList in Java?

Answer: The former is fast and backed by array, while the latter is backed by linked-list, queue. The former also supports index based access at O(1), while the latter provides search at cost of O(n) time.

Shawn Setaro

Share
Published by
Shawn Setaro

Recent Posts

Job Seekers Are Mixed About Recruiters Texting Them

A recent study by SoftwareAdvice says that job seekers have a mixed reaction when it comes to recruiters texting them.…

6 years ago

3 Sites for Finding Work at Home Jobs

More and more people want the flexibility to work from home. So it stands to reason that more remote job…

7 years ago

Keying in on Your Job Interview Selling Points

When you head into a job interview its important to come up with your key "selling points" says Career Coach…

8 years ago

Hiring A Contract Worker vs. Full Time Employee – Which Makes Sense?

Contract Worker vs. Full Time Employee: Things To Keep In Mind In just a few years, it's expected that four out…

8 years ago

The “Misadventures” of Zoe Balaconis

So what’s it like to found and manage your own online and print mag? Balaconis shares the deets: How did…

8 years ago

Five Essential Skills for a Career in Digital Marketing

Ah, digital marketing. It’s all the rage right now, especially for millennials. But I don’t mean that unkindly—we have the…

8 years ago