50 Tricky Java MCQs – Check if you can answer

Tricky Java MCQs uniquely Crafted from Real face-face Interviews on core java, oop and collections to gain confidence.

Are you really good at java basic concepts? Try these MCQs. (10 Questions are given below with answer & detailed explanation. You can read all 50 questions on google play here.)

MCQ – 1

class Box {
}

public class Sample {

	public static void main(String[] args) {

		Box box = new Box();
		String x = "box";
		new String("box");
	}
}

In the given program, the following statements are related to which part of the memory?


a) Box box
b) new Box();
c) "box" string which is assigned to x;
d) new String("box");
  1. (a) Stack, (b) Heap, (c) String pool, (d) Heap
  2. (a) and (b) together on Heap, (c) String pool, (d) Heap
  3. (a) Heap (c) Heap, (c) String pool (D) String pool
  4. None of the above is correct

Answer: 1

a)

The local variables within a method reside on the stack. Since the box variable is a local reference variable in the main method which can refer to a Box class object, it will go to the stack.

b)

The new Box(); statement creates an object of the class Box on the heap memory (The reference of this object will be assigned to the box variable).

c)

The“box” string will go to the string pool (part of heap). Its reference is assigned to the String x variable which is on the stack.

d)

The new String(“box”); creates an object on the heap. It also creates another object in the string pool if it does not find the string “box” in the string pool. Since the “box” is already there in the pool from the previous statement String x = “box”; it will not create another object in the string pool.

VIEW ANSWER

MCQ – 2

class Fuel{
	public int litre = 0;	
}


class Petrol extends Fuel {
	
	public static void fill (){
		litre = 10;
		super.litre =20;
		new Fuel().litre =30;		
	}
}

Which statement(s) cannot access and modify the litre variable of the Fuel class from the fill () method?

  1. litre = 10;
  2. super.litre =20;
  3. new Fuel().litre =30;

Answer: 1 and 2

Since the litre variable in the Fuel class is public, it can be accessible from the child class Petrol.

Let’s discuss why 1st and 2nd statements cannot access while the 3rd can access.

1)

litre = 10;

The fill() method is static. A static method can access only a static variable. And the litre variable is not static. Hence, this statement has an error.

2)

super.litre =20.

The super keyword can be used to access the base class public variables from a non-static method.

In a static method, we cannot use the super keyword. If you use it, then the compiler will flash an error with the message: Cannot use super in a static context”

So, this statement is also wrong.

3)

new Fuel().litre =30;

In a static method, it is ok to call a normal public variable or methods of a class using an object.

So, this is the correct statement and can access the litre variable.

Conclusion: both the options 1st and 2nd cannot access the base class variable litre.

VIEW ANSWER

MCQ – 3

interface Charger {
	void fill();
}

interface Fuel {
	void fill();
}

class Car implements Charger, Fuel {

	@Override
	public void fill() {
		System.out.println("filling");
	}
}

Choose the correct answer about the interface implementation in the code.

  1. Two interfaces cannot have a method with the same name.
  2. Compile-time error.
  3. Run-time error because of ambiguous call of the fill() method.
  4. The interface implementation is fine.

Answer: 4

Interfaces just provide functionalities specifications (unimplemented abstract methods), to subclasses to implement those specifications.

It does not matter how many same specifications you provide with multiple interfaces; a subclass will implement them for only one time without any issue and any confusion.

Let’s consider a scenario,

your mother gives you a specification to prepare a nameplate to put on the main door of your home. And asked you to go to the market to get it ready(implemented).

Your father also gives the same specification and asked you to get it ready. It’s possible. Right?

So, how many nameplates you’d get ready from the market? Of course, one.

So, you got two interfaces, one mother and another father, but with the same specification (nameplate method). And you implemented it and got a nice nameplate. Isn’t this scenario true?

So, the same is applied in the code as well.

As a Code Test:

If you call the fill() method using the object of the Car as shown below, you’ll get the output as “filling”.

public class Sample {

	public static void main(String[] args) {

		Car c = new Car();
		c.fill();
	}
}

VIEW ANSWER

MCQ – 4

public class Sample {

public static void main(String[] args) {

if (new String("Java") == "Java");//1
if (new String("Java") == new String("Java"));// 2
if (new String("Java").equals("Java")); // 3

	}
}

The expressions in the if conditions 1, 2, and 3 will evaluate to:

  1. true, true, false
  2. false, true, false
  3. false, false, true
  4. true, false, true

