MPSeDC GET Program 3.0 2026 – Exam-Oriented JAVA MCQ Questions

MPSeDC GET Program 3.0 2026 – Exam-Oriented JAVA MCQ Questions

BEGINNER LEVEL

Q1: Which of the following is the correct order of access modifiers from most restrictive to least restrictive?
A. public, protected, default, private
B. private, default, protected, public
C. private, protected, default, public
D. public, default, protected, private

Correct Answer: B
Explanation: Access modifiers in increasing order of visibility are: private < default (package-private) < protected < public. private is visible only within the class; default within the package; protected within package + subclasses; public everywhere.
Exam Trick: Remember: P-D-P-P (Private < Default < Protected < Public) — visibility increases left to right.


Q2: Which modifier allows a class member to be accessed only within its own class?
A. default
B. protected
C. private
D. public

Correct Answer: C
Explanation: private restricts access strictly to the declaring class — not even subclasses or same-package classes can access it.
Exam Trick: private = ‘Personal’, stays inside the class only.


Q3: Top-level (outer) classes in Java can use which access modifiers?
A. private and public only
B. public and default(package-private) only
C. protected and private only
D. All four modifiers

Correct Answer: B
Explanation: A top-level class can only be public or default (no modifier). private and protected are not allowed for top-level classes (only for members/nested classes).
Exam Trick: Top-level class rule: ‘Public or Nothing’ (no private/protected at top level).


Q4: Which keyword is used to inherit a class in Java?
A. implements
B. extends
C. inherits
D. instanceof

Correct Answer: B
Explanation: ‘extends’ is used for class inheritance (and interface extension). ‘implements’ is used when a class implements an interface.
Exam Trick: Class extends Class; Class implements Interface.


Q5: What is the default value of a boolean instance variable in Java?
A. true
B. false
C. 0
D. null

Correct Answer: B
Explanation: Uninitialized instance variables of type boolean default to false; numeric types default to 0/0.0; object references default to null.
Exam Trick: Boolean default = false. Numbers default = 0. Objects default = null.


Q6: Which of these is NOT a pillar of Object-Oriented Programming?
A. Encapsulation
B. Polymorphism
C. Compilation
D. Inheritance

Correct Answer: C
Explanation: The four OOP pillars are Encapsulation, Inheritance, Polymorphism, and Abstraction. Compilation is a build process, not an OOP concept.
Exam Trick: Remember ‘A PIE’: Abstraction, Polymorphism, Inheritance, Encapsulation.


Q7: What is the output of the following code?
int x = 5;
int y = x++ + ++x;
System.out.println(y);

A. 10
B. 11
C. 12
D. 13

Correct Answer: B
Explanation: x++ uses 5 (then x becomes 6); ++x increments first to 7. So y = 5 + 7 = 12. Trace: x=5 → x++ returns 5, x becomes 6 → ++x makes x=7 and returns 7 → y=5+7=12.
Exam Trick: Post-increment uses old value then increments; pre-increment increments then uses new value. Trace step by step on paper.


Q8: Which operator is used for logical short-circuit AND?
A. &
B. &&
C. |
D. and

Correct Answer: B
Explanation: && is the short-circuit AND — if the left operand is false, the right operand is not evaluated. & is the non-short-circuit (bitwise/logical) AND.
Exam Trick: Double symbol (&&, ||) = short-circuit (lazy); single symbol (&, |) = always evaluates both sides.


Q9: Which loop is guaranteed to execute its body at least once?
A. for
B. while
C. do-while
D. for-each

Correct Answer: C
Explanation: do-while checks the condition AFTER executing the loop body, so the body always runs at least one time, regardless of the condition.
Exam Trick: do-while = ‘Do first, check later’.


Q10: What does the ‘break’ statement do inside a switch case?
A. Terminates the entire program
B. Exits the switch block
C. Skips to the next case
D. Restarts the switch

Correct Answer: B
Explanation: break exits the enclosing switch statement (or loop). Without it, execution ‘falls through’ into subsequent case blocks.
Exam Trick: Forgetting ‘break’ in switch is a classic trap — leads to fall-through execution.


Q11: Which class is the superclass of all exceptions and errors in Java?
A. Exception
B. RuntimeException
C. Throwable
D. Error

Correct Answer: C
Explanation: java.lang.Throwable is the root class. It has two main subclasses: Exception (recoverable) and Error (serious, usually unrecoverable, like OutOfMemoryError).
Exam Trick: Throwable is the grandparent of Exception and Error — ‘Throwable Throws it all’.


Q12: Which keyword is used to manually throw an exception?
A. throws
B. throw
C. catch
D. raise

Correct Answer: B
Explanation: ‘throw’ is used to explicitly throw an exception instance. ‘throws’ is used in a method signature to declare exceptions a method might throw.
Exam Trick: throw = action (throws the object); throws = declaration (method signature).


Q13: Strings in Java are:
A. Mutable
B. Immutable
C. Mutable only with StringBuilder
D. Mutable only inside methods

Correct Answer: B
Explanation: Once created, a String object’s content cannot be changed. Any modification (concat, replace etc.) creates a new String object.
Exam Trick: String = immutable. For mutable strings use StringBuilder/StringBuffer.


Q14: What is the output of the following code?
String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1 == s2);

A. true
B. false
C. Compilation error
D. Runtime exception

Correct Answer: A
Explanation: Both s1 and s2 refer to the same object in the String pool (string literals are interned), so == (reference comparison) returns true.
Exam Trick: Literal strings without ‘new’ go to the String Constant Pool and get reused.


Q15: Which class is commonly used to read input from the console in Java?
A. System.out
B. Scanner
C. Reader
D. FileReader

Correct Answer: B
Explanation: java.util.Scanner wraps System.in to easily parse primitive types and strings from console input.
Exam Trick: Scanner sc = new Scanner(System.in); — the standard exam pattern.


Q16: Which method converts a String to an int in Java?
A. String.toInt()
B. Integer.parseInt()
C. Integer.valueOf(int)
D. (int) string

Correct Answer: B
Explanation: Integer.parseInt(String) parses a String and returns a primitive int. Integer.valueOf(String) returns an Integer object instead.
Exam Trick: parseInt → primitive; valueOf → wrapper object.


