Java Tutorial chapters (15)
  1. 01Java Introduction
  2. 02Java Variables & Data Types
  3. 03Java Control Statements
  4. 04Java OOPs Basics
  5. 05Java Inheritance & Polymorphism
  6. 06Java Abstraction & Interfaces
  7. 07Java Strings
  8. 08Java Arrays
  9. 09Java Exception Handling
  10. 10Java Collections Framework
  11. 11Java Multithreading
  12. 12Java 8 Features
  13. 13Java I/O & File Handling
  14. 14Java JDBC
  15. 15Java MCQ

Chapter 15

Java MCQ

3 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

A focused practice chapter with multiple-choice questions on Java basics, object-oriented programming and common interview topics.

Each section lists the facts the questions test and a runnable program that proves the tricky answers.

Campus tests, semester exams and screening rounds use MCQs.

Most wrong answers come from a handful of well-known traps that can be memorised and practised.

Placement aptitude tests, university exams, certification warm-ups (OCA/OCP style) and quick revision before interviews.

1

Java MCQ Basics

Java MCQ basics are short questions on data types, operators, literals, type conversion, strings and the program entry point. They are usually solved by knowing a small set of rules and tracing the code step by step.

In short: Basic MCQs test whether you know exactly how Java evaluates simple expressions, so read every character of the code.

Think about it

These questions are the easiest marks in any test; missing them is usually caused by haste, not lack of knowledge. Like reading a cheque: every digit matters, and the order in which you read them changes the amount.

Key rules: int is 4 bytes, long 8, char 2 (unsigned 16-bit), boolean has only true/false.

Defaults: numeric 0, boolean false, references null (local variables have NO default).

Integer overflow wraps around: `Integer.

MAX_VALUE + 1` is Integer.

MIN_VALUE and byte b = 127; b++ gives -128.

Integer division truncates toward zero and % takes the sign of the dividend (-7 % 3 is -1).

+ is evaluated left to right, so 10 + 20 + "Java" is "30Java" while "Java" + 10 + 20 is "Java1020".

A char in arithmetic becomes an int ('a' + 1 is 98), but char c = 'a'; c++ stays a char.

`Math.

round(2.5) is 3 but Math.

round(-2.5)` is -2 (it rounds half up).

Floating point cannot store 0.1 exactly, so 0.1 + 0.2 == 0.3 is false.

Pre/post-increment: x = x++ + ++x with x = 5 is 5 + 7 = 12.

Integer objects between -128 and 127 are cached, so == is true for 127 and false for 128.

goto and const are reserved keywords; sizeof does not exist.

The entry point is `public static void main(String[] args)`.

Always check for compile errors first (missing return, unreachable code, incompatible types) before predicting output.

Key points

  • Overflow: Result exceeds the type range and wraps around.
  • Widening: Automatic conversion to a larger type (int → long).
  • Narrowing: Explicit cast to a smaller type; may lose data.
  • Integer cache: Shared Integer objects for values -128 to 127.
  • Left-to-right evaluation: Operators of equal precedence are evaluated from the left.
  • Sample: 10 + 20 + "Java" + 10 + 20 → 30Java1020.
  • Sample: byte b = 127; b++ → -128. Math.round(-2.5) → -2.
  • Sample: -7 % 3 → -1. 7 / 2 → 3. 7 / 2.0 → 3.5. 1 / 2 * 2.0 → 0.0.
  • Sample: Integer 127 == 127 → true; 128 == 128 → false (different objects).
  • Local variables must be initialised before use; fields get defaults.

Example

