Java OCA OCP Practice Question 2426

Question

Given the following line of code

String s = "assert";

which of the following code options will compile successfully? (Choose all that apply.)

  • a assert(s == null : s = new String());
  • b assert s == null : s = new String();
  • c assert(s == null) : s = new String();
  • d assert(s.equals("assert"));
  • e assert s.equals("assert");
  • f assert s == "assert" ; s.replace('a', 'z');
  • g assert s = new String("Assert") : s.toString();
  • h assert s == new String("Assert") : System.out.println(s);
  • i assert(s = new String("Assert") : System.out.println(s));


b, c, d, e, f

Note

Option (a) is incorrect.

For the longer form of the assert statement that uses two expressions, you can't enclose both expressions within a single parentheses.

Options (b) and (c) are correct.

It's optional to include the individual expressions used in the longer form within a single parentheses.

Options (d) and (e) are correct.

The shorter form of the assert statement uses only one expression, which might or might not be included within parentheses.

Option (f) is correct.

The semicolon placed after the condition s == "assert" delimits the assert statement, and the statement following the semicolon is treated as a separate statement.

It's equivalent to an assert statement using its shorter form followed by another statement, as follows:.

assert s == "assert" ;
s.replace('a', 'z');

Option (g) is incorrect because the first expression in an assert statement must return a boolean value.

In this code, the first expression returns an object of class String.

Option (h) is incorrect because the second expression in an assert statement must return a value of any type.

In this code, the return type of method println() is void.

Option (i) is incorrect.

It incorrectly encloses both expressions of the assert statement within a single pair of parentheses.

If parentheses were removed, it's also an illegal usage of the long form because it uses an expression that doesn't return a boolean value for its first expression and its second expression doesn't return any value.




PreviousNext

Related