Java Coding MCQ (Multiple Choice Questions) with Answers and Explanation

Java is a widely used and versatile programming language known for its platform independence, robustness, and scalability. Whether you are a Java enthusiast, a beginner, or an experienced developer, taking coding quizzes can be a fun and effective way to test your knowledge and learn new concepts. 

Check out 100+ quiz questions: 100+ Quiz Questions to Test Your Java, Spring Boot, Microservices, Hibernate, REST API Skills

In this blog post, we present a Java coding quiz with 25+ multiple-choice questions, each accompanied by detailed answers and explanations. Let's get started!

1. What is the output of the following code snippet?

int x = 5;
int y = 10;
System.out.println(x + y + "Hello");
a) 15Hello 
b) Hello15 
c) 510Hello 
d) 5Hello10 

Answer: 

a) 15Hello 

Explanation: 

In Java, when the + operator is used with a combination of numbers and strings, it performs addition for numbers and concatenation for strings. The expression x + y evaluates to 15, and then "Hello" is concatenated to it. Therefore, the final output is 15Hello.

2. What is the output of the following code snippet?

public class Main{
     public static void main(String []args){
        String str1 = "Hello";
        String str2 = new String("Hello");
        System.out.println(str1 == str2);
     }
}
a) true 
b) false 
c) It will cause a compilation error. 
d) It will throw a runtime exception. 

Answer: 

b) false 

Explanation: 

The == operator compares the object references. In this case, str1 and str2 refer to different objects, even though they contain the same string value. Therefore, the output is false.

3. What is the output of the following code snippet?

int[] arr = {1, 2, 3, 4, 5};
System.out.println(arr.length);
a) 1 
b) 2 
c) 3 
d) 5 

Answer: 

d) 5 

Explanation: 

The length property of an array in Java returns the number of elements in the array. In this case, the array arr has 5 elements, so the output is 5.

4. What is the output of the following Java program?

public class Main{
     public static void main(String []args){
        int x = 5;
        int y = 10;
        if (x < y)
            System.out.println("x is less than y");
        else if (x > y)
            System.out.println("x is greater than y");
        else
            System.out.println("x is equal to y");
     }
}
a) x is less than y 
b) x is greater than y 
c) x is equal to y 
d) The code will not compile due to a syntax error. 

Answer: 

a) x is less than y 

Explanation: 

The if condition x < y is true, so the code inside the first if block is executed, resulting in the output x is less than y

5. What is the output of the following Java program?

public class Main{
     public static void main(String []args){
        int x = 10;
        int y = 5;
        int z = (x > y) ? x : y;
        System.out.println(z);
     }
}
a) 10 
b) 5 
c) 15 
d) The code will not compile due to a syntax error. 

Answer: 

a) 10 

Explanation: 

The ternary operator (x > y) ? x : y evaluates to x because x is greater than y. Therefore, the output is 10.

6. What is the output of the following Java program?

public class Main{
     public static void main(String []args){
        int x = 10;
        while (x > 0) {
            System.out.print(x + " ");
            x--;
        }
     }
}
a) 10 9 8 7 6 5 4 3 2 1 
b) 10 9 8 7 6 5 4 3 2 1 0 
c) 1 2 3 4 5 6 7 8 9 10 
d) The code will not compile due to a syntax error. 

Answer: 

a) 10 9 8 7 6 5 4 3 2 1 

Explanation: 

The while loop iterates as long as the condition x > 0 is true. In each iteration, the value of x is printed, and then it is decremented. Therefore, the output is "10 9 8 7 6 5 4 3 2 1".

7. What is the output of the following Java program?

public class Main{
     public static void main(String []args){
        for (int i = 0; i < 5; i++) {
            System.out.print(i + " ");
            if (i == 2)
                break;
        }
     }
}
a) 0 1 2 
b) 0 1 2 3 4 
c) 0 1 
d) 0 1 2 3 4 5 

Answer: 

a) 0 1 2 

Explanation: 

The for loop iterates from 0 to 4. When i becomes 2, the if condition i == 2 is true, and the break statement is executed, terminating the loop. Therefore, the output is "0 1 2".

