Page 1 of 1
About Question enthuware.ocpjp.v8.2.1588 :
Posted: Tue Jan 21, 2020 4:00 am
by teodorj
void assertTest(Object obj)
{
assert obj != null : throw new AssertionError();
}
Second operand must evaluate to an object or a primitive. (It can also be null)
What do you mean by "Second operand must evaluate to an object or a primitive."?
Re: About Question enthuware.ocpjp.v8.2.1588 :
Posted: Tue Jan 21, 2020 4:54 am
by admin
"Evaluate to" means the type of the result of evaluating the expression.
The assert statement may have two operands, the first operand is a condition, meaning, the result of the expression used as the first operand should be a boolean (true or false ). Similarly, the result of the expression used as the second operand must be either an object or a primitive (or a null).
Examples:
(In the following examples the expression used as the first operand is obj!=null. It evaluates to true or false.)
assert obj != null : 10; //second operand is an int primitive
assert obj != null : null; //second operand is null
assert obj != null : "string"; //second operand is a String object
assert obj != null : new Student(); //second operand is a Student object (assuming there is a Student class).
and so on.
If you have trouble understanding the above, I would suggest you to go through a good book first before attempting mock exams.
Paul.
Re: About Question enthuware.ocpjp.v8.2.1588 :
Posted: Tue Jan 21, 2020 10:22 am
by teodorj
Got it! the second operand is optional error message used as the message for the AssertionError that is thrown.
Re: About Question enthuware.ocpjp.v8.2.1588 :
Posted: Tue Jan 21, 2020 10:26 am
by admin
Correct.
Re: About Question enthuware.ocpjp.v8.2.1588 :
Posted: Tue Jan 21, 2020 10:29 am
by teodorj
Thanks for the quick response
Appreciate it
Re: About Question enthuware.ocpjp.v8.2.1588 :
Posted: Sat Feb 15, 2020 12:53 am
by bvrulez
teodorj wrote: ↑Tue Jan 21, 2020 10:22 am
Got it! the second operand is optional error message used as the message for the AssertionError that is thrown.
Thanks!
Re: About Question enthuware.ocpjp.v8.2.1588 :
Posted: Sun Aug 09, 2020 1:23 pm
by Javier
Hi Paul!
Why the assert code compile if we remove the 'throw' keyword?
Code: Select all
void assertTest(Object obj) {
assert obj != null : throw new AssertionError(); }// not compile
Code: Select all
void assertTest(Object obj) {
assert obj != null : new AssertionError(); }// compile
Re: About Question enthuware.ocpjp.v8.2.1588 :
Posted: Sun Aug 09, 2020 11:44 pm
by admin
Rule of the language. The assert statement requires an expression. "throw new AssertionError();" is not an expression, "new AssertionError()" is. You might want to go through the difference between an expression and a statement from Section 6.1.2 of Hanumant Deshmukh's OCP Java 11 Part 1 Fundamentals:
https://amzn.to/2PucBeT