Code
Classic basic-level output traps:
public class McqBasics {
    public static void main(String[] args) {
        System.out.println(10 + 20 + "Java" + 10 + 20);        // 30Java1020
        System.out.println("Java" + 10 + 20);                  // Java1020

        byte b = 127; b++;
        System.out.println(b);                                 // -128
        System.out.println(Integer.MAX_VALUE + 1);             // -2147483648

        System.out.println('a' + 1);                           // 98
        System.out.println((char) ('a' + 1));                  // b
        char c = 'a'; c++;
        System.out.println(c);                                 // b

        System.out.println(Math.round(2.5) + " " + Math.round(-2.5));  // 3 -2
        System.out.println(0.1 + 0.2 == 0.3);                  // false
        System.out.println(-7 % 3);                            // -1
        System.out.println(7 / 2 + " " + 7 / 2.0);             // 3 3.5
        System.out.println(1 / 2 * 2.0);                       // 0.0

        int x = 5;
        x = x++ + ++x;                                         // 5 + 7
        System.out.println(x);                                 // 12

        Integer p = 127, q = 127, r = 128, s = 128;
        System.out.println((p == q) + " " + (r == s));         // true false
        System.out.println(r.equals(s));                       // true

        boolean flag = false;
        if (flag = true) System.out.println("assigned");       // assigned  (= is assignment)

        int i = 0;
        i = i++;                                               // i stays 0
        System.out.println(i);                                 // 0

        long big = 1L << 40;
        System.out.println(big);                               // 1099511627776
        System.out.println(5 > 3 ? "yes" : "no");              // yes
    }
}
2

Java OOPs MCQ

Java OOPs MCQs test the four pillars (encapsulation, inheritance, polymorphism, abstraction) and the rules around constructors, overriding vs overloading, abstract classes, interfaces, final, static and access modifiers.

In short: Know which method runs (overriding at run time, overloading at compile time), what can be inherited, and what is forbidden.

Think about it

OOP MCQs repeat the same ideas with different code. Knowing the rules makes them quick to answer. A family tree: children inherit traits, but each person can behave differently (overriding), and the child is judged by who they are, not by the label on their file.

Rules to memorise: Java supports multiple inheritance only through interfaces, not through classes.

Constructors are not inherited and have no return type; this() / super() must be the first statement and you cannot use both together; if you do not write one, the compiler inserts super(), so the parent constructor always runs first.

Overloading (same name, different parameters) is compile-time polymorphism chosen by the reference/argument types; overriding (same signature in a subclass) is run-time polymorphism chosen by the actual object type.

Fields and static methods are NOT polymorphic: they are resolved by the reference type (field hiding and method hiding).

private, static and final methods cannot be overridden.

An abstract class cannot be instantiated but may have constructors, fields and concrete methods.

Interface variables are implicitly public static final; interface methods are public abstract (plus default/static/private in newer versions).

A final class cannot be extended, a final variable cannot be reassigned, a final method cannot be overridden.

Access levels from widest: public > protected > default (package) > private.

An overriding method cannot reduce visibility or throw broader checked exceptions.

instanceof tests the actual type.

With f(null) the most specific overload (String over Object) is chosen.

Key points

Example

Code
Overriding, hiding, constructors and abstract classes:
class Parent {
    String name = "Parent";
    Parent() { System.out.println("Parent constructor"); }
    void show() { System.out.println("Parent.show"); }
    static void util() { System.out.println("Parent.util"); }
}

class Child extends Parent {
    String name = "Child";
    Child() { super(); System.out.println("Child constructor"); }
    @Override void show() { System.out.println("Child.show"); }
    static void util() { System.out.println("Child.util"); }   // hides, not overrides
}

abstract class Shape {
    Shape() { System.out.println("Shape constructor"); }       // abstract classes may have constructors
    abstract double area();
}

class Square extends Shape {
    double side = 3;
    double area() { return side * side; }
}

public class McqOops {
    static void f(Object o) { System.out.println("Object"); }
    static void f(String s) { System.out.println("String"); }

