Java Interview Questions


Here is a list of Java coding exercises that will help prepare you for your next job interview.

#1

What is the output of the following program?

public class MyInteger {
    public static void main(String args[]) {
        int i = 0;
        i = i++ + i;
        System.out.println(“I = ” + i);
    }
}

A. I = 0
B. I = 1
C. I = 2
D. I = null
E. Compilation Error

Answer

B

On line 4, i++ represents a post increment. This means that the variable will increase by 1 after line 4 executes. Therefore, it can be read as
i = 0 + 0 -> i = 0
after the line executes, the following will occur
i = 0 + 1 -> i = 1

#2

What is the output of the following program?

public class MyClass {
    static int i = 1;
    public static void main(String args[]) {
        System.out.println(i + ”, “);
        myMethod(i);
        System.out.println(i);
    }
    public void myMethod(int i) {
        i += 2;
    }
}

A. 1, 3
B. 3, 1
C. 1, 1
D. NullPointerException
E. None of the above

Answer

E

Java does not permit referencing a non-static method (myMethod in this case) to be referenced from a static context (main method). This code will not compile as is. In order to make it compile, we need to have myMethod on line 8 be a static method by adding the static keyword as in

public static void myMethod(){…}

Upon compilation and execution the output will be:
1, 
1

#3

What is the output of the following program?

public static void main(String args[]) {
    String s1 = "Hello";
    String s2 = "Hello";
    StringBuilder sb1 = new StringBuilder();
    sb1.append("He").append("llo");
    System.out.println(s1.equals(s2));
    System.out.println(sb1.toString() == s1);
}

A.
true
true
B.
false
true
C.
true
false
D. Compilation error
E. None of the above

Answer

C

The equals() method is used to check whether two String objects contains exactly the same characters in the same order.
The “==” operator checks to see if two objects refer to the same object in memory.

The Java Virtual Machine (JVM) uses what is called a string pool for memory management purposes. This location in the JVM stores any common string literals.

When a literal String object is created on line 2, it goes in the string pool. When an identical literal String object is created on line 3, Java does not create a new object but instead points s2 to the same object already in the string pool. Therefore, both s1 and s2 point to the same object AND their content is equal resulting in the first print statement printing true.

The second print statement prints false because sb1.toString() outputs a string but it is not a literal, meaning that it does not get added to the string pool. Hence, the comparison is not between two identical objects.

#4

What is the output of the following program?

public class MyClass {    
    public static void addToInt(int x, int amountToAdd) {
        x = x + amountToAdd;
    }

    public static void main(String args[]) {
        int a = 7;
        int b = 3;
        MyClass.addToInt(a, b);
        System.out.println(a); 
    } 
}

A. 3
B. 7
C. 10
D. Compilation error on line 3
E. Compilation error on line 9
F. None of the above

Answer

B

This code compiles, so options D & E are invalid. More importantly, this example is referred to as “passing by value” in Java, by which only a copy of variable a is passed into parameter x. Therefore, variable a cannot be changed by the method addToInt(), irrespective of what this method does.

#5

Which of the following are true statements of the following code? (Choose all that apply)

import java.util.*;
public class Flamingo {
    public Flamingo(String s) {
        name = s;
    }
    public static void main(String[] args) {
        Flamingo one = new Flamingo("f1");
        Flamingo two = new Flamingo("f2");
        one = two;
        two = null;
        one = null;
    }
    private String name;
}

A. Immediately after line 9, no flamingo objects are eligible for garbage collection;
B. Immediately after line 10, no flamingo objects are eligible for garbage collection;
C. Immediately after line 9, only one flamingo object is eligible for garbage collection;
D. Immediately after line 10, only one flamingo object is eligible for garbage collection;
E. Immediately after line 11, only one flamingo object is eligible for garbage collection;
F. The code compiles
G. The code does not compile

Answer

C,D,F

Immediately after line 9, only Flamingo f1 is eligible for garbage collection since both one and two point to Flamingo f2.
Immediately after line 10, Flamingo f1 is still the only object eligible for garbage collection. Given that reference two is null but reference one is not.
Immediately after line 11, both Flamingo objects are eligible for garbage collection given that both reference one and two point to null.
This code does compile and although it is common practice to declare instance variables at the start of a class, this is not a requirement.

What is garbage collection?
Garbage collection is a process by which Java automatically frees up memory resources on the head. It does this by deleting objects that can no longer be reached in a program.

#6

What is the result of the following program?

public class Ladybug {
    private String color;
    public Ladybug(){
        this("red");
    }
    public Ladybug(String color) {
        color = color;
    }
    public static void main(String[] args) {
        Ladybug myLady = new Ladybug();
        System.out.println("Color: " + myLady.color);
    }
}

A. Color:
B. Color: null
C. Color: red
D. Compilation error on line 4
E. Compilation error on line 10
F. Compilation error on line 11

Answer

B

Line 10 calls the constructor on line 3, which then calls the constructor on line 6. However, that constructor assigns the method parameter to itself, which leaves the color instance variable on line 2 set to its default value of null.

