[go: up one dir, main page]

0% found this document useful (0 votes)
155 views47 pages

JAVA MCQ QUESTIONS For Quizzes

The document contains a comprehensive set of multiple-choice questions (MCQs) focused on Java programming, covering beginner to intermediate levels. Each question is followed by four options and the correct answer is provided. Topics include Java features, data types, keywords, exception handling, and object-oriented programming concepts.

Uploaded by

abcdfakeuse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
155 views47 pages

JAVA MCQ QUESTIONS For Quizzes

The document contains a comprehensive set of multiple-choice questions (MCQs) focused on Java programming, covering beginner to intermediate levels. Each question is followed by four options and the correct answer is provided. Topics include Java features, data types, keywords, exception handling, and object-oriented programming concepts.

Uploaded by

abcdfakeuse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

JAVA MCQ QUESTIONS

FOR QUIZZES
BEGINNER FRIENDLY QUESTIONS
1. Who is known as the father of Java programming language?
a) Dennis Ritchie
b) Bjarne Stroustrup
c) James Gosling
d) Ken Thompson
Answer: c) James Gosling
2. Which of the following is a valid data type in Java?
a) double
b) integer
c) real
d) float64
Answer: a) double
3. What is the default value of a local variable in Java?
a) 0
b) null
c) Depends on the data type
d) No default value
Answer: d) No default value
4. Which keyword is used to declare a class in Java?
a) class
b) object
c) define
d) create
Answer: a) class
5. Which of the following is not a Java feature?
a) Object-Oriented
b) Platform-Independent
c) Use of Pointers
d) Multi-threaded
Answer: c) Use of Pointers
6. Which method is the entry point for a Java application?
a) init()
b) main()
c) start()
d) public()
Answer: b) main()
7. What is the extension of Java compiled files?
a) .java
b) .class
c) .exe
d) .javac
Answer: b) .class
8. Which of these is used to create an object in Java?
a) constructor
b) import
c) new
d) instance
Answer: c) new
9. What does JVM stand for?
a) Java Variable Machine
b) Java Virtual Machine
c) Java Visible Mode
d) Java Visual Machine
Answer: b) Java Virtual Machine
10. Which of the following is not a primitive data type in Java?
a) int
b) float
c) boolean
d) String
Answer: d) String
11. Which operator is used to compare two values in Java?
a) =
b) ==
c) !=
d) ===
Answer: b) ==
12. How do you declare an array in Java?
a) int arr[5];
b) int arr = new int[5];
c) int arr() = 5;
d) array int arr[5];
Answer: b) int arr = new int[5];
13. Which of these loops is guaranteed to execute at least once?
a) for
b) while
c) do-while
d) None
Answer: c) do-while
14. What is the size of int in Java?
a) 16 bits
b) 32 bits
c) 64 bits
d) Depends on the system
Answer: b) 32 bits
15. What does "static" keyword mean in Java?
a) A variable that belongs to the object
b) A method or variable shared among all instances of a class
c) A method only accessible within a package
d) None of the above
Answer: b) A method or variable shared among all instances of a class
16. Which of these is not a valid Java keyword?
a) static
b) try
c) NULL
d) final
Answer: c) NULL
17. Which of these is used to handle exceptions in Java?
a) error
b) try-catch
c) exception
d) throw-new
Answer: b) try-catch
18. Which of the following packages is automatically imported in Java?
a) java.awt
b) java.io
c) java.lang
d) java.net
Answer: c) java.lang
19. Which method is used to terminate a thread in Java?
a) terminate()
b) stop()
c) exit()
d) end()
Answer: b) stop()

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