Q17: Which interface does the ArrayList class implement (among others)?
A. Set
B. List
C. Map
D. Queue

Correct Answer: B
Explanation: ArrayList implements the List interface, providing an ordered, index-based, resizable-array collection allowing duplicates.
Exam Trick: ArrayList = List family = ordered + duplicates allowed.


Q18: Which collection does NOT allow duplicate elements?
A. ArrayList
B. LinkedList
C. HashSet
D. Vector

Correct Answer: C
Explanation: Set implementations like HashSet do not allow duplicate elements; adding a duplicate has no effect.
Exam Trick: Remember: ‘Set’ = unique elements only, just like a mathematical set.


Q19: What is an inner class in Java?
A. A class defined outside any other class
B. A class defined within another class
C. A class with only static members
D. A class that cannot have methods

Correct Answer: B
Explanation: An inner (nested) class is a class defined within the body of another class. It can access the enclosing class’s members, including private ones.
Exam Trick: Inner class = ‘class inside a class’, has implicit access to outer instance.


Q20: Which method is used to start a new thread of execution in Java?
A. run()
B. start()
C. execute()
D. init()

Correct Answer: B
Explanation: start() creates a new call stack and invokes run() in a separate thread of execution. Calling run() directly just executes it in the current thread (no new thread is created).
Exam Trick: start() → new thread; run() → just a normal method call if invoked directly.


Q21: What is the default access modifier when none is specified?
A. private
B. protected
C. public
D. package-private (default)

Correct Answer: D
Explanation: If no access modifier is specified, Java applies ‘default’ (also called package-private) access — visible only within the same package.
Exam Trick: No modifier = default = package-level visibility only.


Q22: Which keyword prevents a class from being subclassed?
A. static
B. final
C. abstract
D. const

Correct Answer: B
Explanation: ‘final’ on a class prevents inheritance. ‘final’ on a method prevents overriding. ‘final’ on a variable prevents reassignment.
Exam Trick: final = ‘no more changes’ — applies to class (no extend), method (no override), variable (no reassign).


Q23: Which keyword is used to create an object in Java?
A. new
B. create
C. object
D. instance

Correct Answer: A
Explanation: The ‘new’ keyword allocates memory for an object and invokes the constructor to initialize it.
Exam Trick: ‘new’ = always followed by a constructor call, e.g. new Car().


Q24: What does the expression 10 % 3 evaluate to?
A. 3
B. 1
C. 0
D. 3.33

Correct Answer: B
Explanation: % is the modulus operator, returning the remainder of integer division. 10/3 = 3 remainder 1.
Exam Trick: Modulus gives the remainder, not the quotient.


Q25: Which statement is used to skip the current iteration of a loop and continue with the next?
A. break
B. continue
C. return
D. skip

Correct Answer: B
Explanation: ‘continue’ skips the remaining statements in the current loop iteration and moves to the next iteration’s condition check.
Exam Trick: break = exit loop completely; continue = skip to next round.


Q26: Which block always executes whether or not an exception occurs?
A. try
B. catch
C. finally
D. throw

Correct Answer: C
Explanation: ‘finally’ executes regardless of whether an exception was thrown or caught, except in cases like System.exit() or JVM crash.
Exam Trick: finally = ‘final cleanup’ — almost always runs.


Q27: Which method returns the length of a String?
A. size()
B. length()
C. len()
D. count()

Correct Answer: B
Explanation: String.length() returns the number of characters. Note: arrays use the ‘length’ field (no parentheses), while String/Collections use length()/size() methods.
Exam Trick: String → length(); Array → length (field); Collection → size().


Q28: Which package contains the Scanner class?
A. java.io
B. java.util
C. java.lang
D. java.text

Correct Answer: B
Explanation: Scanner is part of java.util package, not java.io.
Exam Trick: Scanner → java.util (commonly confused with java.io).


Q29: What is the main benefit of using Generics in Java?
A. Faster runtime execution
B. Type safety at compile time
C. Reduces memory usage
D. Removes the need for casting at runtime only

Correct Answer: B
Explanation: Generics enable compile-time type checking, eliminating unsafe casts and catching type-mismatch errors early (before runtime, via ClassCastException prevention).
Exam Trick: Generics = compile-time type safety, avoids ClassCastException surprises.


Q30: Which interface must a class implement to define a thread’s task without extending Thread?
A. Runnable
B. Threadable
C. Executable
D. Callable only

Correct Answer: A
Explanation: Implementing Runnable and passing it to a Thread object is the preferred approach since Java allows only single inheritance, and Runnable promotes better design (separation of task from thread management).
Exam Trick: Prefer Runnable over extending Thread — keeps your design flexible (single inheritance limit).

INTERMEDIATE LEVEL


Q31: Identify the error in the following code:
public class Test {
  protected static final int X;
  public static void main(String[] a){}
}

A. No error
B. ‘final’ variable X must be initialized
C. ‘static’ cannot be used with ‘final’
D. ‘protected’ is invalid for top-level access

Correct Answer: B
Explanation: A blank final variable (static or instance) MUST be assigned a value either at declaration or in a static initializer block (for static) / constructor (for instance) before use, otherwise it’s a compile error.
Exam Trick: final variables = ‘assign exactly once’. If not at declaration, must happen in constructor/static block.


Q32: Can a private method be overridden in a subclass?
A. Yes, always
B. No — private methods are not inherited, so subclass methods with the same signature simply hide it
C. Yes, but only if marked final
D. Only in the same package

Correct Answer: B
Explanation: Private methods are not visible to subclasses at all, so they cannot be overridden. If a subclass declares a method with the same signature, it’s an independent new method, not an override.
Exam Trick: private + override = impossible. Private members aren’t inherited — they’re invisible outside the class.


Q33: What is method overloading resolved by?
A. Return type only
B. Number and/or type of parameters (compile-time / static binding)
C. Access modifier
D. Runtime object type

Correct Answer: B
Explanation: Overloading is resolved at compile time based on the method signature (parameter list) — this is static/early binding, unlike overriding which uses dynamic/runtime binding.
Exam Trick: Overloading = compile-time (static); Overriding = runtime (dynamic).