    public static void main(String[] args) {
        Parent p = new Child();            // Parent constructor, then Child constructor
        p.show();                          // Child.show   (run-time polymorphism)
        System.out.println(p.name);        // Parent       (fields are not polymorphic)
        p.util();                          // Parent.util  (static resolved by reference type)
        System.out.println(p instanceof Child);   // true
        Child c = (Child) p;
        System.out.println(c.name);        // Child

        Shape s = new Square();            // Shape constructor
        System.out.println(s.area());      // 9.0

        f("hi");                           // String
        f(new Object());                   // Object
        f(null);                           // String (most specific overload)
        // Shape bad = new Shape();        // compile error: abstract
    }
}
3

Java Interview MCQs

Java interview MCQs cover the questions interviewers ask most often: pass-by-value, == vs equals, equals/hashCode contract, final vs finally vs finalize, collection behaviour, thread-safety, serialization, JVM memory and Java 8 features.

In short: These are short fact questions with traps; the best defence is understanding the reason behind each fact.

Practice: pick the correct option

Think about it

The same dozen concepts decide most screening rounds; clear reasoning also helps in the follow-up discussion. A job interview: the first question is a quick fact, but the follow-up always asks "why?".

Java is always pass-by-value: for objects, the value of the reference is copied, so changing the object through the parameter is visible to the caller, but reassigning the parameter is not.

== compares references (or primitive values) while `equals()` compares content when overridden; classes used in HashSet/HashMap must override equals and hashCode together (equal objects must have equal hash codes).

final (modifier), `finally (block that runs after try/catch) and finalize()` (deprecated method the GC may call before reclaiming an object) are three different things.

System.

gc() is only a request.

HashMap allows one null key and is unsynchronized; Hashtable does not allow null and is synchronized; ConcurrentHashMap is the scalable thread-safe map.

StringBuilder is not thread-safe, StringBuffer is.

Stack is LIFO; Queue is FIFO.

HashSet is unordered, LinkedHashSet keeps insertion order, TreeSet is sorted.

transient fields are skipped by serialization.

Objects live on the heap; local variables and method frames on the thread stack; infinite recursion causes StackOverflowError, while running out of heap causes OutOfMemoryError.

Interface default methods and lambdas arrived in Java 8; streams are lazy and single-use.

A try block with return still runs finally.

Key points

  • Pass-by-value: Java copies the argument value; for objects, the reference value.
  • equals/hashCode contract: If a.equals(b) then a.hashCode() == b.hashCode().
  • finalize(): Deprecated GC callback; never rely on it.
  • StackOverflowError: Thrown when the thread stack is exhausted (deep recursion).
  • OutOfMemoryError: Thrown when the heap cannot satisfy an allocation.
  • Java is pass-by-value, always.
  • final = constant/no override/no inherit; finally = cleanup block; finalize = GC hook.
  • HashMap: one null key; Hashtable: no nulls; ConcurrentHashMap: thread-safe, no null keys.
  • Equal objects must have equal hash codes.
  • String is immutable; StringBuffer is thread-safe; StringBuilder is faster.

Example

Code
Interview traps: pass-by-value, equals/hashCode, finally:
import java.util.*;

public class McqInterview {
    static void change(int n, int[] arr, StringBuilder sb, String s) {
        n = 99;                          // local copy only
        arr[0] = 99;                     // same array object
        sb.append("!");                  // same StringBuilder object
        s = s + "!";                     // new String, caller unaffected
        sb = new StringBuilder("new");   // reassigning parameter has no effect outside
    }

    static class NoEquals { int id; NoEquals(int id) { this.id = id; } }
    static class WithEquals {
        int id; WithEquals(int id) { this.id = id; }
        @Override public boolean equals(Object o) { return o instanceof WithEquals w && w.id == id; }
        @Override public int hashCode() { return Integer.hashCode(id); }
    }

    @SuppressWarnings("finally")
    static int test() {
        try {
            throw new RuntimeException("boom");
        } catch (Exception e) {
            return 1;
        } finally {
            System.out.println("cleanup");   // runs before the method returns 1
        }
    }

