Chapter 15
Java MCQ
3 topics · 1 sections · beginner-friendly study notes · Updated
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.
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
CodeClassic 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
}
}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
- Overloading: Same name, different parameter list; resolved at compile time.
- Overriding: Subclass redefines an inherited method; resolved at run time.
- Method hiding: Static method redeclared in a subclass; chosen by reference type.
- Abstract class: Class that cannot be instantiated and may contain abstract methods.
- Dynamic dispatch: Selecting the overridden method using the actual object type.
- Multiple inheritance of classes: not allowed. Of interfaces: allowed.
- Parent p = new
Child();p.method()runs the Child version; p.field gives the Parent field. - Static, private and final methods are not overridden.
- Abstract classes can have constructors; interfaces cannot.
- Default access = package-private.
Read more
Example
CodeOverriding, 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
}
}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.
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.
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
nullkey; Hashtable: no nulls; ConcurrentHashMap: thread-safe, nonullkeys. - Equal objects must have equal hash codes.
- String is immutable; StringBuffer is thread-safe; StringBuilder is faster.
Example
CodeInterview 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
What is printed by System.out.println(1 + 2 + "3" + 4 + 5);
Output
Formula Applied:—Approach note: Once a String appears, every later + is concatenation.
Parent p = new Child(); p.show(); where both classes define show() and the field name. What does p.name give?
Which version is used
Formula Applied:—Approach note: Methods use the object type; fields and statics use the reference type.
Why does a HashSet of objects without equals/hashCode keep two logically equal objects?
Explanation
Formula Applied:—Approach note: Records provide equals/hashCode automatically.
What is the size in bits of Java int and the default value of an instance int field?
Size and default
Formula Applied:—Approach note: Java fixed widths: byte 8, short 16, int 32, long 64.
Real-world applications
Using Java MCQ in real projects
Placement aptitude tests, university exams, certification warm-ups (OCA/OCP style) and quick revision before interviews.
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
- Basics: left-to-right +, overflow wraps, integer cache -128..127, Math.round(-2.5) = -2
- OOP: overloading = compile time; overriding = run time; fields/statics by reference type
- Abstract class: constructors allowed, no instances; interface fields are public static final
- Java is pass-by-value; equals and hashCode go together
- final vs finally vs finalize; HashMap one null key; StringBuffer thread-safe
- Heap = objects; stack = frames; StackOverflowError = deep recursion
Practice questions
What is the size of an int in Java?
What is the output of System.out.println(10 + 20 + "Java" + 10 + 20);?
What is the default value of a boolean instance variable?
What is printed? byte b = 127; b++; System.out.println(b);
Which of the following is NOT a Java keyword?
What does System.out.println('a' + 1); print?
What does Math.round(2.5) return?
What is the result of 0.1 + 0.2 == 0.3?
int x = 5; x = x++ + ++x; What is x?
Which is the correct signature of the Java entry point?
Integer x = 128, y = 128; What is x == y?
What is the value of -7 % 3 in Java?
Which of these supports multiple inheritance in Java?
Method overloading is an example of:
Parent p = new Child(); p.show(); Child overrides show(). Which version runs?
this() or super() call in a constructor must be:
Can an abstract class be instantiated directly with new?
Variables declared in an interface are implicitly:
A method declared final cannot be:
What is the visibility of a member with no access modifier?
A static method redeclared in a subclass with the same signature is called:
Which keyword prevents a class from being extended?
Which of these is thread-safe?
Java passes method arguments by:
What is finalize()?
How many null keys can a HashMap contain?
Which data structure follows LIFO order?
The transient keyword is used to:
Java 8 streams are:
PreparedStatement mainly helps to prevent:
Default methods in interfaces were introduced in:
Which collection keeps insertion order and rejects duplicates?
Where are Java objects stored in memory?
What typically causes a StackOverflowError?