Java Interview Questions and Answers for Freshers

The Java questions asked most in campus drives and technical rounds at service and product companies, each with the answer and a short explanation. Includes 'what does this code print?' questions.

  1. Q1. Which of these is NOT a primitive type in Java?

    • A. int
    • B. String
    • C. boolean
    • D. char
    Show answer

    Answer: B. String
    String is a class (an object type); the eight primitives are byte, short, int, long, float, double, char and boolean.

  2. Q2. What is the default value of an int field in a Java class?

    • A. 0
    • B. Garbage value
    • C. null
    • D. undefined
    Show answer

    Answer: A. 0
    Fields get default values: 0 for numbers, false for boolean, null for objects. Local variables have no default and must be initialised.

  3. Q3. Which keyword is used to inherit a class in Java?

    • A. super
    • B. inherits
    • C. extends
    • D. implements
    Show answer

    Answer: C. extends
    class B extends A. A class implements interfaces.

  4. Q4. How many classes can a Java class directly extend?

    • A. None
    • B. Two
    • C. Any number
    • D. One
    Show answer

    Answer: D. One
    Java has single inheritance for classes; use interfaces for multiple types.

  5. Q5. What does JVM stand for?

    • A. Joint Virtual Memory
    • B. Java Verified Module
    • C. Java Variable Method
    • D. Java Virtual Machine
    Show answer

    Answer: D. Java Virtual Machine
    The JVM runs compiled bytecode, which is why Java is 'write once, run anywhere'.

  6. Q6. Which method must every Java application have to start running?

    • A. public void start()
    • B. public static void main(String[] args)
    • C. public static run()
    • D. static int main()
    Show answer

    Answer: B. public static void main(String[] args)
    The JVM looks for public static void main(String[] args).

  7. Q7. What is the difference between == and equals() for Strings?

    • A. == compares references, equals() compares contents
    • B. equals() only works for numbers
    • C. They are the same
    • D. == compares contents, equals() compares references
    Show answer

    Answer: A. == compares references, equals() compares contents
    Two different String objects with the same text are equal() but not ==.

  8. Q8. Which collection does NOT allow duplicate elements?

    • A. ArrayList
    • B. HashSet
    • C. Vector
    • D. LinkedList
    Show answer

    Answer: B. HashSet
    A Set keeps unique elements.

  9. Q9. What happens when you access index 5 of an array of length 5?

    • A. It returns 0
    • B. It returns null
    • C. ArrayIndexOutOfBoundsException
    • D. Compile error
    Show answer

    Answer: C. ArrayIndexOutOfBoundsException
    Valid indexes are 0 to 4; Java checks bounds at run time.

  10. Q10. Which keyword prevents a method from being overridden?

    • A. static
    • B. const
    • C. private
    • D. final
    Show answer

    Answer: D. final
    A final method can't be overridden; a final class can't be extended.

  11. Q11. What is method overloading?

    • A. A child class redefining a parent method
    • B. Calling a method too many times
    • C. A method that returns many values
    • D. Same method name with different parameters in one class
    Show answer

    Answer: D. Same method name with different parameters in one class
    Overloading is resolved at compile time; overriding happens in subclasses and is resolved at run time.

  12. Q12. Which of these is a checked exception?

    • A. IOException
    • B. NullPointerException
    • C. ArithmeticException
    • D. ArrayIndexOutOfBoundsException
    Show answer

    Answer: A. IOException
    Checked exceptions must be caught or declared with throws; the others are RuntimeExceptions.

  13. Q13. Can an interface have a method with a body in Java 8 and later?

    • A. Only private methods
    • B. Yes, default and static methods
    • C. Only if the interface is abstract
    • D. No, never
    Show answer

    Answer: B. Yes, default and static methods
    Java 8 added default and static methods to interfaces.

  14. Q14. Why are Java Strings immutable?

    • A. Because they are primitives
    • B. For security, thread safety and the string pool
    • C. They are not immutable
    • D. To save typing
    Show answer

    Answer: B. For security, thread safety and the string pool
    Immutable strings can be safely shared and cached in the string pool.

  15. Q15. Which class should you use to build a long string inside a loop?

    • A. StringBuilder
    • B. Character
    • C. String
    • D. Scanner
    Show answer

    Answer: A. StringBuilder
    StringBuilder appends without creating a new object each time.

  16. Q16. What does the static keyword mean for a field?

    • A. The field is stored on the stack
    • B. The field is private
    • C. One copy is shared by all objects of the class
    • D. The value can never change
    Show answer

    Answer: C. One copy is shared by all objects of the class
    Static members belong to the class, not to individual objects.

  17. Q17. Which access modifier makes a member visible only inside its own class?

    • A. protected
    • B. private
    • C. default (no modifier)
    • D. public
    Show answer

    Answer: B. private
    private is the most restrictive; protected adds subclasses and the package.

  18. Q18. What is the time complexity of get(key) in a HashMap on average?

    • A. O(n log n)
    • B. O(1)
    • C. O(log n)
    • D. O(n)
    Show answer

    Answer: B. O(1)
    Hashing finds the bucket directly; worst case with many collisions is slower.

  19. Q19. What is garbage collection in Java?

    • A. Removing duplicate elements from a list
    • B. Automatic freeing of objects that are no longer referenced
    • C. Clearing the console
    • D. Deleting unused source files
    Show answer

    Answer: B. Automatic freeing of objects that are no longer referenced
    The JVM reclaims memory automatically; there is no delete in Java.

  20. Q20. Which keyword refers to the current object inside a method?

    • A. super
    • B. current
    • C. self
    • D. this
    Show answer

    Answer: D. this
    this.name = name; assigns the parameter to the field.

  21. Q21. What is the parent class of every class in Java?

    • A. Main
    • B. Class
    • C. Base
    • D. Object
    Show answer

    Answer: D. Object
    Every class extends java.lang.Object directly or indirectly.

  22. Q22. Which of these can NOT be instantiated with new?

    • A. A class with a private field
    • B. A class with static methods
    • C. A final class
    • D. An abstract class
    Show answer

    Answer: D. An abstract class
    Abstract classes exist to be extended; create objects of their concrete subclasses.

  23. Q23. What does this code print?

    int a = 5, b = 2;
    System.out.println(a / b);
    • A. 2
    • B. 3
    • C. 2.0
    • D. 2.5
    Show answer

    Answer: A. 2
    Both operands are int, so / does integer division and drops the .5.

  24. Q24. What does this code print?

    System.out.println("" + 10 + 20);
    • A. Error
    • B. 10 20
    • C. 1020
    • D. 30
    Show answer

    Answer: C. 1020
    The String comes first, so + joins text: "" + 10 + 20 = "1020".

  25. Q25. What does this code print?

    System.out.println(10 + 20 + "Java");
    • A. 1020Java
    • B. Java30
    • C. Java1020
    • D. 30Java
    Show answer

    Answer: D. 30Java
    Evaluated left to right: 10 + 20 = 30 first, then joined with "Java".

  26. Q26. What does this code print?

    String a = "hi";
    String b = new String("hi");
    System.out.println((a == b) + " " + a.equals(b));
    • A. true false
    • B. false true
    • C. false false
    • D. true true
    Show answer

    Answer: B. false true
    new String creates a different object, so == is false; equals() compares the text.

  27. Q27. What does this code print?

    int x = 5;
    int y = x++;
    System.out.println(y + " " + x);
    • A. 5 5
    • B. 6 6
    • C. 6 5
    • D. 5 6
    Show answer

    Answer: D. 5 6
    x++ gives the old value (5) and then increments x to 6.

  28. Q28. What does this code print?

    System.out.println("abc".charAt(1));
    • A. a
    • B. ab
    • C. b
    • D. Error
    Show answer

    Answer: C. b
    charAt counts from 0: index 1 is 'b'.

  29. Q29. What does this code print?

    int[] a = {1, 2, 3};
    System.out.println(a.length);
    • A. Error
    • B. 2
    • C. 3
    • D. 4
    Show answer

    Answer: C. 3
    length is a field for arrays: {1, 2, 3} has 3 elements.

  30. Q30. What does this code print?

    int n = 2;
    switch (n) {
        case 1: System.out.print("One ");
        case 2: System.out.print("Two ");
        case 3: System.out.print("Three"); break;
        default: System.out.print("Default");
    }
    • A. Two Three
    • B. Two Three Default
    • C. Default
    • D. Two
    Show answer

    Answer: A. Two Three
    There is no break after case 2, so execution falls through into case 3, which does break.

  31. Q31. What does this code print?

    java.util.List<Integer> list = new java.util.ArrayList<>(java.util.List.of(1, 2, 3));
    list.remove(1);
    System.out.println(list);
    • A. [1, 3]
    • B. [1, 2]
    • C. [3]
    • D. [2, 3]
    Show answer

    Answer: A. [1, 3]
    remove(1) with an int removes the element at index 1 (the value 2).

  32. Q32. What does this code print?

    class Parent { String name() { return "Parent"; } }
    class Child extends Parent { String name() { return "Child"; } }
    public class Main {
        public static void main(String[] args) {
            Parent p = new Child();
            System.out.println(p.name());
        }
    }
    • A. Child
    • B. Parent
    • C. Error
    • D. ParentChild
    Show answer

    Answer: A. Child
    The object is a Child, so the overridden method runs (runtime polymorphism).

  33. Q33. What does this code print?

    public class Main {
        static String f() {
            try { return "done"; }
            finally { System.out.print("finally "); }
        }
        public static void main(String[] args) {
            System.out.println(f());
        }
    }
    • A. finally
    • B. Error
    • C. done
    • D. finally done
    Show answer

    Answer: D. finally done
    finally runs before the method returns, even when try has a return.

  34. Q34. What does this code print?

    class Counter {
        static int count = 0;
        Counter() { count++; }
    }
    public class Main {
        public static void main(String[] args) {
            new Counter();
            new Counter();
            System.out.println(Counter.count);
        }
    }
    • A. 1
    • B. 0
    • C. 3
    • D. 2
    Show answer

    Answer: D. 2
    static count is shared by every Counter object, and two were created.

  35. Q35. What does this code print?

    public class Main {
        static void change(int v) { v = 20; }
        public static void main(String[] args) {
            int x = 10;
            change(x);
            System.out.println(x);
        }
    }
    • A. 10
    • B. 0
    • C. Error
    • D. 20
    Show answer

    Answer: A. 10
    Java passes a copy of the int value; changing it inside the method doesn't affect x.

  36. Q36. What does this code print?

    public class Main {
        static void change(int[] a) { a[0] = 99; }
        public static void main(String[] args) {
            int[] arr = {1, 2};
            change(arr);
            System.out.println(arr[0]);
        }
    }
    • A. 0
    • B. 99
    • C. 1
    • D. Error
    Show answer

    Answer: B. 99
    The array reference is copied, but it points to the same array, so the change is visible.

  37. Q37. What does this code print?

    String s = "java";
    String t = s.toUpperCase();
    System.out.println(t + " " + s);
    • A. JAVA JAVA
    • B. JAVA java
    • C. java java
    • D. Java java
    Show answer

    Answer: B. JAVA java
    toUpperCase returns a new String; s itself never changes.

  38. Q38. What does this code print?

    for (int i = 0; i < 3; i++) System.out.print(i + (i < 2 ? " " : ""));
    • A. 1 2
    • B. 0 1 2 3
    • C. 0 1 2
    • D. 1 2 3
    Show answer

    Answer: C. 0 1 2
    The loop prints while i < 3: 0, 1, 2.

  39. Q39. What does this code print?

    System.out.println(5.0 / 0);
    • A. NaN
    • B. ArithmeticException
    • C. 0
    • D. Infinity
    Show answer

    Answer: D. Infinity
    Dividing a double by zero gives Infinity; only integer division by zero throws.

  40. Q40. What does this code print?

    java.util.Map<String, Integer> m = new java.util.TreeMap<>();
    m.put("b", 2);
    m.put("a", 1);
    System.out.println(m);
    • A. {b=2, a=1}
    • B. [a, b]
    • C. Error
    • D. {a=1, b=2}
    Show answer

    Answer: D. {a=1, b=2}
    A TreeMap keeps its keys sorted.

  41. Q41. What is the size of an int in Java?

    • A. 64 bits
    • B. Depends on the machine
    • C. 16 bits
    • D. 32 bits
    Show answer

    Answer: D. 32 bits
    Java fixes primitive sizes on every platform; long is 64 bits.

  42. Q42. What is autoboxing?

    • A. Automatic memory allocation
    • B. Automatic conversion between a primitive and its wrapper class
    • C. Converting a String to char[]
    • D. Packing classes into a JAR
    Show answer

    Answer: B. Automatic conversion between a primitive and its wrapper class
    int → Integer when adding to an ArrayList<Integer>.

  43. Q43. Which collection keeps keys in sorted order?

    • A. HashMap
    • B. TreeMap
    • C. LinkedHashMap
    • D. Hashtable
    Show answer

    Answer: B. TreeMap
    LinkedHashMap keeps insertion order; HashMap keeps no order.

  44. Q44. What is the difference between ArrayList and LinkedList?

    • A. ArrayList can't grow
    • B. ArrayList gives fast random access; LinkedList gives fast inserts/removes at the ends
    • C. LinkedList is always faster
    • D. They are identical
    Show answer

    Answer: B. ArrayList gives fast random access; LinkedList gives fast inserts/removes at the ends
    ArrayList is backed by an array; LinkedList by doubly linked nodes.

  45. Q45. What does the transient keyword do?

    • A. Deletes a field after use
    • B. Makes a field thread-safe
    • C. Excludes a field from serialization
    • D. Makes a field constant
    Show answer

    Answer: C. Excludes a field from serialization
    Used for passwords or derived values.

  46. Q46. What does the volatile keyword guarantee?

    • A. Reads and writes go to main memory so all threads see the latest value
    • B. The variable can't change
    • C. Faster arithmetic
    • D. The variable is private
    Show answer

    Answer: A. Reads and writes go to main memory so all threads see the latest value
    It doesn't make compound operations like count++ atomic.

  47. Q47. What does the synchronized keyword do?

    • A. Starts a new thread
    • B. Pauses all threads
    • C. Lets only one thread run the block or method on the same lock at a time
    • D. Makes code run faster
    Show answer

    Answer: C. Lets only one thread run the block or method on the same lock at a time
    Prevents race conditions.

  48. Q48. How do you create a thread in Java?

    • A. Extend Thread or implement Runnable (or use an ExecutorService)
    • B. Call new Process()
    • C. Threads can't be created
    • D. Use the async keyword
    Show answer

    Answer: A. Extend Thread or implement Runnable (or use an ExecutorService)
    Call start(), not run(), to begin a new thread.

  49. Q49. What is the difference between Comparable and Comparator?

    • A. They are the same
    • B. Comparable sorts in reverse
    • C. Comparator is only for strings
    • D. Comparable defines natural order inside the class; Comparator defines order outside it
    Show answer

    Answer: D. Comparable defines natural order inside the class; Comparator defines order outside it
    compareTo(other) vs compare(a, b).

  50. Q50. What is the difference between throw and throws?

    • A. They are the same
    • B. throws raises an exception
    • C. throw is for checked exceptions only
    • D. throw raises an exception; throws declares that a method may raise one
    Show answer

    Answer: D. throw raises an exception; throws declares that a method may raise one
    throw new IOException(); void read() throws IOException.

  51. Q51. What is a lambda expression in Java?

    • A. A type of loop
    • B. A short way to implement a functional interface
    • C. A variable that can't change
    • D. A class without methods
    Show answer

    Answer: B. A short way to implement a functional interface
    (a, b) -> a + b.

  52. Q52. What is a functional interface?

    • A. An interface that extends Function
    • B. A class with functions only
    • C. An interface with no methods
    • D. An interface with exactly one abstract method
    Show answer

    Answer: D. An interface with exactly one abstract method
    Runnable, Comparator and Predicate are examples.

  53. Q53. What does Optional help avoid?

    • A. Compile errors
    • B. Memory leaks
    • C. NullPointerException from missing values
    • D. Infinite loops
    Show answer

    Answer: C. NullPointerException from missing values
    Optional.ofNullable(x).orElse(default).

  54. Q54. What is the Stream API used for?

    • A. Processing collections with operations like filter, map and reduce
    • B. Network streaming of video
    • C. Reading files only
    • D. Creating threads
    Show answer

    Answer: A. Processing collections with operations like filter, map and reduce
    list.stream().filter(...).collect(...).

  55. Q55. What is the difference between JDK, JRE and JVM?

    • A. They are the same
    • B. JDK has tools to develop; JRE has what's needed to run; JVM executes bytecode
    • C. JVM includes the JDK
    • D. JRE is used to compile code
    Show answer

    Answer: B. JDK has tools to develop; JRE has what's needed to run; JVM executes bytecode
    JDK ⊃ JRE ⊃ JVM.

  56. Q56. What happens if hashCode() is not overridden along with equals()?

    • A. equals() stops working
    • B. Equal objects may not be found in HashMap or HashSet
    • C. The program won't compile
    • D. Nothing at all
    Show answer

    Answer: B. Equal objects may not be found in HashMap or HashSet
    Equal objects must have equal hash codes.

  57. Q57. What is a static block?

    • A. A block of constants
    • B. A synchronized block
    • C. Code that runs once when the class is loaded
    • D. A block that can't be changed
    Show answer

    Answer: C. Code that runs once when the class is loaded
    static { ... } initialises static fields.

  58. Q58. What is method hiding?

    • A. Making a method private
    • B. A subclass static method with the same signature as a parent static method
    • C. Overriding a final method
    • D. A method with no body
    Show answer

    Answer: B. A subclass static method with the same signature as a parent static method
    Static methods are not overridden; they are hidden.

  59. Q59. Can we override a private method?

    • A. Yes, always
    • B. Only in the same package
    • C. No, private methods aren't inherited
    • D. Only if it is static
    Show answer

    Answer: C. No, private methods aren't inherited
    A subclass method with the same name is a new method.

  60. Q60. What is the purpose of the finalize() method?

    • A. It was called by the garbage collector before reclaiming an object (now deprecated)
    • B. To make a class final
    • C. To close files automatically
    • D. To end the program
    Show answer

    Answer: A. It was called by the garbage collector before reclaiming an object (now deprecated)
    Use try-with-resources instead.

  61. Q61. What does try-with-resources do?

    • A. Ignores exceptions
    • B. Runs code in a new thread
    • C. Closes resources like files automatically after the block
    • D. Retries a failing block
    Show answer

    Answer: C. Closes resources like files automatically after the block
    Resources must implement AutoCloseable.

  62. Q62. Which exception occurs when you call a method on a null reference?

    • A. NullPointerException
    • B. IllegalStateException
    • C. ArithmeticException
    • D. ClassCastException
    Show answer

    Answer: A. NullPointerException
    The most common Java runtime error.

  63. Q63. What is the default capacity growth of an ArrayList when full?

    • A. Plus 1
    • B. About 1.5 times
    • C. Exactly 2 times
    • D. It can't grow
    Show answer

    Answer: B. About 1.5 times
    newCapacity = old + old / 2.

  64. Q64. What is a package in Java?

    • A. A runtime library only
    • B. A compressed file
    • C. A namespace that groups related classes
    • D. A type of interface
    Show answer

    Answer: C. A namespace that groups related classes
    e.g. java.util, java.io.

  65. Q65. What does the instanceof operator check?

    • A. Whether two objects are equal
    • B. Whether a variable is null only
    • C. Whether a class is abstract
    • D. Whether an object is an instance of a type
    Show answer

    Answer: D. Whether an object is an instance of a type
    Java 16 added pattern matching: if (o instanceof String s).

  66. Q66. Which is true about String literals in Java?

    • A. Identical literals share one object in the string pool
    • B. Every literal creates a new object
    • C. Literals can be changed
    • D. Literals are stored on the stack
    Show answer

    Answer: A. Identical literals share one object in the string pool
    That's why "a" == "a" is true but new String("a") == "a" is false.

  67. Q67. What is a marker interface?

    • A. A deprecated interface
    • B. An interface with no methods that tags a class, like Serializable
    • C. An interface with one method
    • D. An abstract class
    Show answer

    Answer: B. An interface with no methods that tags a class, like Serializable
    Annotations are the modern alternative.

  68. Q68. What does the default keyword mean in an interface method?

    • A. The method is private
    • B. The method has a body that implementing classes inherit
    • C. The method is static
    • D. The method is abstract
    Show answer

    Answer: B. The method has a body that implementing classes inherit
    Added in Java 8 for backward-compatible APIs.

  69. Q69. What is the difference between HashMap and Hashtable?

    • A. They are the same
    • B. Hashtable is synchronized and doesn't allow null keys; HashMap is not synchronized and allows one null key
    • C. Hashtable is faster
    • D. HashMap is synchronized
    Show answer

    Answer: B. Hashtable is synchronized and doesn't allow null keys; HashMap is not synchronized and allows one null key
    Use ConcurrentHashMap for thread-safe maps today.

  70. Q70. What is the purpose of the super() call in a constructor?

    • A. To end the constructor
    • B. To call the parent class constructor
    • C. To call a static method
    • D. To create a superclass object separately
    Show answer

    Answer: B. To call the parent class constructor
    It must be the first statement.

  71. Q71. What is an enum in Java?

    • A. A list of numbers
    • B. A type of loop
    • C. A type with a fixed set of named constants
    • D. A collection class
    Show answer

    Answer: C. A type with a fixed set of named constants
    enum Day { MON, TUE, WED }.

  72. Q72. What is the use of the break statement inside switch?

    • A. To restart the switch
    • B. To stop execution falling through to the next case
    • C. To end the program
    • D. To skip the default case
    Show answer

    Answer: B. To stop execution falling through to the next case
    Arrow-style cases (case 1 ->) don't fall through.

  73. Q73. Which is the correct way to compare two Integer objects for value equality?

    • A. a == b
    • B. a.equals(b)
    • C. a = b
    • D. a.compare(b) == true
    Show answer

    Answer: B. a.equals(b)
    == works only for small cached values (-128 to 127).

  74. Q74. What is the result type of 'a' + 1 in Java?

    • A. double
    • B. char
    • C. int
    • D. String
    Show answer

    Answer: C. int
    char is promoted to int: 97 + 1 = 98.

  75. Q75. Which keyword creates an object?

    • A. create
    • B. object
    • C. new
    • D. make
    Show answer

    Answer: C. new
    Student s = new Student();

  76. Q76. What is a wrapper class?

    • A. A class that wraps a file
    • B. A UI component
    • C. An abstract class
    • D. A class that holds a primitive value as an object, like Integer
    Show answer

    Answer: D. A class that holds a primitive value as an object, like Integer
    Needed because collections store objects, not primitives.

  77. Q77. What is the purpose of the StringBuilder.reverse() method?

    • A. Remove spaces
    • B. Reverse the characters in place
    • C. Convert to upper case
    • D. Sort the characters
    Show answer

    Answer: B. Reverse the characters in place
    new StringBuilder(s).reverse().toString().

  78. Q78. Which Java feature lets one method name work on many types, like List<T>?

    • A. Generics
    • B. Annotations
    • C. Reflection
    • D. Serialization
    Show answer

    Answer: A. Generics
    Type safety checked at compile time.

  79. Q79. What does this code print?

    System.out.println('a' + 1);
    • A. a1
    • B. 98
    • C. b
    • D. Error
    Show answer

    Answer: B. 98
    'a' (97) + 1 is the int 98.

  80. Q80. What does this code print?

    System.out.println((char) ('a' + 1));
    • A. Error
    • B. 98
    • C. a1
    • D. b
    Show answer

    Answer: D. b
    Casting 98 back to char gives 'b'.

  81. Q81. What does this code print?

    Integer a = 100, b = 100, c = 1000, d = 1000;
    System.out.println((a == b) + " " + (c == d));
    • A. true true
    • B. false false
    • C. false true
    • D. true false
    Show answer

    Answer: D. true false
    Small Integer values (-128 to 127) are cached; 1000 is not, so == compares different objects.

  82. Q82. What does this code print?

    int x = 5;
    int y = x++ + 1;
    System.out.println(y + x - 5);
    • A. Error
    • B. 7
    • C. 6
    • D. 8
    Show answer

    Answer: B. 7
    x++ gives 5, so y = 6 and x becomes 6; then 6 + 6 - 5 = 7.

  83. Q83. What does this code print?

    System.out.println("" + (10 + 5));
    • A. Error
    • B. 15
    • C. 1+5
    • D. 105
    Show answer

    Answer: B. 15
    Inside the parentheses the numbers are added first.

  84. Q84. What does this code print?

    int count = 0;
    for (int i = 0; i < 10; i += 4) count++;
    System.out.println(count);
    • A. 3
    • B. Error
    • C. 4
    • D. 2
    Show answer

    Answer: A. 3
    The loop runs for i = 0, 1, 2 and count ends at 3.

  85. Q85. What does this code print?

    java.util.List<String> l = new java.util.ArrayList<>(java.util.List.of("a", "b", "c"));
    java.util.Collections.reverse(l);
    System.out.println(l);
    • A. [c, b, a]
    • B. [b, c, a]
    • C. [a, b, c]
    • D. Error
    Show answer

    Answer: A. [c, b, a]
    Collections.reverse reverses the list in place.

  86. Q86. What does this code print?

    java.util.Set<Integer> s = new java.util.HashSet<>(java.util.List.of(1, 2, 3));
    s.add(2);
    System.out.println(s.size());
    • A. 5
    • B. 2
    • C. 3
    • D. 4
    Show answer

    Answer: C. 3
    A HashSet ignores duplicates.

  87. Q87. What does this code print?

    System.out.println("hello".substring(1, 4));
    • A. ello
    • B. ell
    • C. llo
    • D. hel
    Show answer

    Answer: B. ell
    substring(1, 4) takes indexes 1, 2, 3.

  88. Q88. What does this code print?

    System.out.println("hello".indexOf('l'));
    • A. 3
    • B. 1
    • C. 2
    • D. -1
    Show answer

    Answer: C. 2
    indexOf returns the first index of 'l'.

  89. Q89. What does this code print?

    System.out.println("b".compareTo("a"));
    • A. 1
    • B. -1
    • C. Error
    • D. 0
    Show answer

    Answer: A. 1
    compareTo returns a positive number when the first string is later in order; 'b' - 'a' = 1.

  90. Q90. What does this code print?

    int x = 5;
    x += 1;
    System.out.println(x);
    • A. 5
    • B. 6
    • C. Error
    • D. 7
    Show answer

    Answer: B. 6
    x += 1 adds 1 to x: 5 + 1 = 6.

  91. Q91. What does this code print?

    try {
        int z = 0;
        System.out.println(10 / z);
    } catch (ArithmeticException e) {
        System.out.println("Caught");
    }
    • A. 0
    • B. Caught
    • C. Infinity
    • D. Error
    Show answer

    Answer: B. Caught
    Integer division by zero throws ArithmeticException, which is caught.

  92. Q92. What does this code print?

    class P { static String s() { return "A"; } String i() { return "A"; } }
    class C extends P { static String s() { return "B"; } String i() { return "B"; } }
    public class Main {
        public static void main(String[] args) {
            P p = new C();
            System.out.println(P.s() + " " + p.i());
        }
    }
    • A. A
    • B. B
    • C. B A
    • D. A B
    Show answer

    Answer: D. A B
    The static method of the declared type runs: no overriding for static methods. Then the instance method of the object runs.

  93. Q93. What does this code print?

    class Box {
        int value;
        Box(int value) { this.value = value; }
    }
    public class Main {
        public static void main(String[] args) {
            System.out.println(new Box(10).value);
        }
    }
    • A. 10
    • B. Error
    • C. 0
    • D. null
    Show answer

    Answer: A. 10
    The constructor sets value through this.

  94. Q94. What does this code print?

    class Parent { Parent() { System.out.print("Parent "); } }
    class Child extends Parent { Child() { System.out.println("Child"); } }
    public class Main {
        public static void main(String[] args) {
            new Child();
        }
    }
    • A. Child Parent
    • B. Parent
    • C. Parent Child
    • D. Child
    Show answer

    Answer: C. Parent Child
    The parent constructor always runs before the child constructor.

  95. Q95. What does this code print?

    System.out.println(java.util.stream.IntStream.of(1, 2, 3).sum());
    • A. 123
    • B. 6
    • C. 3
    • D. Error
    Show answer

    Answer: B. 6
    The stream sums 1 + 2 + 3.

  96. Q96. What does this code print?

    System.out.println(java.util.List.of(1, 2, 3, 4).stream().filter(n -> n % 2 == 0).collect(java.util.stream.Collectors.toList()));
    • A. [2, 4]
    • B. []
    • C. [1, 3]
    • D. [1, 2, 3, 4]
    Show answer

    Answer: A. [2, 4]
    filter keeps even numbers.

  97. Q97. What does this code print?

    System.out.println(Math.round(1.5));
    • A. 1
    • B. 2
    • C. 3
    • D. 0
    Show answer

    Answer: B. 2
    Math.round(1.5) rounds half up to 2.

  98. Q98. What does this code print?

    System.out.println(Math.round(-1.5));
    • A. 1
    • B. -1
    • C. -2
    • D. -1.5
    Show answer

    Answer: B. -1
    Math.round(-1.5) rounds half up (towards positive infinity) to -1.

  99. Q99. What does this code print?

    System.out.println((int) Math.ceil(2.1));
    • A. 2
    • B. 2.5
    • C. Error
    • D. 3
    Show answer

    Answer: D. 3
    Math.ceil(2.1) is 3.0, cast to int 3.

  100. Q100. What does this code print?

    System.out.println("Java".equalsIgnoreCase("JAVA"));
    • A. false
    • B. Error
    • C. 1
    • D. true
    Show answer

    Answer: D. true
    equalsIgnoreCase ignores letter case.

  101. Q101. What does this code print?

    StringBuilder sb = new StringBuilder();
    sb.append('a').append(1).append("b").append(2);
    System.out.println(sb);
    • A. a1b2
    • B. 1a2b
    • C. Error
    • D. ab12
    Show answer

    Answer: A. a1b2
    StringBuilder appends in order.

  102. Q102. What does this code print?

    System.out.println("Hi Jo".length());
    • A. 4
    • B. Error
    • C. 6
    • D. 5
    Show answer

    Answer: D. 5
    length() counts characters including the space.

  103. Q103. What does this code print?

    public class Main {
        static int sum(int n) { return n == 0 ? 0 : n + sum(n - 1); }
        public static void main(String[] args) {
            System.out.println(sum(5));
        }
    }
    • A. 5
    • B. 120
    • C. Error
    • D. 15
    Show answer

    Answer: D. 15
    The recursive method sums 5 + 4 + 3 + 2 + 1.

  104. Q104. What does this code print?

    java.util.Deque<Integer> q = new java.util.ArrayDeque<>();
    q.offer(1); q.offer(2); q.offer(3);
    System.out.println(q.poll() + " " + q.poll() + " " + q.poll());
    • A. 3 2 1
    • B. Error
    • C. 1 3
    • D. 1 2 3
    Show answer

    Answer: D. 1 2 3
    ArrayDeque used as a queue returns items in insertion order.

  105. Q105. What does this code print?

    java.util.Deque<Integer> st = new java.util.ArrayDeque<>();
    st.push(1); st.push(2); st.push(3);
    System.out.println(st.pop() + " " + st.pop() + " " + st.pop());
    • A. Error
    • B. 3 1 2
    • C. 3 2 1
    • D. 1 2 3
    Show answer

    Answer: C. 3 2 1
    push/pop on a Deque behaves like a stack.

Practised these? Now prove it.

Take a timed mock test with new questions every attempt, earn a verified certificate at 70%+, and get noticed by employers.

Start a mock test