8. What is the output of the following Java program?

public class Main{
     public static void main(String []args){
        for (int i = 0; i < 5; i++) {
            if (i == 2)
                continue;
            System.out.print(i + " ");
        }
     }
}
a) 0 1 2 3 4 
b) 0 1 3 4 
c) 2 
d) 0 1 3 4 5 

Answer: 

b) 0 1 3 4 

Explanation: 

The for loop iterates from 0 to 4. When i becomes 2, the if condition i == 2 is true, and the continue statement is executed, skipping the rest of the loop body for that iteration. Therefore, the output is "0 1 3 4".

9. What is the output of the following Java program?

public class Main{
     public static void main(String []args){
        int i = 0;
        do {
            System.out.print(i + " ");
            i++;
        } while (i < 5);
     }
}
a) 0 1 2 3 4 
b) 0 1 2 3 4 5 
c) 1 2 3 4 5 
d) The code will not compile due to a syntax error.

Answer: 

a) 0 1 2 3 4 

Explanation: 

The do-while loop executes the loop body at least once and continues as long as the condition i < 5 is true. Therefore, the output is "0 1 2 3 4".

10. What is the output of the following program?

public class Main {
    public static void main(String[] args) {
        int x = 10;
        int y = x++;
        System.out.println(y);
    }
}
a) 10
b) 11
c) 9
d) Compile-time error

Answer:

a) 10 

Explanation:

The postfix increment operator (x++) first assigns the value of x to y, and then increments the value of x. Therefore, the value of y is 10.

11. What will be the output of the following Java program?

class Base {
    public Base() {
        System.out.println("Base");
    }
}

class Derived extends Base {
    public Derived() {
        System.out.println("Derived");
    }
}

class DeriDerived extends Derived {
    public DeriDerived() {
        System.out.println("DeriDerived");
    }
}

public class Test {
    public static void main(String[] args) {
        Derived b = new DeriDerived();
    }
}
a)
Base
Derived
DeriDerived
b)
Derived
DeriDerived
c)
DeriDerived
Derived
Base
d)
DeriDerived
Derived

Answer: 

a)
Base
Derived
DeriDerived

Explanation: 

Whenever a class gets instantiated, the constructor of its base classes (the constructor of the root of the hierarchy gets executed first) gets invoked before the constructor of the instantiated class.

12. What will be the output of the following Java program?

public class Test {
    public void print(Integer i) {
        System.out.println("Integer");
    }

    public void print(int i) {
        System.out.println("int");
    }

    public void print(long i) {
        System.out.println("long");
    }

    public static void main(String args[]) {
        Test test = new Test();
        test.print(10);
    }
}
a) The program results in a compiler error (“ambiguous overload”).
b) long
c) Integer
d) int

Answer: 

d) int

Explanation: 

For an integer literal, the JVM matches in the following order: int, long, Integer, int.... In other words, it first looks for an int type parameter; then it looks for long type; and so on. Here, since the int type parameter is specified with an overloaded method, it matches with int.

13. What will be the output of the following Java program?

public class StrEqual {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = new String("hello");
        String s3 = "hello";
        if (s1 == s2) {
            System.out.println("s1 and s2 equal");
        } else {
            System.out.println("s1 and s2 not equal");
        }
        if (s1 == s3) {
            System.out.println("s1 and s3 equal");
        } else {
            System.out.println("s1 and s3 not equal");
        }
    }
}
Which one of the following options provides the output of this program when executed?
a)
s1 and s2 equal
s1 and s3 equal
b)
s1 and s2 equal
s1 and s3 not equal
c)
s1 and s2 not equal
s1 and s3 equal
d)
s1 and s2 not equal
s1 and s3 not equal

Answer:

c)
s1 and s2 not equal
s1 and s3 equal

Explanation: 

JVM sets a constant pool in which it stores all the string constants used in the type. If two references are declared with a constant, then both refer to the same constant object. The == operator checks the similarity of the objects themselves (and not the values in it). Here, the first comparison is between two distinct objects, so we get s1 and s2 not equal. On the other hand, since references to s1 and s3 refer to the same object, we get s1 and s3 equal.