If we were to change line 7 to read
this.color = color;
then the output would be
Color: red

#7

What is the output of the following program?

public class CarOrAirplane {
    public static void main(String[] args) {
        int probability = 10;
        if((probability > 10 ? probability++: --probability)<10) {
            System.out.print("Car");
        } if(probability < 10) System.out.print("Airplane");
    }
}

A. Car
B. Airplane
C. CarAirplane
D. Compilation error on line 4
E. Compilation error on line 6
F. The code compiles but produces no output

Answer

C

This code compiles, so options D & E are invalid. Keep in mind that only one of the right-hand ternary expressions will be evaluated at runtime. Since probability is not greater than 10, the second expression, – –probability, will be evaluated, and since the pre-decrement operator was used, the the value returned is 9, which is less than 10. This means that the first if-then statement will be visited and Car will be output. Since probability is still less than 10, the second if-then statement will also be reached and Airplane will be output.

#8

Assuming that we have a valid, non-null ChickenCoop object whose value is initialized by the blank line shown on line 5, which of the following are possible outputs of this application? (Choose all that apply)

class Chicken {}
interface ChickenCoop { public java.util.Lisk<Chicken> getChickens(); }
public class ChickenSound {
    public static void main(String[] args) {
        ChickenCoop coop = __________
        Chicken chicken = coop.getChickens().get(0);
        for(int i=0; i<coop.getChickens().size();
          chicken = coop.getChickens().get(i++)) {
          System.out.println("Cluck!");
        }
    }
} 

A. The code will not compile due to line 6.
B. The code will not compile due to lines 7-8.
C. The application will compile but will produce no output.
D. The application will output Cluck! exactly once.
E. The application will output Cluck! more than once.
F. The application will compile but produce an exception at runtime.

Answer

D, E, F

The code compiles, so options A & B are incorrect. If coop.getChickens() returns an array of only one element, Cluck! will be printed once, so option D is correct. On the other hand, if coop.getChickens() returns an array of multiple elements, Cluck! will be printed once for each element in the array, so option E is also correct. Lastly, if coop.getChickens() returns an array of zero elements, then an IndexOutOfBoundsException will be thrown on the call to coop.getChickens().get(0); therefore, option C is not possible and option F is correct. An exception will also be thrown if the array returned by coop.getChickens() is null, so option F is possible under multiple conditions.

#9

Which of the following lines can be inserted at line 22 to print true? (Choose all that apply)

public static void main(String[] args) {
    // INSERT CODE HERE
}
private static boolean test(Predicate<Integer> k) {
    return k.test(7);
}

A. System.out.println(test(i -> i == 7));
B. System.out.println(test(i -> {i == 7;}));
C. System.out.println(test((i) -> i == 7));
D. System.out.println(test((int i) -> i == 7));
E. System.out.println(test((int i) -> {return i == 7;}));
F. System.out.println(test((i) -> {return i == 5;}));

Answer

A,C,F

Given that lambda expressions with one parameter can omit the parentheses around the parameter list, this makes options A & C correct. Also, the return statement is optional when a single statement is in the body, which makes option F correct. Option B is incorrect because a return statement is required whenever braces are included around the function’s body. Options D & E are incorrect due to the fact that the type is Integer in the predicate and int in the lambda function. Autoboxing works for collections but not to infer predicates. These two options would be correct if they were both changed to Integer.

Note:  In Java, Predicate<T> is a generic functional interface that represents a single argument function that returns a boolean value.

#10

Which of the following is not a Java primitive type? (Choose all that apply)

A. Integer
B. float
C. Boolean
D. Double
E. String
F. char

Answer

A,C,D,E

Java has eight built-in data types, which are referred to as the Java primitive types. Each primitive type has a corresponding wrapper class. These wrapper classes are used by the Java compiler for autoboxing and unboxing purposes. The following table lists each primitive type along with its corresponding wrapper class.

Primitive TypeWrapper Class
boolean Boolean
byte Byte
char Character
float Float
int Integer
long Long
short Short
double Double

This means that options B & F are primitive types and are therefore incorrect. Option E is not a primitive type nor a wrapper class, so it is correct. Options A, C and D are also correct since they are wrapper classes.

#11

Which one of the following contains an invalid Java identifier? (Choose all that apply)

A. int that = 99;
B. int this = 99;
C. int $other = 99;
D. int &high = 99;
E. int _highest = 100;

Answer

B,D

An identifier in Java is a name given to things such as packages, classes, interfaces, methods, or variables. Below are the rules for identifiers.

  • The name must begin with a letter or the symbol $ or _.
  • Subsequent characters may also be numbers.
  • An identifier’s name may not be the same as a Java reserved word.

Since this is a Java reserved word, option B is correct. Option D is also correct given that ‘&‘ is not one of the allowed symbols.

#12

Which one of the following is a Java reserved word? (Choose all that apply)

A. class
B. volatile
C. static
D. goto
E. implements
F. All of the above