    public static void main(String[] args) {
        int n = 1; int[] arr = {1}; StringBuilder sb = new StringBuilder("hi"); String s = "hi";
        change(n, arr, sb, s);
        System.out.println(n + " " + arr[0] + " " + sb + " " + s);   // 1 99 hi! hi

        Set<NoEquals> a = new HashSet<>();
        a.add(new NoEquals(1)); a.add(new NoEquals(1));
        Set<WithEquals> b = new HashSet<>();
        b.add(new WithEquals(1)); b.add(new WithEquals(1));
        System.out.println(a.size() + " " + b.size());               // 2 1

        System.out.println(test());                                  // cleanup, then 1

        Map<String, Integer> m = new HashMap<>();
        m.put(null, 1);
        System.out.println(m.get(null));                             // 1
        try { new Hashtable<String, Integer>().put(null, 1); }
        catch (NullPointerException e) { System.out.println("Hashtable rejects null"); }

        Deque<Integer> stack = new ArrayDeque<>();
        stack.push(1); stack.push(2);
        System.out.println(stack.pop());                             // 2  (LIFO)

        String s1 = "java", s2 = new String("java");
        System.out.println((s1 == s2) + " " + s1.equals(s2));        // false true
    }
}

Solved examples

Example 01 · Basic

What is printed by System.out.println(1 + 2 + "3" + 4 + 5);

