This question already has answers here:
How to use ternary operator(?:) or Null Coalescing operator(??) to write if-else condition?
(5 answers)
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 2 years ago.
Can someone please explain this java syntax for me.
public boolean isDead() { return numFightersAlive() == 0 ? true : false; }
I am new to java and I was wondering what kind of syntax that is. Normally I would create a variable and return the boolean variable but it's my first time seeing a question mark in a code.
After the question mark is the "then" part, after colon is the "else" part.
So this is shorthand syntax for
if (numFightersAlive() == 0) {
return true;
} else {
return false;
}
It can actually be simplified to be just
return numFightersAlive() == 0
This would give an equivalent result
This is called ternary. It's a shortened version of an if, but it's not better than an if all the time.
The syntax of a ternary is as follows:
(condition) ? result in case of being true: result in case of being false
In this case:
The return is asking a condition. Is the condition equal to zero?
If it is true, return will have a true value, if it is false return will have a false value.
public boolean isDead() { return numFightersAlive() == 0 ? true : false; }
Related
This question already has answers here:
Java logical operator short-circuiting
(10 answers)
Closed 6 years ago.
I work on Java 8 and I have a simple issue that I have not figured out.
I have a 3 methods which are validating the data from db and returning true or false based on whether they got a row or not. The tricky part is, even if I know that the first part
is returning false, I still want it to check for the other two methods. I have written my code like this :
boolean flag = true;
flag = flag && validateMethod1();
flag = flag && validateMethod2();
flag = flag && validateMethod3();
return flag;
The issue is, when validateMethod1() returns false, it is not calling validateMethod2(). Can someone explan why ?
I tried this :
boolean flag = true;
flag = flag & validateMethod1();
flag = flag & validateMethod2();
flag = flag & validateMethod3();
return flag;
Still face the same issue.
&& is a short circuited AND operator. It doesn't evaluate the second operand if the first operand is evaluated to false.
In order to evaluate all the operands, use the non-short-circuit version of the AND operator :
return validateMethod1() & validateMethod2() & validateMethod3();
As you can see, your logic can be reduced to a single line of code.
Java uses sort-circuit evaluation of expressions - i.e. as soon as it knows for sure the result will be false, it stops the evaluation.
Since your expression is a conjunction, once flag is found to be false, it is clear the whole expression will be false.
One way around it (quite verbose) is:
boolean flag1 = validateMethod1();
boolean flag2 = validateMethod2();
boolean flag3 = validateMethod3();
return flag1 && flag2 && flag3;
That's because you are using short circuit && instead of &, which leads to check only first argument in this case, when this argument is false.
The & operator, when used as logical operator, always evaluate both sides.
This question already has answers here:
Difference between "!= true" and "== false"?
(2 answers)
Closed 4 years ago.
I've faced a situation where "!= true" gave me a different output than "= false". I thought that if something isn't true it'd be false automatically. Can anyone please explain me how it works? Thanks!
It gives different output because you confused with Comparison vs Assignment
!= will compares the value with RHS and =false do an assignment to LHS. If you wish to check for equality use the == operator instead.
And I don't think it won't make much difference when you compare in difference styles since both do the same job unless you have some weird line of code.
== is comparison operator, = is assignment operator
!= is not equal to, and == is equal to
In addition to the other answers,
if something isn't true it'd be false automatically
is also wrong.
(Boolean) null != true is true, but (Boolean) null == false is of course false.
!= true is used a comparator. It compare the LHS to true. However = false is an assignment. An equivalent of != true will be == false. == is also a comparator operator that checks for equality while != checks for inequality.
It is all about writing or checking the value...
look this example...
boolean flag = true; a boolean variable is defined and assig to true
if (flag!=true) { //you should do instead if(!flag)
//this is checking the content of the flag variable
}
if (flag=true) { //you should do instad if(flag)
//this is writing the content of the flag assigning it to true
}
In a boolean statement, if you use != true, if the boolean is null, the operator will allow it to run whatever it is comparing. If you use == false, it will only run if the boolean is currently set to false.
First is comparison, in later case you are assigning
This question already has answers here:
Unreachable code compiler error [duplicate]
(7 answers)
Closed 6 years ago.
Why does this method return the error: Error: Unreachable code Thank you!
public static boolean zeroCheck(double numberTwo, String operator) {
if (numberTwo == 0) {
return false;
if(operator == "/" || operator == "%")
System.out.println("You cannot use a zero to divide or mod.");
} else return true;
}
}
Error:
File: C:\JAVA\LABS\LabSix.java [line: 228]
Error: Unreachable code
You return a value before you procceed to the rest of the code that is never reached. When you use the return statement, it automatically ends the code and returns boolean in your case.
Just put your return statement in the end of your block.
public static boolean zeroCheck(double numberTwo, String operator) {
if (numberTwo == 0) {
if (operator == "/" || operator == "%") {
System.out.println("You cannot use a zero to divide or mod.");
}
return false;
} else return true
}
By the way, if you want to compare String, please use equals(..) method, because String is not the primitive type like int or double etc. are. Generally, use equals(..) in case of comparing all objects.
if (operator.equals("/") || operator.equals("%"))
I'm assuming you meant to put the return false after the operator check. What happens is that the function returns when the numberTwo is 0 before the code gets a chance to check the if statement, making this the unreachable code
Don't worry, this is a common misunderstanding for newcomers, it's not just you. :-) The return keyword does two things:
Determines what the return value of the function will be, and
Exits the function at that point
Newcomers sometimes think it just does the first, not the second. (And there are languages where the two are in fact done separately, Java just isn't one of them.)
So in your example, the unreachable code is the code after the return false;, since when the return false; statement is executed, it exits the function.
Just put it after the other code in that block:
public static boolean zeroCheck(double numberTwo, String operator)
{
if (numberTwo == 0)
{
if (operator.equals("/") || operator.equals("%"))
{
System.out.println("You cannot use a zero to divide or mod.");
}
return false;
}
else // See note #3 below, you don't really need this
{
return true;
}
}
A couple of other notes on the code above:
You don't compare strings in Java with ==, you use str.equals(otherStr). More: How do I compare strings in Java?
Note that I added braces around the inner block (the one attached to if (operator.equals...). They aren't strictly-speaking necessary, but when you're using braces in the outer block (which you have to), leaving them off the inner block can trip up someone editing the code later.
Since your if block ends with return false;, there's no need for the else; you could just follow the end of the if block with return true; It can't be reached if you went into the block, because of course, you exited the function.
The code above returns false if numberTwo is 0, even if the operator isn't / or %. That's what I think your original code meant to do, but I thought I'd flag it up.
Re #3 above, another option is to remember your return value in a variable:
public static boolean zeroCheck(double numberTwo, String operator)
{
boolean numberTwoIsZero = numberTwo == 0;
if (numberTwoIsZero)
{
if (operator.equals("/") || operator.equals("%"))
{
System.out.println("You cannot use a zero to divide or mod.");
}
}
return numberTwoIsZero;
}
This question already has answers here:
Using NOT operator in IF conditions
(8 answers)
Closed 7 years ago.
I have a boolean variable collision initialized to false.
Now in an if statement, suppose my if condition is the following:
if(!collision)
does this mean that the if statement will execute if collision is the opposite of what is initialized? Meaning, will it execute when !collision returns true?
Just a bit confused since I initialized it to false, and I want this if statement to run when collision is false, but don't know if !collision is the right way to do it or not.
Code as requested. Still confused on what the condition would be. I have collision initialized to false. As a result, I want the statement to be executed when it is false. Should I write if(collision) or if(!collision)?
boolean collision = false;
boolean winner = false;
while(!winner){
//Main loop where user will be able to move the ships and try to destroy the ship
//boolean shipAlive = true/false; YET TO ADD!
//if(!shipAlive) -> winner = true; YET TO ADD!
//movement of ships
if(!collision){
System.out.println("Player 1: L, R, or S? (L = Left, R = Right, S = Stay)");
String p1Input = IO.readString();
int k = movement(p1Input, player1);
while (k == 1){
System.out.print("Error! Enter either L, R or S: ");
p1Input = IO.readString();
k = movement(p1Input, player1);
}
}
collision = fireProjectileUp();
if(collision){
winner = true;
}
Yes, it is the right way to do it:
In if (!someBoolExpr) { ... }, the "then-clause" will run if someBoolExpr == false.
See the JLS ยง15.15.6: Logical Complement Operator ! for more information:
The value of the unary logical complement expression is true if the (possibly converted) operand value is false, and false if the (possibly converted) operand value is true.
! represents NOT in Java. So if you have something like
if(!true) {
//doSomething
} else {
//Something else --- This is executed.
}
if(!false) {
//doSomething --- This is executed.
} else {
//Something else
}
true and false are the final result of your comparison operations
! means not, so your expression will be translated to if(NOcollision).
Check documentation for further info.
Yes, your if statement will be executed when collision is false.
!false returns true
You've asked a question, but I suspect this is a bit of an XY problem for you. You've asked about clarification of the ! operator, then proceeded to explain exactly what a not operation is.
When constructing your conditions, you want to manipulate the logic so that it evaluates to true when you want it too. For example, I want something to run if there has been a collision.
if(collision)
Simple. This is because this will evaluate to true when you want it too. Now you want something to run if their hasn't been a collision.
if(!collision)
Once again, it evaluates to true if collision is false. Or, when you want it too. The trick here is working out how to express what you want in a way that the compiler understands, and this is done through logical expressions that resolve to some boolean true or boolean false.
EDIT
Just incase, ! operator is simply the opposite of the value. !true is false, !false is true. Going by what I explained above, you can combine this knowledge to create your solution.
When if(!collision) is executed then first of all it checks the value of collision. Let's assume its is 'false'. Then ! operator converts it to true. opposite of false. Then the value is 'true ' so, if statement will execute its code block.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the Java ?: operator called and what does it do?
Maybe this is a duplicated question to some other questions here but I could not find it.
Yesterday I saw a guy using a new way of writing the if statement by using ? and : and I'm not sure what do they all mean.
If someone could point me out to a tutorial or an already answered question I would so much appreciated.
The conditional operator, it's a type of ternary operator
wikipedia - ?:
wikipedia - ternary operation
(condition) ? (what happens if true) : (what happens if false);
Example use:
int a = 1;
int b = (a == 1) ? 2 : (a + 1);
It's a ternary operator. General form:
expr1 ? expr2 : expr3
If expr1 evaluates to true, the returned result is expr2, otherwise it's expr3. Example:
Object obj = (obj != null) ? obj : new Object();
Easy way to initialize an object if it's null.
(statement) ? TRUE : FALSE
Example in pseudocode: a = (5 > 3) ? 1 : 0
If the statement is true, a will be one (which it is), otherwise it will be 0.
That's called a ternary operator, and it's a cute, if sometimes hard to read, way of writing an IF statement.
if ( x == 3) {
do-magic
}
else {
do-other-magic
}
would be expressed like so:
x == 3 ? do-magic : do-other-magic