Q34: What is the output of the following code?
class A { void show(){ System.out.println("A"); } }
class B extends A { void show(){ System.out.println("B"); } }
public class Test {
  public static void main(String[] args){
    A a = new B();
    a.show();
  }
}

A. A
B. B
C. Compilation error
D. Runtime exception

Correct Answer: B
Explanation: Even though the reference type is A, the actual object is B. Method calls on overridden instance methods use the object’s runtime type (dynamic method dispatch / runtime polymorphism).
Exam Trick: Reference type decides what’s ACCESSIBLE; object type decides what RUNS (for overridden methods).


Q35: Which of these can have a body in Java (default methods aside)?
A. Abstract method
B. Interface constant
C. Concrete (non-abstract) method
D. None of the above can have a body

Correct Answer: C
Explanation: A concrete method has an implementation (body). Abstract methods have no body; interface fields are implicitly public static final constants.
Exam Trick: Abstract = no body, must end with semicolon, must be implemented by a concrete subclass.


Q36: A class has two constructors: one with no arguments and one with one int argument. If you instantiate the class with ‘new MyClass()’, which constructor is invoked?
A. The one with int argument
B. The no-argument constructor
C. Compilation error — ambiguous
D. Both run sequentially

Correct Answer: B
Explanation: Constructor overloading works just like method overloading — Java picks the constructor matching the argument list given, here the no-arg constructor.
Exam Trick: Constructors follow normal overload resolution rules based on arguments passed.


Q37: What is printed by the following code?
byte b = 10;
b = b + 1; // line A

A. Compiles fine, prints nothing relevant
B. Compilation error at line A
C. Runtime exception
D. Prints 11 with no issue

Correct Answer: B
Explanation: b + 1 is promoted to int automatically (binary numeric promotion). Assigning an int back to a byte without an explicit cast causes a compile-time ‘possible lossy conversion’ error. (b += 1 would work due to implicit cast in compound assignment.)
Exam Trick: Compound assignment (+=) has an implicit cast; plain assignment (=) does not — classic exam trap.


Q38: What is the output of the following code?
int a = 5;
int b = (a > 3) ? 10 : 20;
System.out.println(b);

A. 5
B. 10
C. 20
D. Compilation error

Correct Answer: B
Explanation: The ternary operator: condition ? valueIfTrue : valueIfFalse. Since a > 3 is true (5 > 3), b becomes 10.
Exam Trick: Ternary = inline if-else: cond ? trueVal : falseVal.


Q39: Which of these is true regarding the ‘==’ operator for objects (not primitives)?
A. Compares the contents of the objects
B. Compares object references (memory addresses)
C. Always returns true for different objects
D. Cannot be used on objects

Correct Answer: B
Explanation: For object references, == checks if both variables point to the exact same object in memory. Use .equals() to compare logical content/equality.
Exam Trick: == for objects → reference comparison; .equals() → content comparison (if overridden).


Q40: What’s wrong with this switch statement?
int x = 5;
switch(x) {
  case 1: System.out.println("one");
  case 2.5: System.out.println("two");
}

A. Nothing wrong
B. case 2.5 is invalid — switch on int cannot use a double/float label
C. Missing default
D. Missing break only

Correct Answer: B
Explanation: switch case labels must be compile-time constants of a type compatible with the switch expression (int/char/byte/short/String/enum). A double literal like 2.5 is not allowed.
Exam Trick: switch supports: byte, short, char, int, their wrappers, String, and enum — NOT float/double/long.


Q41: What is the output of the following code?
for(int i=0;i<3;i++){
  if(i==1) continue;
  System.out.print(i);
}

A. 012
B. 02
C. 01
D. Infinite loop

Correct Answer: B
Explanation: When i==1, continue skips the print statement and jumps to the increment/condition check. So i=0 prints ‘0’, i=1 is skipped, i=2 prints ‘2’ → output ’02’.
Exam Trick: continue skips the rest of the CURRENT iteration’s body only, loop continues normally afterward.


Q42: A labeled break statement is used to:
A. Exit only the innermost loop
B. Exit a specifically labeled outer loop from within nested loops
C. Cause a compile error
D. Restart the labeled loop

Correct Answer: B
Explanation: Labeled break allows breaking out of an outer loop directly from inside a nested inner loop, by referencing the outer loop’s label.
Exam Trick: outer: for(…) { for(…) { break outer; } } — jumps clean out of both loops.


Q43: What is the output of the following code?
try {
  int[] arr = new int[2];
  System.out.println(arr[5]);
} catch(ArithmeticException e) {
  System.out.println("Arithmetic");
} catch(ArrayIndexOutOfBoundsException e) {
  System.out.println("ArrayIndex");
}

A. Arithmetic
B. ArrayIndex
C. Compilation error
D. Nothing prints

Correct Answer: B
Explanation: Accessing index 5 of a 2-element array throws ArrayIndexOutOfBoundsException, which is caught by the matching catch block specific to that exception type.
Exam Trick: Multiple catch blocks: Java matches the FIRST catch block whose type matches the thrown exception, top to bottom.


Q44: What’s wrong with the following code?
try {
  // code
} catch(Exception e) {
  // generic
} catch(ArithmeticException e) {
  // specific
}

A. No error
B. Compilation error — subclass exception catch block placed after its superclass catch block is unreachable
C. Runtime exception only
D. ArithmeticException must come first always

Correct Answer: B
Explanation: Java requires more specific exception catch blocks to appear before more general ones. Since ArithmeticException is a subclass of Exception, placing Exception first makes the second block unreachable — compile error.
Exam Trick: Order catch blocks: Most Specific → Most General (child classes before parent classes).


Q45: Which of these is an unchecked exception?
A. IOException
B. SQLException
C. NullPointerException
D. ClassNotFoundException

Correct Answer: C
Explanation: NullPointerException extends RuntimeException, making it unchecked (compiler doesn’t force handling). IOException, SQLException, and ClassNotFoundException are all checked exceptions.
Exam Trick: Unchecked = RuntimeException and its subclasses + Error. Checked = everything else under Exception.