14. What is the output of the following Java program?

public class Test {

    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = new String("hello");

        s2 = s2.intern();
        System.out.println(s1 == s2);
    }
}
a) false
b) true

Answer: 

b) true

Explanation: 

We know that the intern() method will return the String object reference from the string pool since we assign it back to s2 and now both s1 and s2 are having the same reference. It means that s1 and s2 references point to the same object.

15. What is the output of the following code snippet?

public class Main {
    public static void main(String[] args) {
        String str = "Java";
        str.concat(" Programming");
        System.out.println(str);
    }
}
a) Java
b) Java Programming
c) Programming
d) Compile-time error

Answer:

a) Java

Explanation:

The concat() method returns a new string resulting from concatenating the specified string to the original string. However, in this code, the result of concat() is not assigned back to the str variable. Therefore, the original string "Java" remains unchanged, and the output is "Java".

16. What is the output of the following code snippet?

import java.util.regex.*;

public class RegexQuiz {
    public static void main(String[] args) {
        String regex = "\\d+";
        String input = "1234";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);

        while (matcher.find()) {
            System.out.print(matcher.group() + " ");
        }
    }
}
a) 1 
b) 1234 
c) 123456789 
d) Compile-time error

Answer:

b) 1234 

Explanation:

The regex pattern "\\d+" is used, which matches one or more digits. Since the input string "1234" consists of only digits, the regex pattern matches the entire string. Therefore, the output will be "1234".

17. What is the output of the following code snippet?

import java.util.regex.*;

public class RegexQuiz {
    public static void main(String[] args) {
        String regex = "[a-c]";
        String input = "abcABC";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);

        while (matcher.find()) {
            System.out.print(matcher.group() + " ");
        }
    }
}
a) a b c 
b) A B C 
c) a b c A B C 
d) Compile-time error

Answer:

a) a b c 

Explanation:

The regex "[a-c]" matches any character between 'a' and 'c' (inclusive) in a case-sensitive manner. In the input string "abcABC", it matches "a", "b", and "c" and prints them.

18. What is the output of the following Java program?

class One{
	public static void print(){
		System.out.println("1");
	}
}

class Two extends One{
	public static void print(){
		System.out.println("2");
	}
}

public class Test{
	public static void main(String args[]){
		One one = new Two();
		one.print();
	}
}
a) 2
b) 1
c) Compile-time error
d) Run-time error

Answer:

b) 1

Explanation:

Static methods are defined at the class level. In the case of the static methods, regardless of which object the reference is pointing to, it always calls the static method defined by the reference class. Here, the reference is of type One, so the static method of class One will be called.

19. What is the output of the following Java program?

class One{
	public void print(){
		System.out.println("1");
	}
}

class Two extends One{
	public void print(){
		System.out.println("2");
	}
}

public class Test{
	public static void main(String args[]){
		One one = new Two();
		one.print();
	}
}
a) 2
b) 1
c) Compile-time error
d) Run-time error

Answer:

a) 2

Explanation:

Even though the reference type of object one is One, the actual object it points to is of type Two due to polymorphism. When we call the print method on One, the JVM dynamically binds the call to the print method in class Two at runtime. As a result, "2" is printed on the console.

20. What is the output of the following Java program?

class One{

	public One(int x){
		System.out.print("int constructor");
	}

	public One(long l){
		System.out.print("long constructor");
	}
}

public class Test{

	public static void main(String[] args){
		long l = 20L;
		One one = new One(l);
	}
}
a) int constructor
b) long constructor
c) Compile-time error
d) Run-time error

Answer:

b) long constructor

Explanation:

When we create object one with the long variable l as an argument, the constructor with the long parameter in class One is called. As a result, the "long constructor" is printed to the console.
If you pass an int parameter in class One then it will print "int constructor" to the console.

21. What is the output of the following Java program?

class Parent{
	public void className(){
		System.out.println("Parent");
	}
}
class Child extends Parent{
	void className(){
		System.out.println("Child");
	}
}

public class Test{