Answer: 3: false, false, true

You need to keep 3 points in mind.

1) The string literals “Java” get stored in the string pool (part of a heap area).

2) Every time, when you create an object using the new keyword, it creates an object on the heap memory with the string value “Java”.

3) When you use “==” comparator, you’re comparing the references, not the content “Java” string. To compare the content at two places in the memory, we use the equal method.

So, in the 1st if condition, the “Java” string is at two places, one in the heap and another in the string pool. In the expression, we’ve compared their references using the “==” operator. Since their references are different, the expression will result in false.

In the 2nd if condition, we’ve created the “Java” string at two separate places in the heap itself. But have used == operator, so expression becomes false.

In the 3rd if condition, one “Java” string is in the heap, and another is in the string pool. Since we’ve used the equal method, the content “Java” will be compared not their references. Since strings contents are the same at both places, the expression becomes true.

Hence, the expressions in the 1st and 2nd conditions are false, and the 3rd condition true.

VIEW ANSWER

MCQ – 5

import java.util.HashMap;
public class Sample {

	public static void main(String[] args) {

		HashMap<Integer, String> map = new 			HashMap<Integer, String>();

		map.put(1, "Java");
		map.put(null, "OOP");
		map.put(null, null);

	}
}

What is the size of the HashMap?

  1. 0
  2. 1
  3. 2
  4. Run time error
  5. Compile-time error

Answer: 3: HashMap size is 2

The HashMap contains a key-value pair, and it can accept null as a key or null as a value.

If you try to put another null key if one already exists, then the compiler will not throw any error, but it will replace the previous key-value pair with the new one.

For example, in below code, the (null, “OOP”) key value will be replaced with (null, null);

            map.put(null, “OOP”);

            map.put(null, null);

So, in the given code, the hash map contains the key-value pair (1, “Java”); and (null, null). Hence the size will be 2.

If you place the System.out.println(map. size()); as the last statement in the main method in the given program, it’ll print the map size 2.       

SIDE NOTE

1)

If you try to put any duplicate key including null, the existing key value will be updated with the new one.

For example, if you add key value like below,

            map.put(1, “Java”);

            map.put(1, “OOP”);

the map will contain key-value pair (1, “OOP”); not the pair (1, “Java”);

2)

The map can contain multiple null values as shown below.

            map.put(2, null);

            map.put(3, null);

VIEW ANSWER

MCQ – 6

public class Sample {

	public static void main(String[] args) {

		bulb(false, true);
		bulb(false, false);
	}

	public static void bulb(boolean on, boolean off) {

		if (on) {
			System.out.println("Status1");
		} else if (on && off) {
			System.out.println("Status2");
		} else {
			if (!off) {
				System.out.println("Status3");
			} else {
				System.out.println("Status4");
			}
		}
	}
}

What is the output?

  1. Status4, Status2
  2. Status4, Status3
  3. Status2, Status2
  4. Status2, Status3

Answer: 2: Status4, Status3

bulb (false, true)call;

When you call this method bulb (boolean on, boolean off), the on variable contains false and the off contains true.

Since the variable on is false, the control will skip the if (on) condition and jump straight to the else if (on && off).  Here, since on is false, the control will not bother about the off variable if it is true or false after the logical and (&&) operator.

You know that the && operator always evaluates to true if and only if both side variables are true. If the control finds the left variable false, then there is no point in evaluating the right-side variable.

So, the control will move to the else part in if (!off) condition. Here, the off variable is true but the negation (!) operator will change its value to false. So, the control will jump to the else part printing the string “Status4”.

bulb (false, false); call:

This will call the method bulb (boolean on, boolean off). The variable on is false and off is also false. So, the control will skip the if (on) condition and jump straight to the else if (on && off). Here, the on is false, so the control will jump to the else part in the if (! off) condition. Here, since, the off variable is false, the ! operator will change it to true. So, the control will come inside this condition and print the string Status3.

VIEW ANSWER

MCQ – 7

class Player {
	public void start() {
		System.out.println("Start player ");
		stop();
	}

	public void stop() {
		System.out.println("Stop player ");
	}
}

class Music extends Player {
	public void start() {
		super.start();
		System.out.println("Start music");
	}

	public void stop() {
		System.out.println("Stop music ");
	}
}

public class Sample {

	public static void main(String[] args) {

		new Music().start();		
	}
}