Answer

F

All of those listed are reserved words in Java. Click here to see the complete list and learn about each of them.

#13

Which of the following are true statements? (Choose all that apply)

short atomicNum = 34;
int atomicMass = 78.97;
String element = "Selenium";
atomicNum.length();
atomicMass.length();
element.length();

A. Line 4 generates a compiler error.
B. Line 5 generates a compiler error.
C. Line 6 generates a compiler error.
D. Line 7 generates a compiler error.
E. Line 8 generates a compiler error.
F. Line 9 generates a compiler error.
G. The code compiles without error.

Answer

B, D, E

In Java, a literal is a number, text, or anything that represents a value. Moreover, Java has five types of literals that are listed below.

  • Integral Literal
  • Floating-Point Literal
  • Char Literal
  • String Literal
  • Boolean Literal

Option A (line 4) compiles because short is an integral type. Option B (line 5) generates a compiler error because int is an integral type, but 78.97 is a floating-point type. Option C (line 6) compiles because it is assigned a String. Options D & E (lines 7 & 8) do not compile because short and int are primitives (see question #10). Primitives do not allow methods to be called on them. Option F (line 9) compiles because length() is defined on String.

#14

What is the output of the following program?

public class MilkCarton {
    private String brand;
    private boolean empty;
    
    public static void main(String[] args) {
        MilkCarton mc= new MilkCarton ();
        System.out.print("Empty = " + mc.empty);
        System.out.print(", Brand = " + mc.brand);
    }
}

A. Compilation error on line 7
B. Compilation error on line 8
C. No output
D. Empty = false, Brand = null
E. Empty = false, Brand =
F. Empty = true, Brand = null

Answer

D

In Java, boolean fields initialize to false while references initialize to null.

#15

Which of the following can be used to fill in the blank to be able to run the main() method from the command line? (Choose all that apply)

public static void main(_______)

A. String[] _values
B. String[] 555
C. String sam[]
D. String _Values[]
E. String… $v
F. String values
G. None of the above

Answer

A, C, D, E

Option A is correct because it is the traditional main() method signature and variables may begin with an underscore. Options C & D are correct because the array operator may appear after the variable name. Option E is correct because varargs are allowed in place of an array. Option B is correct because variables are not allowed to begin with a digit. Option F is incorrect because the argument must be an array or varargs. Option F is a perfectly good method. However, it is not one that can be run from the command line because it has the wrong parameter type.

#16

Given the following class, which of the following lines of code can replace ENTER CODE HERE to make the code compile? (Choose all that apply)

public class Distance {
    public void speed() {
        ENTER CODE HERE
        System.out.println(rate);
    }
}

A. int rate = 35L;
B. int rate = 0b110;
C. int rate = 0xF
D. double rate = 0xF;
E. double rate = 9_5_.5_0;
F. int rate = 9_5_;
G. None of the above

Answer

B, C, D

B is correct since 0b is the prefix for a binary value. C and D are correct since 0x is the prefix for a hexadecimal value; this value can be assigned to many primitive types, including int and double. A is incorrect because 35L is a long value (long rate = 35L would be allowed. E is incorrect because the underscore is immediately before the decimal. F is incorrect because the underscore is the very last character.

#17

Which option represents the order in which the following statements can be assembled into a program that will compile successfully? (Choose all that apply)

A: class Student {}
B: import java.util.*;
C: package school;

A. A, B, C
B. B, C, A
C. C, B, A
D. B, A
E. C, A
F. A, C
G. A, B

Answer

C, D, E

In Java, package and import are both optional. If both are present, the order must be package, then import, then class. Option A is incorrect because class is before package and import. Option B is incorrect because import is before package. Option F is incorrect because class is before package. Option G is incorrect because class is before import.

#18

What is the output of the following program?

public class Selenium {
    int version;
    public void Selenium() {
        version = 4;
    }

    public static void main(String[] args) {
        Selenium s = new Selenium();
        System.out.println(s.version);
    }
}

A. 0
B. 4
C. Compilation error on line 3
D. Compilation error on line 4
E. Compilation error on line 8
F. Compilation error on line 9

Answer

A

The code on line 3 compiles, however it is not a constructor because it has a return type (constructors do not have a return type). This is just a method that happens to have the same same as the class. When this code runs, the default constructor is called and count assumes the default value for an int (0).

#19

Which of the following are true statements? (Choose all that apply)

A. Java allows operator overloading.
B. Java code compiled on Windows can run on Linux.
C. Java has pointers to specific locations in memory.
D. Java is a procedural language.
E. Java is an object-oriented language.
F. Java is a functional programming language.
Answer

B, E

While C++ has both operator overloading and pointers, Java made a point of not having either. Java does have references to objects, but these are pointing to an object that is free to move around in memory. Option B is correct because Java is platform independent. Option E is correct because Java is an object oriented language. While it does support some parts of functional programming, these occur within a class, so it is not considered a functional programming language.

Leave a Reply