Q46: How is the assert statement enabled at runtime in Java (it’s disabled by default)?
A. It’s always enabled
B. Using the -ea (or -enableassertions) JVM flag
C. Using the -assert flag
D. Cannot be enabled, only used in IDE

Correct Answer: B
Explanation: Assertions are disabled by default for performance. Run with ‘java -ea ClassName’ to enable them at runtime.
Exam Trick: -ea = enable assertions. Without it, assert statements are silently skipped.


Q47: What is the output of the following code?
String s = "hello";
s.concat(" world");
System.out.println(s);

A. hello world
B. hello
C. world
D. Compilation error

Correct Answer: B
Explanation: Since String is immutable, concat() returns a NEW string but doesn’t modify the original. Since the result wasn’t reassigned to s, s remains “hello”.
Exam Trick: Always assign the result back: s = s.concat(” world”); — immutability classic trap.


Q48: What is the output of the following code?
String s1 = new String("Java");
String s2 = "Java";
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));

A. true, true
B. false, true
C. true, false
D. false, false

Correct Answer: B
Explanation: ‘new String()’ always creates a new object on the heap (outside the string pool), so s1 != s2 by reference (false). But .equals() compares content, which is identical (true).
Exam Trick: ‘new String()’ always makes a new object → == is false; .equals() compares values → true.


Q49: Which class should be used for frequent string concatenation in a loop for better performance?
A. String
B. StringBuilder
C. StringTokenizer
D. StringJoiner only

Correct Answer: B
Explanation: StringBuilder is mutable and efficient for repeated modifications (no new object created each time), unlike String which creates a new object on every concatenation.
Exam Trick: Loop + lots of concatenation → use StringBuilder (or StringBuffer if thread-safety needed).


Q50: Which class provides buffered reading for efficient character input?
A. FileReader
B. BufferedReader
C. InputStreamReader
D. DataInputStream

Correct Answer: B
Explanation: BufferedReader wraps another Reader (e.g., FileReader) to provide efficient reading with an internal buffer, plus convenience methods like readLine().
Exam Trick: BufferedReader = wraps a Reader for speed + readLine() convenience.


Q51: What is the output of the following code?
System.out.printf("%d-%s%n", 10, "abc");
A. 10-abc
B. %d-%s
C. Compilation error
D. 10abc

Correct Answer: A
Explanation: printf uses format specifiers: %d for integer (10), %s for string (“abc”), %n for platform-independent newline. Output: 10-abc
Exam Trick: %d=int, %f=float/double, %s=string, %c=char, %n=newline.


Q52: Which exception is thrown by Integer.parseInt() when given an invalid string like “abc”?
A. NumberFormatException
B. ParseException
C. IllegalArgumentException only (no subtype)
D. InputMismatchException

Correct Answer: A
Explanation: NumberFormatException (a subclass of IllegalArgumentException) is thrown when the string cannot be parsed as a valid number.
Exam Trick: parseInt(“abc”) → NumberFormatException — common runtime trap when reading user input.


Q53: What does the wildcard ‘? extends T’ represent in generics?
A. An unbounded wildcard
B. An upper-bounded wildcard — accepts T or any subtype of T
C. A lower-bounded wildcard
D. A type that must be exactly T

Correct Answer: B
Explanation: ‘? extends T’ is an upper bound: it accepts T itself or any of its subclasses. It’s typically used for read-only access (producer) — you can read as T but cannot safely add elements (except null).
Exam Trick: PECS rule: Producer Extends, Consumer Super — ‘? extends’ for reading, ‘? super’ for writing.


Q54: What’s wrong with the following code?
List list = new ArrayList<>();
list.add("A");
list.add(10); // line X

A. No error, compiles fine
B. Compile error at line X — type mismatch, expects String not int
C. Runtime ClassCastException
D. Auto-boxes to String

Correct Answer: B
Explanation: The list is generically typed as List, so only String objects (or null) can be added. Adding an int causes a compile-time type mismatch error, which generics specifically prevent.
Exam Trick: Generics catch this at COMPILE time — that’s the whole point of using them over raw types.


Q55: Which collection maintains elements in a sorted order automatically?
A. HashMap
B. TreeMap
C. LinkedHashMap
D. HashSet

Correct Answer: B
Explanation: TreeMap implements SortedMap/NavigableMap and keeps keys sorted according to natural ordering or a provided Comparator. TreeSet does the same for Sets.
Exam Trick: Tree-prefixed collections (TreeMap, TreeSet) = sorted order, backed by a Red-Black tree.


Q56: Which collection class is synchronized (thread-safe) by default among legacy classes?
A. ArrayList
B. HashMap
C. Vector
D. HashSet

Correct Answer: C
Explanation: Vector (and Hashtable) are legacy classes that are synchronized by default. Modern collections like ArrayList and HashMap are NOT synchronized (use Collections.synchronizedList() or concurrent collections instead).
Exam Trick: Legacy + synchronized: Vector, Hashtable, Stack. Modern + unsynchronized: ArrayList, HashMap.


Q57: What is the output of the following code?
Map m = new HashMap<>();
m.put("a",1);
m.put("a",2);
System.out.println(m.get("a"));

A. 1
B. 2
C. null
D. Compilation error

Correct Answer: B
Explanation: HashMap keys are unique — putting a value with an existing key overwrites (replaces) the previous value. So m.get(“a”) returns 2.
Exam Trick: put() with a duplicate key replaces the old value and returns the OLD value (not used here).


Q58: Which type of inner class is declared static and does NOT need an outer class instance to be instantiated?
A. Member inner class
B. Static nested class
C. Local inner class
D. Anonymous inner class

Correct Answer: B
Explanation: A static nested class behaves like a top-level class but is namespaced inside the outer class; it can be instantiated without an outer instance and cannot access non-static outer members directly.
Exam Trick: static nested class = like a regular class, just packaged inside another class — no outer instance needed.


Q59: How do you instantiate a (non-static) member inner class from outside the outer class?
A. new Inner()
B. new Outer.Inner()
C. outerObject.new Inner()
D. new Outer().Inner()

