Are you wondering how to prepare for an upcoming Java interview? Here is a list of typical Java interview questions that will help prepare you for that.
You will love our QA and Selenium interview questions if you enjoy this content.
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
B
On line 4, i++ represents a post increment. This means that the variable i 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
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
E
Java does not permit referencing a non-static method (myMethod in this case) from a static context (main method). This code will not compile as is. 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
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
C
The equals() method checks whether two String objects contain the same characters in the same order.
The “==” operator checks to see if two objects in memory refer to the same object.
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 literal.
When a literal String object is created on line 2, it goes into 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.
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
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.
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
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 a program can no longer reach.
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
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, leaving the color instance variable on line 2 set to its default null value.
If we were to change line 7 to read
this.color = color;
then the output would be
Color: red
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
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 value returned is 9, which is less than 10. That 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.
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.
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. Also, an exception will get thrown if the array returned by coop.getChickens() is null, so option F is possible under multiple conditions.
Which of the following lines can be inserted at line 2 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;}));
A,C,F
Given that lambda expressions with one parameter can omit the parentheses around the parameter list, options A & C are correct. Also, the return statement is optional when a single line of code is in the body, making option F right. Option B is incorrect because there must be a return statement whenever the function’s body has braces. Options D & E are wrong since the type is Integer in the predicate and int in the lambda function. These two options would be correct if they were both changed to Integer. Autoboxing works for collections but not to infer predicates.
Note: In Java, Predicate<T> is a generic functional interface representing a single argument function that returns a boolean value.
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
A,C,D,E
Java has eight built-in data types, referred to as the Java primitive types, each having a corresponding wrapper class used by the Java compiler for autoboxing and unboxing purposes. The following table lists each primitive type along with its corresponding wrapper class.
Primitive Type | Wrapper Class |
boolean | Boolean |
byte | Byte |
char | Character |
float | Float |
int | Integer |
long | Long |
short | Short |
double | Double |
That means that 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.
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;
B,D
An identifier in Java is a name given to 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.
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
F
All of those listed are reserved words in Java. Click here to see the complete list and learn about each of them.
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 1 generates a compiler error.
B. Line 2 generates a compiler error.
C. Line 3 generates a compiler error.
D. Line 4 generates a compiler error.
E. Line 5 generates a compiler error.
F. Line 6 generates a compiler error.
G. The code compiles without error.
B, D, E
In Java, a literal is a number, text, or anything that representing 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.
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
D
In Java, boolean fields initialize to false while references initialize to null.
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
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.
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
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.
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
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.
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
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). That is just a method that happens to be the same as the class. The default constructor is called when this code runs, and count assumes the default value for an int (0).
Which of the following are factual 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.
B, E
While C++ has both operator overloading and pointers, Java does not have either. Java does have references to objects, but these point to an object 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 supports some functional programming parts, these occur within a class, so it is not considered a functional programming language.
What are the four pillars of Object-Oriented Programming (OOP)?
What is polymorphism?
Polymorphism is one of the four pillars of Object-Oriented Programming (OOP). It is a combination of two words, “poly” and “morph”, which mean “many forms.” According to the Oracle website, polymorphism is defined as follows.
“The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their unique behaviors and yet share some of the same functionality of the parent class.”
Click here for some examples.
What is inheritance?
Inheritance is one of the four pillars of Object Oriented-Programming (OOP). An example from the animal kingdom can explain it. We can agree that mammals have the following things in common.
- Mammary glands
- Single-boned lower jaws
- Warm-blooded metabolisms
Yet each mammal also defines additional features that set them apart from its peers. For instance, a cow moos while a dog barks.
In object-oriented programming, inheritance allows a class called Cow to inherit a commonly used state and behavior from another class called Mammal.
What is encapsulation?
Encapsulation is one of the four pillars of Object-Oriented Programming (OOP). It is how we protect data from being accessed by unauthorized users. Making class variables private and providing getter and setter methods to access them can achieve it.
What is abstraction?
Abstraction is one of the four pillars of Object-Oriented Programming (OOP). It refers to hiding specific details and providing user access only to essential information. We can use abstract classes and interfaces to achieve abstraction.
Click here to learn more.
What is the difference between throw and throws?
Throw and throws are keywords that are used for exception handling. Throw is used to throw an exception. While throws is used as part of a method’s signature to indicate that such method may throw an exception.
The example below shows how these two keywords may be used in a program.
public class CarInsurancePolicy {
public static void verifyCarAge(int age) throws ArithmeticException {
if (age > 3) {
throw new ArithmeticException("This policy does not qualify for new car discount.");
} else {
System.out.println("This policy qualifies for new car discount.");
}
}
public static void main(String[] args) {
verifyCarAge(3);
}
}
Line 3 shows that the verifyCarAge() method may throw an ArithmeticException. Line 5 throws this exception when the car’s age is more than three years.