What is the output of the program?

  1. Start player, Stop music, Start music
  2. Start player, Stop player, Start music
  3. Start music, Start player, Stop player
  4. None of the above.

Answer: 1: Start player, Stop music, Start music

Let’s start with the main () method, where the start () method is invoked by an object of the child class Music.

            new Music().start();         

The control will go the start () method of the Music class, and then move immediately to the base class Player start () method because of its call using the super keyword (super.start() ) and print the message “Start Player”.

The next statement after printing the message is invocation of the stop () method.

The actual trick is here: It seems like the stop () method of the Player base class itself will be called, but it’s not. Actually, since, we’re using the child class object, so the stop () method of the Music class will be called. Hence, the next message will be printed as “Stop Music”.

Now the control will come back inside the start () method of the child class Music after the super.start() method call and then print the message “Start music”.

So, the answer sequence would be as Start Player, Stop music, Start music!

VIEW ANSWER

MCQ – 8

public class Sample {

	public static void main(String[] args) {
		int index = 0;
		String[] box = 						{"Red","Green","Blue","Black" };

		try {
			double x = 9.0 / 0.0;
			index++;

			int y = 5 / 0;
			index++;

		} catch (ArithmeticException e) {
			index++;

		} finally {
			index++;
		}
		System.out.println(box[index]);
	}
}

Which color of the box will be printed?

  1. Red
  2. Green
  3. Blue
  4. Black

Answer: 4:Black

Let’s have the tricky concepts first.

When we divide a number by a double number, 0.0, the result comes as infinity. Or NaN (not a number).

double x = 9.0 / 0.0;

When we divide a number an integer number 0, as int x = 5 / 0;

the result throws an exception java.lang.ArithmeticException: / by zero .

So, coming to the code,

The initial value of the index is 0.

In the try block, since the statement double x = 9.0 / 0.0; does not throw an exception, the next index++; will execute and its value becomes 1.

When the next statement int y = 5 / 0; executes, an arithmetic exception is thrown, so the next index++ will not be executed and control goes to the catch block.

In the catch block, the index++ results in 2.

Now the control will come to the block finally and execute the index++ that results in 3.

Note that in the try block, you get an exception or not, the control always comes to the block finally unless you force a program to exist e.g., using the system exist method i.e., System.exit(0).

In the next statement the System.out.println(box[index]); we have retrieved the element with index 3 from the box array and print.

Since, at the 3rd index, the element is Black. The output will be printed as Black.

VIEW ANSWER

MCQ – 9

public class Sample {

	public static void main(String[] args) {	
		int n = 1;
		switch(n)
		{
		  case 0:System.out.println("Apple");
		  break;
		  case 1:System.out.println("Kiwi");		  
		  case 2:System.out.println("Mango");
		  case 4%3:System.out.println("Orange");
		}
	}	
}

What is the output of the program?

  1. Kiwi
  2. Kiwi, Mango
  3. Kiwi, Mango, Orange
  4. Compiler error

Answer: 4

Case 1 and Case 4%3 are the same because 4%3 also results in 1. Since there cannot be duplicate cases in a switch-case statement, the compiler will throw an error at the compile time itself.

SIDE NOTE

The % sign between the numbers 4 and 3 represents the remainder. If you divide the number 4 by 3, the remainder will be 1 as shown below.

3) 4 (1
  - 3
*************
     1 (Remainder)

VIEW ANSWER

MCQ – 10

public class Sample {

	public static void main(String[] args) {

		System.out.println(3 + 5 + "JDK");
		System.out.println("MCQ" + 5 + 0);
	}
}

What is the output?

  1. 8JDK, MCQ50
  2. 8JDK, MCQ5
  3. 35JDK, MCQ50
  4. 8, 5

Answer: 1: 8JDK, MCQ50

3 + 5 + “JDK” :

Since the associativity of the + operator is from left to right. 3 and 5 will be added and the expression will become as below.

8 + “JDK”

Now, since the + operator with string acts as a concatenation operator. The expression would become as a string as below.

“8JDK”

“MCQ” + 5 + 0:

Following the above concepts:

“MCQ” + 5 + 0 will result in a string “MCQ5” + 0. Further, it’ll become to a string “MCQ50”.

So, the answer would be: 8JDK, MCQ50

VIEW ANSWER

Read instantly all the 50 tricky Java MCQs to improve your Java basics on Google play. Click the below button!

Leave a Comment