Correct Answer: C
Explanation: A non-static inner class instance is tied to an outer instance. Syntax: Outer outerObj = new Outer(); Outer.Inner innerObj = outerObj.new Inner();
Exam Trick: Non-static inner class needs: outerRef.new InnerClass() syntax.


Q60: What is the correct thread lifecycle state sequence (typical) in Java?
A. New → Runnable → Running → (Blocked/Waiting) → Terminated
B. New → Terminated → Runnable
C. Runnable → New → Terminated
D. Blocked → New → Running

Correct Answer: A
Explanation: A thread starts in New state, moves to Runnable after start(), may go to Running when scheduled, can transition to Blocked/Waiting/Timed-Waiting, and finally reaches Terminated (dead) after completion.
Exam Trick: Thread states: NEW → RUNNABLE → (BLOCKED/WAITING/TIMED_WAITING) → TERMINATED.


Q61: Which keyword is used to ensure only one thread can execute a block of code at a time?
A. volatile
B. synchronized
C. transient
D. atomic

Correct Answer: B
Explanation: ‘synchronized’ creates a mutually exclusive lock around a method or block, ensuring only one thread executes it at a time for a given object/lock.
Exam Trick: synchronized = mutual exclusion lock; prevents race conditions on shared data.


Q62: What does the volatile keyword guarantee in Java?
A. Atomicity of compound operations like i++
B. Visibility of changes to a variable across threads (reads/writes go to main memory)
C. Thread synchronization equivalent to synchronized
D. Faster execution always

Correct Answer: B
Explanation: volatile ensures that reads/writes to the variable are visible to all threads immediately (no caching in thread-local memory), but it does NOT make compound operations (like i++) atomic.
Exam Trick: volatile = visibility, NOT atomicity. For atomic compound ops use AtomicInteger or synchronized.


Q63: What is the purpose of the ‘super’ keyword?
A. To call a static method only
B. To refer to the parent class’s members/constructor
C. To create a new object
D. To declare a class final

Correct Answer: B
Explanation: ‘super’ is used to access parent class methods/fields hidden by the subclass, or to explicitly call the parent class constructor via super(…).
Exam Trick: super.method() / super.field / super(args) — always refers to the immediate parent class.


Q64: What’s wrong with the following code?
abstract class Shape {
  abstract void draw();
}
public class Test {
  public static void main(String[] a){
    Shape s = new Shape(); // line X
  }
}

A. No error
B. Compile error at line X — cannot instantiate an abstract class
C. Runtime exception
D. draw() must be called before instantiation

Correct Answer: B
Explanation: Abstract classes cannot be instantiated directly with ‘new’ because they may have unimplemented abstract methods. You must instantiate a concrete subclass instead.
Exam Trick: Abstract class = blueprint only, ‘new AbstractClass()’ is always a compile error.


Q65: What is the output of the following code?
int a = 10, b = 3;
System.out.println(a / b);
System.out.println((double)a / b);

A. 3, 3.0
B. 3, 3.333333333333333
C. 3.33, 3.33
D. Compilation error

Correct Answer: B
Explanation: Integer division (a/b where both are int) truncates the decimal: 10/3 = 3. Casting a to double before division forces floating-point division: 10.0/3 ≈ 3.333333333333333.
Exam Trick: int / int = int (truncated). Cast at least one operand to double/float for decimal precision.


Q66: What is the output of the following code?
int i = 0;
while(i < 5) {
  if(i == 3) break;
  System.out.print(i);
  i++;
}

A. 01234
B. 0123
C. 012
D. Infinite loop

Correct Answer: B
Explanation: Loop prints 0,1,2 then when i==3, break exits the loop before printing 3. Since break occurs before the print statement runs at i=3, the output is the digits 0,1,2 concatenated together.
Exam Trick: Trace carefully: break exits BEFORE the print statement executes when i==3, so 3 is never printed. (Correct output: 012)


Q67: If a finally block contains a return statement, what happens to a return value set in the try block?
A. The try block’s return value is always used
B. The finally block’s return value overrides the try block’s return value
C. Compilation error
D. Both values are returned

Correct Answer: B
Explanation: If finally has its own return statement, it overrides any return from try/catch — this is considered bad practice but is legal and a classic interview/tricky question.
Exam Trick: Avoid returning from finally — it silently swallows the try block’s return/exception, a common bug source.


Q68: What is the output of the following code?
String s = "Java Programming";
System.out.println(s.substring(5));

A. Java
B. Programming
C. Java
D. gramming

Correct Answer: B
Explanation: substring(5) returns the substring starting at index 5 (0-based) to the end. “Java Programming”[5] = ‘P’ (after ‘Java ‘), giving “Programming”.
Exam Trick: substring(beginIndex) → from beginIndex to end; substring(begin,end) → end is exclusive.


Q69: What is the output of the following code?
System.out.println(String.format("%05d", 42));
A. 42
B. 00042
C. 42
D. 42000

Correct Answer: B
Explanation: %05d means: integer field, minimum width 5, zero-padded on the left. 42 becomes 00042.
Exam Trick: %05d = zero-pad to width 5; %5d (no 0) = space-pad instead.

ADVANCED LEVEL


Q70: What is the difference between Iterator and ListIterator?
A. No difference
B. ListIterator can traverse only forward; Iterator can traverse both directions
C. ListIterator can traverse both forward and backward and supports add/set; Iterator is forward-only and supports only remove
D. Iterator works only on Lists

Correct Answer: C
Explanation: ListIterator (available only for List implementations) extends Iterator with bidirectional traversal and add()/set() capability. Iterator (works on any Collection) is forward-only with just remove().
Exam Trick: Iterator = forward + remove only. ListIterator = forward+backward + add/set/remove (List-only).


Q71: What’s wrong with the following code?
class Outer {
  private int x = 5;
  class Inner {
    void show(){ System.out.println(x); }
  }
}

A. Compile error — Inner cannot access private member x
B. No error — inner classes can access outer class private members
C. Runtime error
D. x must be declared protected

Correct Answer: B
Explanation: Non-static inner classes have an implicit reference to their enclosing instance and CAN access all members of the outer class, including private ones — a unique feature of inner classes in Java.
Exam Trick: Inner classes break normal private encapsulation w.r.t. their own enclosing class — a frequently tested ‘gotcha’.