	public static void main(String[] args){
		Parent parent = new Child();
		parent.className();
	}
}
a) Parent
b) Child
c) Compile-time error
d) Run-time error

Answer:

c) Compile-time error

Explanation:

When overriding a parent class method in a child class, we cannot reduce the visibility of the method. For example, if the method is defined as public in the parent class, a child class cannot override it with protected. The code will give the compilation error “Cannot reduce the visibility of the inherited method from Parent”.

22. What is the output of the following Java program?

class Demo{
	public Demo(int i){
		System.out.println("int");
	}

	public void Demo(short s){
		System.out.println("short");
	}
}

public class Test{

	public static void main(String[] args){
		short s = 10;
		Demo demo = new Demo(s);
	}
}
a) int
b) short
c) Compile-time error
d) Run-time error

Answer:

a) int

Explanation:

The class Demo has one constructor i.e. with int argument. The short value is automatically promoted to an int value during object creation so the constructor with the int argument will be called and it will print “int”.

23. What is the output of the following Java program?

class Demo{
	void Demo(){
		System.out.println("Demo");
	}

}

public class Test{

	public static void main(String[] args){
		Demo demo = new Demo();
	}
}
a) Demo
b) No Output
c) Compile-time error
d) Run-time error

Answer:

b) No Output

Explanation:

Java constructors do not have a return type. If you mention the return type, it automatically becomes a method instead of a constructor. Hence, the void Demo() becomes a method of the class Demo and thus it will not be called when an object of the class Demo is created.

24. What is the output of the following Java program?

class One{
	public One(){
		System.out.print("One,");
	}
}
class Two extends One{
	public Two(){
		System.out.print("Two,");
	}
}
class Three extends Two{
	public Three(){
		System.out.print("Three");
	}
}

public class Test{

	public static void main(String[] args){
		Three three = new Three();
	}
}
a) Three
b) One
c) One,Two,Three
d) Run-time error

Answer:

c) One,Two,Three

Explanation:

When we create an object of class Three, the constructors are executed in the following order: 
One(): Prints "One,". 
Two(): Prints "Two,". 
Three(): Prints "Three". 
So, the overall output is "One,Two,Three". The constructors are executed in the order of inheritance hierarchy from the topmost superclass (One) to the subclass (Three).

25. What is the output of the following Java program?

class Hello{
	public Hello(){
		System.out.println("Hello");
	}
}

public class Main{

	Hello hello = new Hello();

	public static void main(String[] args) {
		System.out.println("Hello World!");
	}
}
a) Hello
b) Hello World!
c) No Output
d) Run-time error

Answer:

b) Hello World!

Explanation:

The execution of the Java program starts from the main() method so it will print "Hello World!"

26. What is the output of the following Java program?

public class Main{

	static String name = "Ramesh";

	public Main(){
		name = "Prabhas";
	}

	public static void main(String[] args){
		System.out.println("The name is " + name);
	}
}
a) Prabhas
b) The name is Ramesh
c) No Output
d) Run-time error

Answer:

b) The name is Ramesh

Explanation:

The name String variable is declared as static and initialized with the string “Ramesh”. The value of the name variable is changed in the constructor. However, the class constructor is called only when an object is created. The code does not create any objects of the class Test, and hence the constructor is never called. So the value of the name variable remains unchanged.

27. What will be the output of the following program?

class First
{
    static void staticMethod()
    {
        System.out.println("Static Method");
    }
}

public class MainClass
{
    public static void main(String[] args)
    {
        First first = null;

        first.staticMethod();
    }
}
a) Static Method
b) Throws a NullPointerException
c) Compile-time error
d) Runtime error

Answer:

a) Static Method

Explanation:

The provided Java code will compile and execute successfully without any exceptions. When calling a static method, it doesn't require an instance of the class. Therefore, you can call the static method staticMethod() from class First using the null reference first.

Conclusion

Congratulations on completing the Java coding quiz! We hope this quiz has helped you assess your Java programming knowledge. Understanding these core concepts is crucial for Java developers. Feel free to review the explanations and practice more Java coding to improve your skills further. Happy coding!

Comments