a) 55
b) 10
c) Error
d) None of the above
Answer: a) 55
21. What is an interface in Java?
a) A class that extends multiple classes
b) A reference type that can contain only abstract methods
c) A method without parameters
d) None of the above
Answer: b) A reference type that can contain only abstract methods
22. Which of the following is a wrapper class?
a) int
b) float
c) Integer
d) char
Answer: c) Integer
23. Which exception is thrown when dividing by zero?
a) IOException
b) ArithmeticException
c) NullPointerException
d) DivideByZeroException
Answer: b) ArithmeticException
24. What is the superclass of all classes in Java?
a) java.util
b) Object
c) java.lang.Class
d) None of the above
Answer: b) Object
25. Which keyword is used to inherit a class in Java?
a) extends
b) implements
c) super
d) inherits
Answer: a) extends
26. What is the use of the "this" keyword in Java?
a) Refers to the current object
b) Refers to the superclass
c) Used to declare static variables
d) None of the above
Answer: a) Refers to the current object
27. Which of these is a valid comment in Java?
a) // This is a comment
b) # This is a comment
c) /* This is a comment */
d) Both a and c
Answer: d) Both a and c
28. What does the final keyword in Java signify?
a) A variable can’t be modified
b) A method can’t be overridden
c) A class can’t be subclassed
d) All of the above
Answer: d) All of the above
29. What is the purpose of the "break" statement?
a) Exit a loop or switch statement
b) Pause the program
c) Start a new iteration of a loop
d) End a program
Answer: a) Exit a loop or switch statement
30. Which keyword is used to define a constant in Java?
a) const
b) final
c) constant
d) static
Answer: b) final
31. What does the "super" keyword in Java do?
a) Refers to the child class
b) Refers to the parent class
c) Used to call a static method
d) None of the above
Answer: b) Refers to the parent class
32. Which of the following is not an access modifier in Java?
a) private
b) protected
c) package
d) public
Answer: c) package
33. What will be the output of the following code?
System.out.println(10 > 5 ? "Yes" : "No");
a) Yes
b) No
c) true
d) Error
Answer: a) Yes
34. Which loop is best suited for iterating over an array in Java?
a) while
b) do-while
c) for-each
d) All are equally suitable
Answer: c) for-each
35. What is the result of: 10 % 3 in Java?
a) 1
b) 3
c) 0
d) 10
Answer: a) 1
36. Which of these methods is used to convert a string to an integer?
a) Integer.parseInt()
b) String.toInt()
c) Integer.valueOf()
d) Both a and c
Answer: d) Both a and c
37. How can you stop a thread in Java?
a) interrupt()
b) stop()
c) Both a and b
d) None of the above
Answer: c) Both a and b
38. Which keyword is used to implement an interface?
a) implements
b) extends
c) import
d) interface
Answer: a) implements
39. What will Math.max(10, 20) return?
a) 10
b) 20
c) 30
d) Error
Answer: b) 20
40. Which of these is not a reserved keyword in Java?
a) native
b) strictfp
c) inline
d) synchronized
Answer: c) inline
41. What does String.length() return?
a) The length of the string in bytes
b) The number of characters in the string
c) The length of the string plus one
d) None of the above
Answer: b) The number of characters in the string
42. Which of these is a checked exception in Java?
a) NullPointerException
b) ArithmeticException
c) IOException
d) ArrayIndexOutOfBoundsException
Answer: c) IOException
43. What is the value of Math.pow(2, 3)?
a) 5
b) 6
c) 8
d) 9
Answer: c) 8
44. What does the "continue" statement do in Java?
a) Terminates the program
b) Skips the rest of the current iteration of a loop
c) Exits the loop
d) None of the above
Answer: b) Skips the rest of the current iteration of a loop
45. What is the default value of a boolean in Java?
a) true
b) false
c) null
d) 0
Answer: b) false
46. Which of the following is a marker interface in Java?
a) Serializable
b) Cloneable
c) Both a and b
d) None of the above
Answer: c) Both a and b
47. How do you declare a constant in Java?
a) final int x = 10;
b) int final x = 10;
c) constant int x = 10;
d) int x = 10;
Answer: a) final int x = 10;
48. What is bytecode in Java?
a) Machine code for the JVM
b) Source code written by the programmer
c) Native code for the operating system
d) None of the above
Answer: a) Machine code for the JVM
49. Which method is used to check if two strings are equal in Java?
a) ==
b) equals()
c) compare()
d) match()
Answer: b) equals()
50. What is the output of the following code?
System.out.println("Java" + 10 + 20);
a)Java30
b) Java1020
c) Error
d) None of the above
Answer: b) Java1020
51. Which method is used to get the length of an array in Java?
a) length()
b) size()
c) length
d) getSize()
Answer: c) length
52. What does System.out.println() do?
a) Prints a line to the console
b) Writes output to a file
c) Terminates the program
d) Reads input from the user
Answer: a) Prints a line to the console
53. What is the size of a char in Java?
a) 1 byte
b) 2 bytes
c) 4 bytes
d) Depends on the operating system
Answer: b) 2 bytes
54. Which of these is used for inheritance in Java?
a) interface
b) extends
c) implements
d) import
Answer: b) extends
55. Which keyword is used to avoid method overriding?
a) static
b) final
c) private
d) protected
Answer: b) final
56. What is the output of the following code?
System.out.println(10 + 20 + "Java");
a)Java30
b) 30Java
c) 1020Java
d) Error
Answer: b) 30Java
57. What is the range of values for a byte in Java?
a) -128 to 127
b) -255 to 255
c) -32768 to 32767
d) 0 to 255
Answer: a) -128 to 127
58. What is the default value of a String variable?
a) Empty string ("")
b) null
c) "null"
d) 0
Answer: b) null
59. Which of the following operators is used for string concatenation in
Java?
a) +
b) *
c) &
d) %
Answer: a) +
60. Which of the following is not an OOP concept in Java?
a) Polymorphism
b) Encapsulation
c) Compilation
d) Inheritance
Answer: c) Compilation
61. Which exception is thrown when accessing a null object reference?
a) IOException
b) ArithmeticException
c) NullPointerException
d) ClassNotFoundException
Answer: c) NullPointerException
62. Which keyword is used to explicitly call the parent class
constructor?
a) parent
b) super
c) this
d) extends
Answer: b) super
63. What is the purpose of the import statement in Java?
a) To include external libraries in the code
b) To declare variables
c) To initialize arrays
d) To write comments
Answer: a) To include external libraries in the code
64. What is the output of the following code?
System.out.println('A' + 1);
a)A1
b) 65
c) 66
d) Error
Answer: c) 66
65. Which of the following is not a valid variable name in Java?
a) _name
b) $value
c) 123abc
d) user123
Answer: c) 123abc
66. Which of these is not a type of loop in Java?
a) for
b) do-while
c) foreach
d) repeat-until
Answer: d) repeat-until
67. Which keyword is used to throw an exception?
a) throws
b) throw
c) catch
d) finally
Answer: b) throw
68. What does the toString() method in Java do?
a) Converts a string to lowercase
b) Converts a string to uppercase
c) Returns the string representation of an object
d) None of the above
Answer: c) Returns the string representation of an object
69. Which of these methods is used to start a thread in Java?
a) begin()
b) execute()
c) start()
d) run()
Answer: c) start()
70. What is the use of the default keyword in a switch statement?
a) It ends the switch statement
b) It specifies the code to execute when no case matches
c) It initializes a variable
d) None of the above
Answer: b) It specifies the code to execute when no case matches
INTERMEDIATE LEVEL QUESTIONS
1. What will happen if a static method is called on a null object
reference?
a) NullPointerException
b) The method executes normally
c) Compilation error
d) Runtime exception
Answer: b) The method executes normally
2. Which of the following is true about a final class?
a) It cannot be inherited
b) It can contain abstract methods
c) It cannot have a constructor
d) It cannot be instantiated
Answer: a) It cannot be inherited
3. What happens when two objects have the same hashCode() but are
not equal using equals()?
a) Compiler error
b) No issues arise
c) Violates the hashCode-equals contract
d) Causes runtime exception
Answer: c) Violates the hashCode-equals contract
4. What is the purpose of the transient keyword in Java?
a) Makes a variable constant
b) Makes a variable not serializable
c) Allows inheritance of methods
d) Specifies a synchronized block
Answer: b) Makes a variable not serializable
5. Which statement is correct about the volatile keyword in Java?
a) It prevents variable overriding
b) It guarantees visibility of changes to a variable across threads
c) It locks a variable for a single thread
d) It makes variables immutable
Answer: b) It guarantees visibility of changes to a variable across
threads
6. Which of the following is a thread-safe collection?
a) ArrayList
b) LinkedList
c) Vector
d) HashSet
Answer: c) Vector
7. What is the correct way to make a class immutable in Java?
a) Declare all fields as static
b) Declare the class as final and provide no setters
c) Use the transient keyword for fields
d) Use volatile for fields
Answer: b) Declare the class as final and provide no setters
8. Which of the following methods is used to interrupt a thread in Java?
a) terminate()
b) interrupt()
c) stop()
d) exit()
Answer: b) interrupt()
9. What is the default priority of a thread in Java?
a) 0
b) 1
c) 5
d) 10
Answer: c) 5
10. Which of the following statements about a singleton class is
correct?
a) It cannot have private fields
b) It can only be inherited
c) It allows only one instance of the class
d) It requires static imports
Answer: c) It allows only one instance of the class
11. Which of these exceptions is thrown if an object is not found during
deserialization?
a) IOException
b) ClassNotFoundException
c) NullPointerException
d) FileNotFoundException
Answer: b) ClassNotFoundException
12. Which method is used to notify all threads waiting on an object?
a) notify()
b) notifyAll()
c) wait()
d) signal()
Answer: b) notifyAll()
13. What does the instanceof operator do?
a) Checks if two objects are equal
b) Compares two classes
c) Checks if an object is an instance of a specific class or subclass
d) Checks if an object is null
Answer: c) Checks if an object is an instance of a specific class or
subclass
14. Which of the following best describes polymorphism in Java?
a) It is a way to perform one task in multiple ways
b) It is used to create new classes
c) It refers to data hiding
d) It prevents method overriding
Answer: a) It is a way to perform one task in multiple ways