Q72: Can a protected member be accessed from a subclass in a DIFFERENT package via an instance of the parent class (not the subclass)?
A. Yes, always
B. No — protected access via inheritance in a different package only allows access through the subclass type/reference, not via parent type reference
C. Only if static
D. Only inside main()

Correct Answer: B
Explanation: protected access across packages is restricted: a subclass in a different package can access an inherited protected member only through references of its own type (or subtype), not by creating/accessing a parent class instance directly.
Exam Trick: Cross-package protected access rule: ‘use through subclass reference only’, not via the parent class reference.


Q73: What is the output of the following code?
class A {
  static void greet(){ System.out.println("A static"); }
}
class B extends A {
  static void greet(){ System.out.println("B static"); }
}
public class Test {
  public static void main(String[] args){
    A a = new B();
    a.greet();
  }
}

A. A static
B. B static
C. Compilation error
D. Runtime exception

Correct Answer: A
Explanation: Static methods are resolved using the REFERENCE TYPE at compile time (static/early binding) — this is called method HIDING, not overriding. Since ‘a’ is declared type A, A’s greet() runs.
Exam Trick: Static methods = hidden, not overridden. Resolved by reference type, NOT object type (opposite of instance method overriding).


Q74: Why can’t constructors be declared ‘final’, ‘static’, or ‘abstract’?
A. Constructors are not inherited (final/abstract irrelevant) and are tied to instance creation, not the class itself (static irrelevant)
B. It’s a JVM limitation with no logical reason
C. Constructors can be static in interfaces
D. They actually can be final in some cases

Correct Answer: A
Explanation: Constructors aren’t inherited so ‘final’/’abstract’ (which relate to overriding) make no sense; they’re invoked per-instance during object creation, so ‘static’ (class-level, no instance) is incompatible.
Exam Trick: Constructor modifier rule: only access modifiers (public/private/protected/default) are allowed — no final/static/abstract/synchronized.


Q75: What is the output of the following code?
class A {
  A(){ System.out.println("A constructor"); show(); }
  void show(){ System.out.println("A show"); }
}
class B extends A {
  int x = 10;
  void show(){ System.out.println("B show, x="+x); }
}
public class Test {
  public static void main(String[] args){
    new B();
  }
}

A. A constructor, A show
B. A constructor, B show, x=10
C. A constructor, B show, x=0
D. B show, A constructor

Correct Answer: C
Explanation: Parent constructor runs first and calls the overridden show() (dynamic dispatch picks B’s version since the object IS a B). But B’s field x hasn’t been initialized yet at that point (field initializers run AFTER the super() call completes), so x is still its default value 0.
Exam Trick: Classic trap: calling overridable methods from a constructor — subclass fields aren’t initialized yet, so you get default values, not the assigned ones.


Q76: What is the output of the following code?
Integer a = 127, b = 127;
Integer c = 200, d = 200;
System.out.println(a==b);
System.out.println(c==d);

A. true, true
B. false, false
C. true, false
D. false, true

Correct Answer: C
Explanation: Java caches Integer objects from -128 to 127 (Integer Cache). Values within this range share the same cached object (a==b is true). Values outside (like 200) create new objects each time, so c==d is false.
Exam Trick: Integer caching range: -128 to 127 inclusive. Beyond this, == on wrapper objects is unreliable — always use .equals().


Q77: What is the output of the following code?
System.out.println(1 + 2 + "3");
System.out.println("1" + 2 + 3);

A. 33, 33
B. 123, 123
C. 33, 123
D. 123, 33

Correct Answer: C
Explanation: Left-to-right evaluation: 1+2+”3″ → (1+2)=3, then 3+”3″=”33″. For “1”+2+3 → (“1″+2)=”12”, then “12”+3=”123″. Output: 33 then 123.
Exam Trick: + is left-associative: once a String appears, everything after becomes string concatenation, but numeric ops BEFORE the string still happen as math.


Q78: What is the output of the following code?
outer:
for(int i=0;i<3;i++){
  for(int j=0;j<3;j++){
    if(j==1) continue outer;
    System.out.print(i+""+j);
  }
}

A. 001020
B. 000102101112202122
C. 00 10 20
D. Infinite loop

Correct Answer: A
Explanation: Labeled continue jumps to the next iteration of the OUTER loop, skipping remaining inner iterations. For each i, only j=0 prints before continue outer triggers at j=1: prints ’00’,’10’,’20’ → concatenated: 001020.
Exam Trick: Trace each outer iteration: i=0,j=0→prints ’00’; j=1→continue outer (skip j=2, go to i=1). i=1,j=0→’10’; j=1→continue outer. i=2,j=0→’20’. Output = 001020.


Q79: Why does the following code not compile?
final int x;
if(someCondition()) {
  x = 5;
}
System.out.println(x);

A. It compiles fine
B. Compiler cannot guarantee x is definitely assigned in all paths before use (the else path leaves x unassigned)
C. x must be initialized at declaration always
D. final cannot be used with int

Correct Answer: B
Explanation: Java requires ‘definite assignment’ for final local variables before use. Since there’s no else branch, the compiler cannot prove x is always assigned, so println(x) is a compile error.
Exam Trick: Definite Assignment Rule: a blank final variable must be assigned along EVERY possible code path before it’s read.


Q80: What is the output of the following code?
public class Test {
  static int test(){
    try { return 1; }
    finally { return 2; }
  }
  public static void main(String[] a){
    System.out.println(test());
  }
}

A. 1
B. 2
C. Compilation error
D. 1 then 2

Correct Answer: B
Explanation: When finally contains a return, it overrides/replaces any return from the try block — the method returns 2, and the try’s ‘return 1’ is discarded entirely.
Exam Trick: finally’s return ALWAYS wins over try/catch’s return — dangerous pattern, frequently tested.


Q81: What happens if an exception is thrown inside a finally block while another exception is already propagating from the try block?
A. Both exceptions are reported together
B. Only the original exception from try is reported
C. The exception from finally suppresses/replaces the original exception
D. Compilation error

