Java interview questions and answers 👨‍💻

Copied to clipboard

Java is one of the most competitive programming languages among developers.

On the one hand, there’s a lucrative job market, with thousands of enterprise-level positions.

On the flip side, Java is a popular choice among programming learners, so the competition for top-tier spots is intense.

To help entry-level Java programmers ace interview questions, we wrote a lineup of the most common practice problems using the knowledge base at Codegym Java Course for answers.

1. What is the difference between LinkedList and ArrayList in Java?

When answering the question, it’s a good idea to highlight the similarities and differences between collection classes. This way, you’ll show a deeper understanding of when using one or the other is a good idea.

    • You can pass both using java.util.list since they implement the List interface.
    • Both collections are ordered – the first element will be assigned the first position.
    • ArrayList and LinkedList are the only implementations of List that allow duplicates.
    • Both are fail-fast collections – whenever the structure of the collection changes, the system returns a ConcurrentModificationException.
    • Backed by different data structures – LinkedList in the case of the LinkedList collection and Array for ArrayList.
    • ArrayList does not implement Deque, LinkedList does.
    • When you call remove(index), ArrayList makes a copy and performs a O(n) operation. On the other hand, a LinkedList will have to transverse to the deletion point O(n/2).
    • Memory: ArrayList stores data in Arrays, LinkedList uses nested classes (a wrapper object called entry) to store nodes.

  • There are four key differences between StringBuilder and StringBuffer: synchronization, thread-safety, availability, and speed.

Both StringBuilder and StringBuffer are used to edit Strings that are immutable by nature.

Here’s how these are handled by StringBuilder and StringBuffer.

  • StringBuilder:

    • Methods are not synchronized

     

    StringBuffer:

    • Methods are synchronized
  • StringBuilder:

    • Is not thread-safe so developers use it locally.

     

    StringBuffer:

    • Is thread-safe – programmers can share instances among several threads
  • StringBuilder:

    • Faster since it doesn’t require releasing and acquiring locks for synchronization

     

    StringBuffer:

    • Slower – lower execution speed is a side effect of method synchronization
  • StringBuilder:

    • Added to JDK 5

     

    StringBuffer:

    • Added to Java 1.0.

  • A runnable interface executes run() in background. It returns no value but, should Runnable fail, there might be system side effects. To queue asks, programmers need to run execute().

    Callable runs call() in the background and allows developers to return values by calling get(). To queue Callable tasks, use submit().

    Runnable was a part of JDK since 1.0 while Callable was introduced later, in Java 5.0.

  • By definition, a prime number is such that cannot be divided by numbers other than itself. 1 is not considered a prime number so, as you write a program, it makes sense to start validating the condition at 2.

    In algebra, a tool used to determine if the number is prime is trial division. It determines if a value is a multiple of other values in the range [2, n].

    There are several ways to answer the question:

1) Using a “while” loop:

import java.util.Scanner;

/** * Write a program that checks whether a number is prime. The code

* retrieves a number from a user-generated input and assesses if it’s prime

* using trial division./

public class TestPrime {

public static void main(String args[]) {

Scanner scnr = new

Scanner(System.in); int number = Integer.MAX_VALUE;

System.out.println(“Enter any number “);

while (number != 0) { number = scnr.nextInt(); System.out.printf(“Does %d is prime? %s %s %s %n”, number, isPrime(number), isPrimeOrNot(number), isPrimeNumber(number)); } }

2) Using a “for” loop:

/* * A Java method that confirms whether an integer is a prime number.
* @return true for prime numbers, else false
*/
public static boolean isPrime(int number)
{ int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 2; i < sqrt; i++) {
if (number % i == 0) { // number is divisible with no quotient – no prime return false;
}
}
return true; }

3) Using PrimeNumber():

/* * Second version of isPrimeNumber method, with improvement like not

* Checking numbers for division even if the number is not divisible by 2 using PrimeNumber().

*/

public static boolean isPrimeNumber(int number) {

if (num == 2 || num == 3) {

return true; }

if (num % 2 == 0) {

return false;

}

int sqrt = (int) Math.sqrt(num) + 1;

for (int i = 3; i < sqrt; i += 2) {

if (num % i == 0) {

return false; }

}

return true;

}

  • There are two ways to convert bytes into characters. You can either rely on default JDK methods or use third-party APIs. To that end, Google Guava and Apache Commons are both widely used in tech teams.

    Usually, APIs offer two approaches to byte conversion – character encoding and platform encoding. For the sake of best coding practices and avoiding excessive reliance on the default encoding, use the first one.

    Take a look at the real-world examples of:

    a. Converting a byte to a string using the String constructor (keep in mind that you need to specify the encoding system as one of the new String parameters.

    String str = new String(bytes, “UTF-8”)

    b. Converting a byte to a string using Apache Commons – helpful when reading byte arrays from HTML or XML:

    String fromStream = IOUtils.toString(fileInputStream, “UTF-8”)

    UTF-8 is the most common character encoding set used for conversion. It’s not the only one available – you can use UTF_16, UTF_16BE, UTF_16LE, ISO_8859_1, and US_ASCII.

  • When developers don’t want variables to be serialized, they apply transient. During deserialization, transient variables are initialized with their default values.

    On the other hand, the main application of volatile variables is avoiding reordering. They are typically used in concurrent programming (i.e. Singleton double-checked locking).

  • Association is a functional and applicational relationship between two Java objects.

    There are two forms of association – aggregation and composition. The key difference is that where two classes are in Composition if one owns others. Thus, if an owner is destroyed, other classes will be eliminated as well.

    Given an owner class Computer and other classes Local Drive, Trash, Document, if the owner is destroyed, there will be no way to access others.

    Association, on the other hand, keeps classes independent so one can exist even when the other doesn’t.

    To illustrate the example of association, suggest two classes House and Tenants. Even if a House is destroyed, Tenants can always “move” into a new one, so they will keep existing.

  • This is an introspective question that gives employees an understanding of what programming pet peeves you have, what you prioritize in code, and what “high quality” means to you.

    1. Assign descriptive thread names to facilitate debugging.
    2. To save time on resizing, state Collection sizes in advance.
    3. Don’t code on implementations – use interfaces instead.
    4. Assign dependencies to methods to prepare code for unit testing.
    5. Don’t overuse Checked Exception (if needed, convert into Runtime Exception).
  • The key difference between overloading and overriding methods is in the timing of resolution. Overloading is resolved at compile-time, while overriding resolves during method runtime.

    Method overloading and overriding behave differently when it comes to static methods – a static method can be overloaded but not overridden.

    To overload methods, developers use an overloading constructor. For overriding, you need to create and extend a child class.

  • It’s a practice problem that puts both a candidate’s logical reasoning and basic Java programming skills to the test. The easiest way to answer the question (writing a loop) is not applicable here since you don’t know the length of the list.

    That’s why programmers should look for an alternative solution using pointers. A way to go is to create two pointers (slow and fast). A slow pointer moves 1 step while a fast one moves two steps.

    This way, a slow pointer will be pointing to the middle and the fast one – to the end of the list.

Java Core interview questions test a developer’s skill to apply the syntax of the programming language to solving real-world problems. Also, most interviewers will ask trick or trivia questions where you’ll be expected to point out technical incongruencies.

What’s a good way to prepare for a job interview? Solve practice problems online and take another glance at fundamental books on Java theory. A fine line between theory and practice should fuel you for success.

Was this post useful?