Given Data:
    Required To Find:

    Output

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: 1 + 2 = 3 (both ints)
    Step 2: 3 + "3" = "33"
    Step 3: "33" + 4 = "334", then + 5 = "3345"
    Final Answer: 3345

    Approach note: Once a String appears, every later + is concatenation.

    Example 02 · Basic

    Parent p = new Child(); p.show(); where both classes define show() and the field name. What does p.name give?

    Given Data:
      Required To Find:

      Which version is used

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: show() is overridden, so the Child version runs
      Step 2: Fields are resolved by the reference type Parent
      Step 3: p.name is the Parent field
      Final Answer: Child.show runs; p.name is "Parent".

      Approach note: Methods use the object type; fields and statics use the reference type.

      Example 03 · Intermediate

      Why does a HashSet of objects without equals/hashCode keep two logically equal objects?

      Given Data:
        Required To Find:

        Explanation

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: Default hashCode and equals use object identity
        Step 2: Two new objects have different identities
        Step 3: So the set treats them as different
        Final Answer: Override equals and hashCode so logically equal objects are equal.

        Approach note: Records provide equals/hashCode automatically.

        Example 04 · Basic

        What is the size in bits of Java int and the default value of an instance int field?

        Given Data:
          Required To Find:

          Size and default

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: int is always 32 bits in Java
          Step 2: Instance numeric fields default to 0
          Step 3: Local ints must be assigned before use
          Final Answer: 32 bits; default 0 for fields

          Approach note: Java fixed widths: byte 8, short 16, int 32, long 64.

          Real-world applications

          Java

          Using Java MCQ in real projects

          Placement aptitude tests, university exams, certification warm-ups (OCA/OCP style) and quick revision before interviews.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: Java passes objects by reference.

          Why this is wrong: Java copies the reference value; the reference itself cannot be re-pointed for the caller.

          ✅ Verified Truth: Java is strictly pass-by-value.

          ⚠️ Exam Tip: Show the swap(a, b) example that does not swap.

          ❌ Myth: Overriding is decided at compile time.

          Why this is wrong: The actual object type chooses the method at run time.

          ✅ Verified Truth: Overloading = compile time; overriding = run time.

          ⚠️ Exam Tip: Compile-time vs run-time polymorphism is a standard question.

          ❌ Myth: An abstract class cannot have a constructor.

          Why this is wrong: It runs when a concrete subclass is created.

          ✅ Verified Truth: Abstract classes can have constructors, fields and normal methods.

          ⚠️ Exam Tip: They just cannot be instantiated directly.

          ❌ Myth: System.gc() forces garbage collection.

          Why this is wrong: It is only a suggestion to the JVM.

          ✅ Verified Truth: The JVM decides when to collect.

          ⚠️ Exam Tip: finalize() is deprecated for the same reason.

          Revision notes

          A focused practice chapter with multiple-choice questions on Java basics, object-oriented programming and common interview topics. Each section lists the facts the questions test and a runnable program that proves the tricky answers.

          High-Yield Quick Revision Points

          1. Basics: left-to-right +, overflow wraps, integer cache -128..127, Math.round(-2.5) = -2
          2. OOP: overloading = compile time; overriding = run time; fields/statics by reference type
          3. Abstract class: constructors allowed, no instances; interface fields are public static final
          4. Java is pass-by-value; equals and hashCode go together
          5. final vs finally vs finalize; HashMap one null key; StringBuffer thread-safe
          6. Heap = objects; stack = frames; StackOverflowError = deep recursion

          Practice questions

          Question 1 · MCQ (Java basics)

          What is the size of an int in Java?

          Question 2 · MCQ (Java basics)

          What is the output of System.out.println(10 + 20 + "Java" + 10 + 20);?

          Question 3 · MCQ (Java basics)

          What is the default value of a boolean instance variable?

          Question 4 · MCQ (Java basics)

          What is printed? byte b = 127; b++; System.out.println(b);

          Question 5 · MCQ (Java basics)

          Which of the following is NOT a Java keyword?

          Question 6 · MCQ (Java basics)

          What does System.out.println('a' + 1); print?

          Question 7 · MCQ (Java basics)

          What does Math.round(2.5) return?

          Question 8 · MCQ (Java basics)

          What is the result of 0.1 + 0.2 == 0.3?

          Question 9 · MCQ (Java basics)

          int x = 5; x = x++ + ++x; What is x?

          Question 10 · MCQ (Java basics)

          Which is the correct signature of the Java entry point?

          Question 11 · MCQ (Java basics)

          Integer x = 128, y = 128; What is x == y?

          Question 12 · MCQ (Java basics)

          What is the value of -7 % 3 in Java?

          Question 13 · MCQ (Java OOPs)

          Which of these supports multiple inheritance in Java?

          Question 14 · MCQ (Java OOPs)

          Method overloading is an example of:

          Question 15 · MCQ (Java OOPs)

          Parent p = new Child(); p.show(); Child overrides show(). Which version runs?

          Question 16 · MCQ (Java OOPs)

          this() or super() call in a constructor must be:

          Question 17 · MCQ (Java OOPs)

          Can an abstract class be instantiated directly with new?

          Question 18 · MCQ (Java OOPs)

          Variables declared in an interface are implicitly:

          Question 19 · MCQ (Java OOPs)

          A method declared final cannot be:

          Question 20 · MCQ (Java OOPs)

          What is the visibility of a member with no access modifier?

          Question 21 · MCQ (Java OOPs)

          A static method redeclared in a subclass with the same signature is called:

          Question 22 · MCQ (Java OOPs)

          Which keyword prevents a class from being extended?

          Question 23 · MCQ (Java interview)

          Which of these is thread-safe?

          Question 24 · MCQ (Java interview)

          Java passes method arguments by:

          Question 25 · MCQ (Java interview)

          What is finalize()?

          Question 26 · MCQ (Java interview)

          How many null keys can a HashMap contain?

          Question 27 · MCQ (Java interview)

          Which data structure follows LIFO order?

          Question 28 · MCQ (Java interview)

          The transient keyword is used to:

          Question 29 · MCQ (Java interview)

          Java 8 streams are:

          Question 30 · MCQ (Java interview)

          PreparedStatement mainly helps to prevent:

          Question 31 · MCQ (Java interview)

          Default methods in interfaces were introduced in:

          Question 32 · MCQ (Java interview)

          Which collection keeps insertion order and rejects duplicates?

          Question 33 · MCQ (Java interview)

          Where are Java objects stored in memory?

          Question 34 · MCQ (Java interview)

          What typically causes a StackOverflowError?