Correct Answer: C
Explanation: If finally itself throws an exception, it overrides (replaces) the exception that was propagating from try/catch — the original gets lost unless explicitly handled (e.g. via Throwable.addSuppressed in try-with-resources).
Exam Trick: An exception thrown in finally always ‘wins’ and hides the original exception — a real-world bug source.


Q82: In a try-with-resources statement, in what order are multiple resources closed?
A. In the order declared (first to last)
B. In reverse order of declaration (last declared, first closed)
C. Random order
D. Only the last resource is closed

Correct Answer: B
Explanation: Resources in try-with-resources are closed automatically in the reverse order of their declaration, similar to a stack (LIFO).
Exam Trick: try-with-resources closing order = LIFO (reverse declaration order).


Q83: What is the output of the following code?
StringBuilder sb = new StringBuilder("abc");
sb.append("def").insert(0,"X").reverse();
System.out.println(sb);

A. Xabcdef
B. fedcbaX
C. fedcbaX reversed again
D. XabcdefX

Correct Answer: B
Explanation: Step by step: append(“def”) → “abcdef”; insert(0,”X”) → “Xabcdef”; reverse() → “fedcbaX”. Methods are chained left to right, each operating on the cumulative result.
Exam Trick: StringBuilder methods are chainable and mutate the SAME object — trace operations strictly left to right.


Q84: Why is String considered immutable and used heavily in the String Constant Pool — what’s the main design benefit?
A. It makes Strings faster to create always
B. Security, thread-safety, and safe sharing/caching of String literals (hashcode caching, safe as HashMap keys, security for class loading)
C. It reduces JVM startup time
D. No real benefit, it’s a legacy decision

Correct Answer: B
Explanation: Immutability allows safe sharing of String objects (pool reuse), thread-safety without synchronization, caching of hashcode for fast HashMap lookups, and prevents security risks like mutation of class names/file paths passed as Strings.
Exam Trick: Common interview answer: Security + Synchronization (thread-safety) + String Pool sharing + HashCode caching.


Q85: What is the output of the following code?
System.out.printf("%.2f%n", 5.0/3);
A. 1.66
B. 1.67
C. 1.6666666666666667
D. 1.7

Correct Answer: B
Explanation: 5.0/3 ≈ 1.6666666666… The format specifier %.2f rounds to 2 decimal places using standard rounding (HALF_UP-like behavior here), giving 1.67.
Exam Trick: %.2f rounds (not truncates) to 2 decimal places.


Q86: What’s the difference between DataInputStream/DataOutputStream and ObjectInputStream/ObjectOutputStream?
A. No difference
B. Data streams read/write primitive types in a machine-independent way; Object streams serialize/deserialize entire objects (must implement Serializable)
C. Data streams are for objects too
D. Object streams cannot write primitives

Correct Answer: B
Explanation: DataInputStream/DataOutputStream handle primitive data types (int, double, etc.) in a portable binary format. ObjectInputStream/ObjectOutputStream perform full object serialization, requiring the class to implement java.io.Serializable.
Exam Trick: Data streams = primitives. Object streams = whole objects (needs Serializable).


Q87: What is the output of the following code (ignoring exact insertion-order guarantees)?
Set s = new TreeSet<>();
s.add(5); s.add(1); s.add(3);
System.out.println(s);

A. [5, 1, 3]
B. [1, 3, 5]
C. [3, 1, 5]
D. Compilation error

Correct Answer: B
Explanation: TreeSet always maintains elements in natural sorted order (ascending for Integers by default), regardless of insertion order.
Exam Trick: TreeSet/TreeMap → always sorted on iteration. HashSet/HashMap → no guaranteed order. LinkedHashSet/LinkedHashMap → insertion order.


Q88: What happens if you use a mutable object as a key in a HashMap and then change its hashCode-affecting fields after insertion?
A. Nothing, HashMap handles it automatically
B. The entry may become unreachable/’lost’ because the bucket location is based on the OLD hashCode, but lookups recompute the hash from the CURRENT state
C. Compile-time error
D. The HashMap automatically re-hashes the changed key

Correct Answer: B
Explanation: HashMap stores entries based on the hashCode computed at insertion time. If a key’s fields used in hashCode() change afterward, get()/containsKey() using the new hashCode won’t find the entry in its (old) bucket — leading to a ‘lost’ entry.
Exam Trick: Golden rule: never use mutable objects (whose hashCode can change) as HashMap/HashSet keys.


Q89: What is the difference between fail-fast and fail-safe iterators?
A. No difference
B. Fail-fast throws ConcurrentModificationException on structural modification during iteration (e.g., ArrayList); fail-safe iterates over a clone/snapshot and allows modification (e.g., CopyOnWriteArrayList)
C. Fail-safe is always faster
D. Fail-fast is used only with Maps

Correct Answer: B
Explanation: Fail-fast iterators (most java.util collections like ArrayList, HashMap) detect concurrent structural changes via a modCount check and throw ConcurrentModificationException. Fail-safe iterators (java.util.concurrent collections) operate on a copy, avoiding this exception but possibly seeing stale data.
Exam Trick: Fail-fast = throws CME on modification mid-iteration. Fail-safe = works on a snapshot, no CME, may show stale data.


Q90: What’s wrong with the following code?
List list = Arrays.asList(1,2,3);
list.add(4); // line X

A. No error, works fine
B. Runtime UnsupportedOperationException at line X — Arrays.asList() returns a fixed-size list backed by the array
C. Compilation error
D. Returns a new list with 4 added

Correct Answer: B
Explanation: Arrays.asList() returns a fixed-size List backed directly by the array. Structural modification operations like add()/remove() are not supported and throw UnsupportedOperationException at runtime.
Exam Trick: Arrays.asList() → fixed-size view; set() works but add()/remove() throws UnsupportedOperationException.


Q91: What is the output of the following code?
public class Test {
  int x = 10;
  void method(){
    int y = 20;
    class Local {
      void show(){ System.out.println(x + " " + y); }
    }
    new Local().show();
  }
  public static void main(String[] a){
    new Test().method();
  }
}

A. 10 20
B. Compilation error — y must be final or effectively final
C. 20 10
D. 0 0