15. Which design pattern is most commonly used to create a singleton


class?
a) Factory
b) Builder
c) Lazy Initialization
d) Singleton
Answer: d) Singleton
16. What is the difference between == and equals() in Java?
a) Both compare objects in the same way
b) == compares references, while equals() compares values
c) == is used for strings, while equals() is used for primitives
d) equals() is faster than ==
Answer: b) == compares references, while equals() compares values
17. Which of the following allows multiple inheritance in Java?
a) Classes
b) Interfaces
c) Abstract classes
d) Static methods
Answer: b) Interfaces
18. What will be the output of the following code?
String s1 = "Java";
String s2 = "Java";
System.out.println(s1 == s2);
a) true
b) false
c) Compilation error
d) Runtime exception
Answer: a) true

19. Which statement about method overloading is correct?


a) Methods must have the same name and return type
b) Methods must have the same name but different parameter lists
c) Methods must belong to different classes
d) Overloading is not supported in Java
Answer: b) Methods must have the same name but different parameter
lists
20. What is the output of the following code?
System.out.println(Math.ceil(2.5));
a) 2
b) 2.5
c) 3
d) Error
Answer: c) 3
21. What is the maximum size of an int in Java?
a) 2^16
b) 2^32
c) 2^31 - 1
d) 2^63 - 1
Answer: c) 2^31 - 1
22. Which of the following statements about the abstract keyword is
true?
a) Abstract methods cannot have a body
b) Abstract classes cannot be subclassed
c) Abstract methods can be static
d) Abstract classes cannot have constructors
Answer: a) Abstract methods cannot have a body
23. What is the purpose of the finalize() method in Java?
a) To release resources before an object is garbage collected
b) To explicitly delete objects
c) To clone objects
d) To terminate the program
Answer: a) To release resources before an object is garbage collected
24. Which of the following is not a type of Java Inner Class?
a) Static Inner Class
b) Anonymous Inner Class
c) Abstract Inner Class
d) Local Inner Class
Answer: c) Abstract Inner Class
25. What is the main feature of a functional interface?
a) It has multiple abstract methods
b) It has exactly one abstract method
c) It can only be used in lambda expressions
d) It is used for polymorphism
Answer: b) It has exactly one abstract method
26. What is the output of the following code?
int x = 10;
x = x++;
System.out.println(x);
a) 11
b) 10
c) Compilation error
d) Runtime exception
Answer: b) 10
27. Which of the following exceptions is unchecked?
a) IOException
b) NullPointerException
c) SQLException
d) FileNotFoundException
Answer: b) NullPointerException
28. Which statement about a synchronized method is correct?
a) It can be accessed simultaneously by multiple threads
b) It allows only one thread at a time to execute the method
c) It can only be static
d) It cannot throw exceptions
Answer: b) It allows only one thread at a time to execute the method
29. Which of the following is not a type of Java operator?
a) Relational
b) Logical
c) Bitwise
d) Ternary
Answer: d) Ternary
30. What will happen if Thread.sleep(1000) is called?
a) The thread will stop forever
b) The thread will wait for 1 second
c) The thread will terminate after 1 second
d) The thread will execute immediately
Answer: b) The thread will wait for 1 second
31. Which of these best describes composition in Java?
a) "Has-a" relationship
b) "Is-a" relationship
c) "Uses-a" relationship
d) "Inherits-a" relationship
Answer: a) "Has-a" relationship
32. What does the finally block do in Java?
a) Executes code only if an exception is thrown
b) Executes code only if no exception is thrown
c) Always executes code regardless of an exception
d) Does not execute if a return statement is used
Answer: c) Always executes code regardless of an exception
33. What is the purpose of the super() keyword?
a) To call a parent class constructor
b) To access private variables of the parent class
c) To create a new instance of the parent class
d) To define static methods
Answer: a) To call a parent class constructor
34. Which of the following is true about garbage collection in Java?
a) Objects are deleted manually
b) The programmer must explicitly call garbage collection
c) It is managed by the JVM automatically
d) It requires the finalize() method
Answer: c) It is managed by the JVM automatically
35. What will the following code print?
String s1 = "Java";
String s2 = new String("Java");
System.out.println(s1 == s2);
a) true
b) false
c) Compilation error
d) Runtime exception
Answer: b) false
36. Which of the following classes is immutable in Java?
a) StringBuffer
b) StringBuilder
c) String
d) ArrayList
Answer: c) String
37. Which of the following is not part of the Java Collection Framework?
a) HashMap
b) ArrayList
c) Hashtable
d) FileReader
Answer: d) FileReader
38. What will be the output of the following code?
System.out.println(10 >> 2);
a) 2
b) 5
c) 8
d) 10
Answer: b) 5
39. What is the use of the Iterator interface in Java?
a) To iterate through collections
b) To modify collection elements
c) To store elements in collections
d) To sort collections
Answer: a) To iterate through collections
40. What is a marker interface in Java?
a) An interface that contains default methods
b) An interface without any methods or fields
c) An interface that defines abstract methods
d) An interface that implements another interface
Answer: b) An interface without any methods or fields
41. Which access modifier allows visibility within the same package
only?
a) public
b) private
c) protected
d) default
Answer: d) default
42. What is the output of the following code?
System.out.println("Hello" + null);
a) Hello
b) Hellonull
c) Compilation error
d) Runtime exception
Answer: b) Hellonull
43. Which of the following is not a feature of Java?
a) Platform independence
b) Object-oriented
c) Pointers
d) Multithreading
Answer: c) Pointers
44. Which of these methods is used to sort a list in Java?
a) sort()
b) Collections.sort()
c) Arrays.sort()
d) Both b and c
Answer: d) Both b and c
45. What is the use of the this keyword in Java?
a) To refer to the current class instance
b) To refer to the parent class instance
c) To call a static method
d) To invoke a superclass method
Answer: a) To refer to the current class instance
46. What happens when you call start() on a thread in Java?
a) The thread starts execution immediately
b) The thread enters the ready state
c) The thread enters the waiting state
d) The thread terminates immediately
Answer: b) The thread enters the ready state
47. Which method is used to convert an array to a list in Java?
a) Arrays.asList()
b) Collections.asList()
c) Arrays.toList()
d) List.of()
Answer: a) Arrays.asList()
48. Which of the following is a characteristic of the Java Map interface?
a) It allows duplicate keys
b) It does not allow null values
c) It maps keys to values
d) It is thread-safe
Answer: c) It maps keys to values
49. Which of the following best describes encapsulation in Java?
a) Wrapping data and methods into a single unit
b) Using multiple classes to perform a task
c) Inheriting methods from a parent class
d) Making methods static
Answer: a) Wrapping data and methods into a single unit
50. What does the String.trim() method do?
a) Removes leading and trailing whitespace
b) Converts a string to lowercase
c) Removes all spaces in the string
d) Splits a string into parts
Answer: a) Removes leading and trailing whitespace
51. Which exception is thrown when dividing a number by zero in Java?
a) ArithmeticException
b) NullPointerException
c) ArrayIndexOutOfBoundsException
d) NumberFormatException
Answer: a) ArithmeticException
52. What will be the output of the following code?
String s1 = "Java";
String s2 = "Java";
System.out.println(s1.equals(s2));
a) true
b) false
c) Compilation error
d) Runtime exception
Answer: a) true
53. Which of the following is not a valid state in the thread lifecycle?
a) New
b) Blocked
c) Suspended
d) Terminated
Answer: c) Suspended
54. Which data structure is used by the JVM for method calls?
a) Queue
b) Stack
c) Heap
d) LinkedList
Answer: b) Stack
55. What will the following code output?
System.out.println(5 + "5");
a) 10
b) 55
c) 5 5
d) Compilation error
Answer: b) 55
56. Which of the following statements about the HashMap class is
true?
a) It allows duplicate keys
b) It allows one null key
c) It is synchronized
d) It maintains the order of elements
Answer: b) It allows one null key
57. Which of these methods is used to retrieve the current time in
milliseconds?
a) System.now()
b) System.getTime()
c) System.currentTimeMillis()
d) Date.now()
Answer: c) System.currentTimeMillis()
58. What is the main purpose of the enum type in Java?
a) To create a list of constants
b) To declare a class as immutable
c) To define a set of abstract methods
d) To implement functional interfaces
Answer: a) To create a list of constants
59. What will the following code print?
System.out.println("A".compareTo("B"));
a) 1
b) -1
c) 0
d) Compilation error
Answer: b) -1
60. What does the @Override annotation do?
a) It hides the parent class method
b) It indicates that a method is overriding a superclass method
c) It marks a method as static
d) It indicates that a method is abstract
Answer: b) It indicates that a method is overriding a superclass method
61. What happens when an exception is not caught in Java?
a) The program continues execution
b) The program terminates immediately
c) The JVM calls the printStackTrace() method and terminates the program
d) The exception is ignored
Answer: c) The JVM calls the printStackTrace() method and terminates
the program
62. Which of the following classes is synchronized?
a) ArrayList
b) LinkedList
c) Hashtable
d) HashMap
Answer: c) Hashtable
63. What will the following code print?
int a = 5;
System.out.println(++a);
a) 5
b) 6
c) Compilation error
d) Runtime exception
Answer: b) 6
64. What does the Files.exists(Path path) method do?
a) Creates a file if it does not exist
b) Checks whether a file exists at the specified path
c) Deletes a file if it exists
d) Returns the size of the file
Answer: b) Checks whether a file exists at the specified path
65. Which of these best describes the Factory design pattern?
a) It is used to clone objects
b) It provides a way to create objects without specifying the exact class
c) It allows objects to communicate without knowing each other
d) It ensures a class has only one instance
Answer: b) It provides a way to create objects without specifying the
exact class
66. What is the default encoding of a Java InputStreamReader if no
encoding is specified?
a) UTF-16
b) UTF-8
c) The platform's default encoding
d) ASCII
Answer: c) The platform's default encoding
67. What does the default keyword do in an interface?
a) Defines a method that must be implemented
b) Provides a default implementation for a method in the interface
c) Marks an interface as immutable
d) Indicates a method is abstract
Answer: b) Provides a default implementation for a method in the
interface
68. Which statement about TreeSet in Java is true?
a) It allows duplicate elements
b) It maintains the insertion order
c) It stores elements in sorted order
d) It is not a part of the Java Collections Framework
Answer: c) It stores elements in sorted order
69. Which of the following best describes the final keyword when
applied to a method?
a) The method can be overridden
b) The method cannot be inherited
c) The method cannot be overridden
d) The method must return a constant value
Answer: c) The method cannot be overridden
70. What is the primary advantage of using a ConcurrentHashMap over
a Hashtable?
a) It allows null keys and values
b) It is faster for write operations
c) It is thread-safe with better performance
d) It does not allow duplicate values
Answer: c) It is thread-safe with better performance
ADVANCED LEVEL QUESTIONS
1. Which of the following ensures that a Java class cannot be
subclassed?
a) private keyword
b) final keyword
c) abstract keyword
d) static keyword
Answer: b) final keyword
2. What is the purpose of the volatile keyword in Java?
a) To make variables thread-safe
b) To prevent caching of variables
c) To ensure atomic operations
d) Both a and b
Answer: d) Both a and b
3. What will the following code output?
String s1 = "abc";
String s2 = new String("abc");
System.out.println(s1 == s2);
a) true
b) false
c) Compilation error
d) Runtime exception
Answer: b) false
4. Which of the following is NOT a feature of Java’s Stream API?
a) Lazy evaluation
b) Immutable data
c) Parallel execution
d) Built-in exception handling
Answer: d) Built-in exception handling
5. What will happen if two threads access a HashMap concurrently?
a) It throws ConcurrentModificationException
b) It behaves unpredictably
c) It blocks the threads
d) It ensures consistent access
Answer: b) It behaves unpredictably
6. What does the computeIfAbsent method in Map do?
a) Removes the key if absent
b) Updates the value if the key is present
c) Adds the key-value pair if the key is absent
d) Throws an exception if the key is absent
Answer: c) Adds the key-value pair if the key is absent
7. What is the result of calling
Optional.ofNullable(null).orElse("default")?
a) null
b) default
c) Compilation error
d) Runtime exception
Answer: b) default
8. Which collection allows duplicate elements and maintains insertion
order?
a) HashSet
b) TreeSet
c) ArrayList
d) LinkedHashSet
Answer: c) ArrayList
9. How does the LinkedHashMap maintain the order of its elements?
a) Random order
b) Sorted order
c) Reverse order
d) Insertion order
Answer: d) Insertion order
10. What is the default capacity of an ArrayList in Java?
a) 0
b) 8
c) 10
d) 16
Answer: c) 10
11. What happens if a thread calls Thread.yield()?
a) The thread enters a waiting state
b) The thread relinquishes CPU but remains runnable
c) The thread terminates
d) The thread is paused indefinitely
Answer: b) The thread relinquishes CPU but remains runnable
12. What is the time complexity of inserting an element in a
HashMap (without collisions)?
a) O(1)
b) O(n)
c) O(log n)
d) O(n^2)
Answer: a) O(1)
13. Which of the following ensures atomicity for compound
operations?
a) synchronized block
b) volatile keyword
c) AtomicInteger class
d) Both a and c
Answer: d) Both a and c
14. What does the forkJoinPool framework in Java use to improve
performance?
a) Recursive tasks
b) Work-stealing algorithm
c) Thread pooling
d) All of the above
Answer: d) All of the above
15. Which of the following methods in ExecutorService shuts down
the executor immediately?
a) shutdownNow()
b) shutdown()
c) awaitTermination()
d) close()
Answer: a) shutdownNow()
16. Which class is thread-safe for manipulating lists?
a) ArrayList
b) LinkedList
c) Vector
d) HashSet
Answer: c) Vector
17. Which annotation is used to suppress compiler warnings in
Java?
a) @Deprecated
b) @SuppressWarnings
c) @Override
d) @FunctionalInterface
Answer: b) @SuppressWarnings
18. What is the difference between StringBuffer and StringBuilder?
a) StringBuffer is thread-safe, StringBuilder is not
b) StringBuilder is thread-safe, StringBuffer is not
c) Both are thread-safe
d) Neither is thread-safe
Answer: a) StringBuffer is thread-safe, StringBuilder is not

