Assertions Questions and Answers
Assertions questions with answers in Java programming test a candidate’s ability to debug and validate logic efficiently. The assert keyword is used to verify assumptions during program execution, ensuring code reliability and preventing logical errors. Many placement tests from companies like TCS, Infosys, and Wipro include Java Assertion MCQs to evaluate coding fundamentals. This section offers a collection of Java programming questions and answers with explanations to help you understand the use, syntax, and runtime behavior of assertions. Practice these questions to strengthen your programming logic and prepare effectively for technical interviews and coding tests.
Assertions
Showing 10 of
45 questions
21. Can assertions be enabled for specific packages or classes?
- No, only globally
- Yes, using -ea:package or -ea:class
- Only through code annotations
- Only for system classes
22. Which of these is a valid assert statement?
- assert x = 5;
- assert x > 0;
- assert System.out.println("test");
- assert null;
23. What is the inheritance hierarchy of AssertionError?
- Object -> Throwable -> Exception -> AssertionError
- Object -> Throwable -> Error -> AssertionError
- Object -> Error -> AssertionError
- Object -> Exception -> AssertionError
24. Why are assertions disabled by default?
- They are experimental feature
- To avoid performance overhead in production
- They cause security issues
- Java specifications require it
25. What happens if you use assertions in a place that should always be checked?
- Code becomes more robust
- Potential bugs may occur if assertions disabled
- Compilation warning appears
- Automatic conversion to if-check
26. What is the primary purpose of assertions in Java?
- To handle runtime exceptions
- To improve program performance
- To document code for other developers
- To verify assumptions during development
27. Which keyword is used to declare an assertion in Java?
- assert
- assertion
- Assert
- verify
28. What happens by default when an assertion fails at runtime?
- Compilation error occurs
- AssertionError is thrown
- Program continues silently
- NullPointerException is thrown
29. Which of the following is the correct syntax for a simple assertion?
- assert (condition);
- assert condition;
- assert condition
- assert: condition;
30. How do you enable assertions when running a Java program?
- -enableassertions or -ea
- -assert
- -enable
- -assertions