Correct Answer: A
Explanation: Local inner classes can access local variables of the enclosing method only if they are final or ‘effectively final’ (never reassigned after initialization) — here y is effectively final, so this compiles fine and prints ’10 20′.
Exam Trick: Local/anonymous inner classes require enclosing local variables to be final or effectively final (Java 8+).


Q92: What is an anonymous inner class typically used for?
A. Creating reusable named classes
B. Creating a one-time-use subclass/interface implementation inline, often for event handlers or simple Runnable/Comparator implementations
C. Defining static utility methods only
D. Replacing top-level classes entirely

Correct Answer: B
Explanation: Anonymous inner classes let you instantiate and define a class (extending a class or implementing an interface) in a single expression, useful for short, one-off implementations like listeners, Runnables, or Comparators (now often replaced by lambdas).
Exam Trick: Anonymous class = ‘new InterfaceOrClass() { …override methods… }’ — no name, instantiated immediately.


Q93: What is most likely (not guaranteed) about the output of the following code?
public class Test {
  public static void main(String[] a) throws Exception {
    Thread t1 = new Thread(()-> System.out.print("A"));
    Thread t2 = new Thread(()-> System.out.print("B"));
    t1.start(); t2.start();
  }
}

A. Always prints ‘AB’
B. Always prints ‘BA’
C. Output order is NOT guaranteed (could be AB or BA) — thread scheduling is non-deterministic
D. Compilation error

Correct Answer: C
Explanation: Once both threads are started, the JVM thread scheduler decides execution order, which is non-deterministic. The output could be ‘AB’ or ‘BA’ (or even interleaved differently with more output) depending on the run.
Exam Trick: Never assume a specific execution order for independently started threads unless explicit synchronization/join() is used.


Q94: What is a deadlock, and which classic conditions commonly lead to it?
A. When a thread runs forever doing useful work
B. A state where two or more threads are blocked forever, each waiting for a lock/resource held by the other (circular wait)
C. A thread that completes too fast
D. A compilation error in threaded code

Correct Answer: B
Explanation: Deadlock occurs when two or more threads each hold a lock the other needs, and neither can proceed — a circular waiting condition. Common cause: acquiring multiple locks in inconsistent order across threads.
Exam Trick: Avoid deadlock: always acquire multiple locks in the SAME consistent order across all threads.


Q95: What is the purpose of wait(), notify(), and notifyAll() in Java?
A. They belong to the Thread class for starting threads
B. They belong to Object class and are used for inter-thread communication within a synchronized block/method
C. They are used to stop a thread permanently
D. They replace the synchronized keyword

Correct Answer: B
Explanation: wait()/notify()/notifyAll() are defined in Object (not Thread) and must be called from within a synchronized context. wait() releases the lock and pauses the thread; notify()/notifyAll() wake up waiting thread(s).
Exam Trick: wait/notify/notifyAll live in Object class, not Thread — and MUST be called holding the object’s monitor (inside synchronized).


Q96: Can an interface have private methods in modern Java (Java 9+)?
A. No, never allowed
B. Yes — private methods (and private static methods) are allowed to share code between default/static methods within the interface
C. Only protected methods are allowed
D. Only public abstract methods are allowed ever

Correct Answer: B
Explanation: Since Java 9, interfaces can have private and private static methods, used internally to share common code between default and static methods without exposing it to implementing classes.
Exam Trick: Java 8 added default & static interface methods; Java 9 added private interface methods for internal reuse.


Q97: What’s wrong with overriding this method?
class A {
  void method() throws IOException { }
}
class B extends A {
  void method() throws SQLException { } // line X
}

A. No error
B. Compile error — an overriding method cannot throw a new/broader checked exception not declared (or a subtype of one declared) by the overridden method
C. SQLException is always allowed
D. IOException must be removed in B

Correct Answer: B
Explanation: An overriding method can throw the same checked exceptions, narrower (subclass) checked exceptions, fewer exceptions, or any unchecked exceptions — but NOT new/unrelated checked exceptions like SQLException when the parent only declares IOException.
Exam Trick: Override exception rule: same or narrower checked exceptions only (or none); unchecked exceptions are unrestricted.


Q98: You need a Map that preserves insertion order during iteration. Which should you choose?
A. HashMap
B. TreeMap
C. LinkedHashMap
D. Hashtable

Correct Answer: C
Explanation: LinkedHashMap maintains a doubly-linked list running through its entries, preserving insertion order (or optionally access order) during iteration, unlike HashMap (no order) or TreeMap (sorted order).
Exam Trick: HashMap=no order, TreeMap=sorted order, LinkedHashMap=insertion order — pick based on requirement.


Q99: What is the output of the following code?
System.out.println(5 & 3);
System.out.println(5 | 3);
System.out.println(5 ^ 3);

A. 1, 7, 6
B. 7, 1, 6
C. 1, 6, 7
D. 6, 7, 1

Correct Answer: A
Explanation: 5 = 101, 3 = 011 in binary. AND(&): 101&011=001=1. OR(|): 101|011=111=7. XOR(^): 101^011=110=6. Output: 1, 7, 6.
Exam Trick: Convert to binary first: AND keeps common 1s, OR combines all 1s, XOR keeps differing bits only.


Q100: Why is it recommended to implement Runnable (or Callable) instead of extending Thread directly when designing a multi-threaded task class?
A. Runnable is faster at runtime than Thread
B. Implementing Runnable keeps the class free to extend another class (since Java allows only single inheritance) and promotes separation of the ‘task’ from the ‘thread mechanism’ (better OOP design)
C. Extending Thread is not allowed in Java
D. Runnable provides automatic synchronization

Correct Answer: B
Explanation: Since a class can extend only one class but implement multiple interfaces, implementing Runnable leaves room to extend another class if needed, and decouples the task logic (what to run) from thread management (how to run it) — a cleaner, more reusable design.
Exam Trick: Best practice: ‘implements Runnable’ over ‘extends Thread’ — preserves inheritance flexibility + separates concerns.

MPSeDC GET Program 3.0 2026 – Exam-Oriented JAVA MCQ Questions
Scroll to top