19. What is the result of the following code?


int x = 10;
int y = ++x + x--;
System.out.println(y);
a) 20
b) 21
c) 22
d) Compilation error
Answer: b) 21
20. Which of the following methods is used to handle
asynchronous tasks in Java?
a) CompletableFuture
b) Future
c) ThreadPoolExecutor
d) All of the above
Answer: d) All of the above
21. Which of the following is used to create an immutable
collection in Java 9?
a) Collections.unmodifiableList()
b) List.of()
c) List.copyOf()
d) Both b and c
Answer: d) Both b and c
22. What will happen if you serialize an object with a transient
field?
a) The field will be serialized normally
b) The field will throw a NotSerializableException
c) The field will not be serialized
d) The object will not be serialized
Answer: c) The field will not be serialized
23. Which of the following is true about Optional in Java?
a) It is used to handle null values gracefully
b) It can have at most one value
c) It reduces the risk of NullPointerException
d) All of the above
Answer: d) All of the above
24. Which of the following is not a valid functional interface?
a) Runnable
b) Callable
c) Comparator
d) Serializable
Answer: d) Serializable
25. What is the output of the following code?
IntStream.range(1, 5).forEach(System.out::print);
a) 12345
b) 1234
c) 2345
d) Compilation error
Answer: b) 1234
26. Which class in Java is used for key-value pair storage and is
thread-safe?
a) HashMap
b) Hashtable
c) ConcurrentHashMap
d) Both b and c
Answer: d) Both b and c
27. What is the default priority of a Java thread?
a) 0
b) 5
c) 10
d) 1
Answer: b) 5
28. What is the difference between synchronized and
ReentrantLock?
a) ReentrantLock provides more flexibility
b) ReentrantLock allows tryLock()
c) synchronized blocks are simpler to use
d) All of the above
Answer: d) All of the above
29. Which method in the Stream API can terminate the pipeline?
a) map()
b) filter()
c) reduce()
d) flatMap()
Answer: c) reduce()
30. Which of the following allows dynamic proxies in Java?
a) Proxy class
b) InvocationHandler interface
c) Both a and b
d) None of the above
Answer: c) Both a and b
31. Which Java feature allows method execution to be determined
at runtime?
a) Polymorphism
b) Abstraction
c) Reflection
d) Dynamic binding
Answer: d) Dynamic binding
32. Which method in the ExecutorService interface is used to
submit a Callable task?
a) execute()
b) submit()
c) call()
d) run()
Answer: b) submit()
33. Which annotation ensures that a method overrides a
superclass method?
a) @Deprecated
b) @FunctionalInterface
c) @Override
d) @SuppressWarnings
Answer: c) @Override
34. What is the result of using TreeSet to store elements?
a) Random order
b) Sorted order
c) Reverse order
d) Insertion order
Answer: b) Sorted order
35. Which of the following methods in the Optional class returns
the value if present or throws an exception otherwise?
a) orElse()
b) get()
c) isPresent()
d) orElseThrow()
Answer: b) get()
36. What is the key feature of the CompletableFuture class in Java?
a) It handles synchronous tasks
b) It allows asynchronous computation
c) It is deprecated in Java 11
d) None of the above
Answer: b) It allows asynchronous computation
37. Which class uses a work-stealing algorithm for parallelism in
Java?
a) ThreadPoolExecutor
b) ForkJoinPool
c) ExecutorService
d) ScheduledThreadPoolExecutor
Answer: b) ForkJoinPool
38. What is the result of calling String.intern()?
a) It creates a new string object
b) It returns the canonical representation of the string
c) It throws a NullPointerException if the string is null
d) None of the above
Answer: b) It returns the canonical representation of the string
39. Which method in Stream is used to remove duplicate
elements?
a) distinct()
b) filter()
c) map()
d) flatMap()
Answer: a) distinct()
40. Which data structure is used internally by PriorityQueue?
a) Array
b) LinkedList
c) Balanced Binary Tree
d) Heap
Answer: d) Heap
41. What happens if wait() is called on an object without holding its
lock?
a) The thread is blocked
b) IllegalMonitorStateException is thrown
c) The thread terminates
d) The thread waits indefinitely
Answer: b) IllegalMonitorStateException is thrown
42. Which functional interface is used to execute a block of code
without arguments or return values?
a) Supplier
b) Consumer
c) Runnable
d) Callable
Answer: c) Runnable
43. How can you achieve immutability in Java?
a) Use final keyword for class
b) Make fields final and private
c) Avoid exposing setters
d) All of the above
Answer: d) All of the above
44. Which stream operation is used to transform elements?
a) map()
b) reduce()
c) filter()
d) distinct()
Answer: a) map()
45. What is the time complexity of accessing elements in a
HashMap with no collisions?
a) O(1)
b) O(log n)
c) O(n)
d) O(n^2)
Answer: a) O(1)
46. What happens if two threads call put() on a
ConcurrentHashMap with the same key?
a) The latest value is retained
b) Both values are retained
c) It throws ConcurrentModificationException
d) None of the above
Answer: a) The latest value is retained
47. Which collection is backed by a hash table and maintains
insertion order?
a) LinkedHashSet
b) TreeSet
c) HashSet
d) ArrayList
Answer: a) LinkedHashSet
48. What does the finalize() method do?
a) It is called by the garbage collector before an object is destroyed
b) It releases system resources explicitly
c) It is deprecated in modern Java versions
d) Both a and c
Answer: d) Both a and c
49. Which class in the java.util.concurrent package allows threads
to count down to a latch?
a) CyclicBarrier
b) CountDownLatch
c) Semaphore
d) Exchanger
Answer: b) CountDownLatch
50. Which design pattern is implemented by java.lang.Runtime?
a) Factory Pattern
b) Singleton Pattern
c) Prototype Pattern
d) Builder Pattern
Answer: b) Singleton Pattern
51. Which of the following methods is used to check if a thread
holds a particular lock?
a) Thread.isLocked()
b) Thread.holdsLock()
c) Lock.isHeldByCurrentThread()
d) Lock.holdsLock()
Answer: b) Thread.holdsLock()
52. What is the primary difference between wait() and sleep()?
a) wait() does not release the lock, sleep() does
b) wait() is used for inter-thread communication, sleep() is not
c) Both release the lock
d) Both are identical
Answer: b) wait() is used for inter-thread communication, sleep() is
not
53. What is the purpose of the readResolve() method in Java
serialization?
a) It writes objects during serialization
b) It ensures singleton property during deserialization
c) It replaces the object being serialized
d) It handles object references during serialization
Answer: b) It ensures singleton property during deserialization
54. Which feature of Java allows accessing private members of a
class?
a) Reflection
b) Serialization
c) Generics
d) Encapsulation
Answer: a) Reflection
55. Which method in Stream API is a terminal operation?
a) filter()
b) sorted()
c) forEach()
d) peek()
Answer: c) forEach()
56. How does ConcurrentLinkedQueue handle concurrency?
a) Using locks
b) Using a wait-notify mechanism
c) Using a non-blocking algorithm
d) Using thread-local variables
Answer: c) Using a non-blocking algorithm
57. What is the purpose of the @SafeVarargs annotation?
a) To suppress unchecked warnings for generic varargs
b) To ensure thread safety in methods
c) To prevent method overriding
d) To mark methods as deprecated
Answer: a) To suppress unchecked warnings for generic varargs
58. What happens if a try block has both catch and finally clauses?
a) Only catch is executed
b) Only finally is executed
c) Both are executed, with finally always running
d) Neither is executed
Answer: c) Both are executed, with finally always running
59. Which of the following statements about TreeMap is correct?
a) It maintains a random order of keys
b) It allows null keys
c) It sorts keys in natural or custom order
d) It is synchronized by default
Answer: c) It sorts keys in natural or custom order
60. What is the difference between Comparator and Comparable?
a) Comparable is for natural ordering, Comparator is for custom
ordering
b) Comparator is for natural ordering, Comparable is for custom
ordering
c) Both are identical
d) Both are functional interfaces
Answer: a) Comparable is for natural ordering, Comparator is for
custom ordering
61. Which of the following methods in the ExecutorService waits
for tasks to finish execution?
a) awaitTermination()
b) shutdown()
c) shutdownNow()
d) invokeAll()
Answer: a) awaitTermination()
62. What does ConcurrentSkipListMap use internally for
concurrency?
a) A binary tree
b) A skip list
c) A hash table
d) A balanced tree
Answer: b) A skip list
63. What does the default keyword do in an interface?
a) Allows default implementation of a method
b) Prevents method overriding
c) Creates static methods
d) Marks a method as abstract
Answer: a) Allows default implementation of a method
64. Which of the following is true about Phaser in Java?
a) It is used to manage threads arriving in phases
b) It is an alternative to CountDownLatch
c) It supports dynamic addition of threads
d) All of the above
Answer: d) All of the above
65. Which method in Java creates a thread-safe list?
a) Collections.synchronizedList()
b) Arrays.asList()
c) List.of()
d) List.copyOf()
Answer: a) Collections.synchronizedList()
66. Which garbage collection algorithm is used by default in the
Java Virtual Machine?
a) Serial GC
b) G1 GC
c) Parallel GC
d) Z GC
Answer: c) Parallel GC
67. What does the isDaemon() method return for a thread?
a) Whether the thread is alive
b) Whether the thread is a daemon thread
c) Whether the thread has exited
d) None of the above
Answer: b) Whether the thread is a daemon thread
68. What is the main advantage of CompletableFuture over
Future?
a) Support for chaining multiple tasks
b) Support for blocking operations
c) Built-in retry mechanism
d) None of the above
Answer: a) Support for chaining multiple tasks
69. Which of the following is NOT an advantage of immutability?
a) Thread safety
b) Simpler debugging
c) Reduced memory usage
d) Preventing accidental modifications
Answer: c) Reduced memory usage
70. Which class in Java supports a bounded blocking queue?
a) LinkedBlockingQueue
b) PriorityBlockingQueue
c) ArrayBlockingQueue
d) All of the above
Answer: d) All of the above

You might also like