Java questions and answers

OOP, strings, collections and exceptions. Practise java questions from the technical & programming section of placement tests, with a worked explanation after every answer. Practice is free and needs no sign-up.

Sample java questions with worked answers

Question 1

Which Java keyword, when applied to a class, prevents any other class from extending it?

  1. static
  2. final
  3. private
  4. abstract

Answer: B. final

Explanation: A final class cannot be subclassed (java.lang.String is an example). abstract means the opposite: the class is meant to be extended.

Question 2

Which of the following statements about interfaces is true in Java 8 and later?

  1. An interface can have instance fields that each object gets its own copy of
  2. An interface can contain default methods that have a body
  3. An interface can have a public constructor
  4. A class can implement only one interface

Answer: B. An interface can contain default methods that have a body

Explanation: Since Java 8, interfaces may define default and static methods with bodies. Interface fields are implicitly public static final, interfaces cannot have constructors, and a class can implement many interfaces.

Question 3

What will be the output of the following Java program?

class P {
    static String who() { return "P"; }
    String me() { return "p"; }
}

class C extends P {
    static String who() { return "C"; }
    String me() { return "c"; }
}

public class Main {
    public static void main(String[] args) {
        P obj = new C();
        System.out.println(obj.who() + obj.me());
    }
}
  1. Cc
  2. Pp
  3. Pc
  4. Cp

Answer: C. Pc

Explanation: Static methods are not overridden, only hidden, so obj.who() is chosen by the reference type P and returns "P". me() is an instance method, so it is overridden and returns "c".

All 30 java questions with answers

Java: common questions

What are java questions?

OOP, strings, collections and exceptions. They appear in the technical & programming section of many placement tests.

Where can I practise java questions with answers for free?

Right here on LogicWiz Exams. Every java question has a worked explanation after you answer. Practice is free and needs no sign-up.

How should I practise java?

Start with easy questions, then move to medium and hard. Read the explanation after each answer, and come back to the ones you missed.

Start practising

On this page you can start a fresh set of java questions, choose easy, medium or hard, and time yourself if you want to. Or practise the whole subject: Technical & Programming practice.

More technical & programming topics

Other subjects

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge · Test from a job description · LogicWiz Open: free team quiz · Free interview prep