Reputation: 599
I have the following method, which returns true if the first number is greater than the second number:
static boolean firstGreaterSecond(int x1, int x2) {
boolean result;
if (x1 > x2) {
result = true;
} else {
result = false;
}
return result;
}
I have added the following assertion:
actual=MyClass.firstGreaterSecond(10,11);
assert false==actual;
I was advised that it may be possible to replace false== with 1 character. I think they may be referring to ?, as in explained here, but no matter how much I tried, I can't seem to get the right syntax. Could you please help?
Upvotes: 1
Views: 13013
Reputation: 11
Both implementation and assertion can be simplified:
private static boolean firstGreaterSecond(int x1, int x2) {
boolean result = x1 > x2;
return result;
}
actual=MyClass.firstGreaterSecond(10,11);
assert !actual;
Upvotes: 1
Reputation: 8724
Well first off,
static boolean firstGreaterSecond(int x1, int x2) {
boolean result;
if (x1 > x2) {
result = true;
} else {
result = false;
}
return result;
}
can be rewritten as:
static boolean firstGreaterSecond(int x1, int x2) {
return x1 > x2;
}
Secondly, you should be able to just:
actual=MyClass.firstGreaterSecond(10,11);
assert !actual;
Take a look at the assert docs
The assertion statement has two forms. The first, simpler form is:
assert Expression1 ;
where Expression1 is a boolean expression. When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no detail message.
The negation of a boolean
expression is also a boolean expression, hence !actual
being valid for the assertion.
Upvotes: 3
Reputation: 6390
boolean firstGreaterSecond(int x1, int x2) {
return (x1>x2)?true:false;
}
What is wrong in this implementation??
Assert will be like:
actual=MyClass.firstGreaterSecond(10,11);
assert !actual;
Upvotes: 0
Reputation: 5191
I believe the alternative they are referring to is
assert(!actual);
Upvotes: 0