Assertions Questions and Answers

Practice Mode
Showing 10 of 45 questions
Q11
When should assertions typically be used?
  • A To validate user input
  • B To check method parameters in public methods
  • C For internal invariants and debugging assumptions
  • D To handle file I/O errors
Answer: Option C
Explanation: Assertions are for internal invariants and debugging, not for public method parameter validation.
Q12
What is the type of exception thrown by failed assertions?
  • A AssertionException
  • B RuntimeException
  • C AssertionError
  • D ValidationException
Answer: Option C
Explanation: AssertionError extends Error, not Exception.
Q13
Which command disables assertions?
  • A -disableassertions or -da
  • B -noassertions
  • C -assertoff
  • D -disableassert
Answer: Option A
Explanation: -da or -disableassertions disables assertions.
Q14
What happens if assertions are disabled?
  • A Assert statements throw compile error
  • B Assert statements are ignored at runtime
  • C Program execution stops
  • D All assertions return false
Answer: Option B
Explanation: When disabled, assert statements have no effect at runtime.
Q15
Which Java version introduced assertions?
  • A Java 1.0
  • B Java 1.2
  • C Java 1.4
  • D Java 5
Answer: Option C
Explanation: Assertions were introduced in Java 1.4.
Q16
What is the main advantage of using assertions over regular if-checks?
  • A They provide better performance always
  • B They can be enabled/disabled without code changes
  • C They automatically handle exceptions
  • D They work better with inheritance
Answer: Option B
Explanation: Assertions can be disabled in production, removing performance overhead.
Q17
Which of these is NOT appropriate for assertions?
  • A Checking internal class invariants
  • B Validating user input in public methods
  • C Checking control flow assumptions
  • D Debugging complex calculations
Answer: Option B
Explanation: User input validation should use regular exception handling, not assertions.
Q18
What will happen if you try to catch AssertionError?
  • A Compilation error
  • B Runtime exception
  • C It can be caught but is not recommended
  • D JVM crash
Answer: Option C
Explanation: While technically possible, catching AssertionError is generally not recommended.
Q19
Which package contains AssertionError?
  • A java.util
  • B java.lang
  • C java.assert
  • D java.error
Answer: Option B
Explanation: AssertionError is in java.lang package.
Q20
What is the output of: assert false : "Error message"; when assertions enabled?
  • A Prints "Error message"
  • B Throws AssertionError with "Error message"
  • C Compilation error
  • D No output
Answer: Option B
Explanation: AssertionError with the specified message is thrown.
Questions and Answers for Competitive Exams Various Entrance Test