This question already has answers here:
java ternary operator
(2 answers)
Closed 9 years ago.
I think this question is a general programming question,
but let's assume I'm asking this for Java.
what does the following statement do ?
return a ? (b || c) : (b && c);
I have seen the syntax with ?'s and :'s in many topics at SO, this particular one I found in Check if at least two out of three booleans are true
But I don't know what they mean, so how to use them, and I believe it's something very useful for me.
Thanks !
That's the conditional operator. It means something like:
condition ? value-if-true : value-if-false;
So in your case, it returns b || c if a is true, and b && c if a is false.
This is known as a ternary statement; it's shorthand for an if-else block - you can google that for more info.
Your example is equivalent to
if (a) {
return (b || c);
} else {
return (b && c);
}
condition ? first statement : second statement
if condition is true then first statement is executed otherwise the second statement
It's the ternary operator, the whole statement expands to something more like this:
if a == true then
if b == true or c == true then
return true
else
if b == true and c == true then
return true
As your link says a much more elegant way to check if at least 2 out of three booleans are true when applied in this way!
its an conditional operator... jst like if and else....
e.g----
a<b ? 4 :5 where a= 2 and b=5
as a is less then b.... then this operator will return 4... else it return 5....
in short... if your condition i.e statement before ? is correct then it returns 1st value.. i.e statement before colon.... else it returns 2nd value......
According to your code,
return a ? (b || c) : (b && c);
Result will be like this :
if a == true , then result = b || c
otherwise result = b && c
its a ternary operator & used in most of the languages C,C++, java, Javascript
Related
This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 7 years ago.
Two questions about using a question mark "?" and colon ":" operator within the parentheses of a print function: What do they do? Also, does anyone know the standard term for them or where I can find more information on their use? I've read that they are similar to an 'if' 'else' statement.
int row = 10;
int column;
while (row >= 1)
{
column = 1;
while(column <= 10)
{
System.out.print(row % 2 == 1 ? "<" : "\r>");
++column;
}
--row;
System.out.println();
}
This is the ternary conditional operator, which can be used anywhere, not just the print statement. It's sometimes just called "the ternary operator", but it's not the only ternary operator, just the most common one.
Here's a good example from Wikipedia demonstrating how it works:
A traditional if-else construct in C, Java and JavaScript is written:
if (a > b) {
result = x;
} else {
result = y;
}
This can be rewritten as the following statement:
result = a > b ? x : y;
Basically it takes the form:
boolean statement ? true result : false result;
So if the boolean statement is true, you get the first part, and if it's false you get the second one.
Try these if that still doesn't make sense:
System.out.println(true ? "true!" : "false.");
System.out.println(false ? "true!" : "false.");
Thats an if/else statement equilavent to
if(row % 2 == 1){
System.out.print("<");
}else{
System.out.print("\r>");
}
a=1;
b=2;
x=3;
y=4;
answer = a > b ? x : y;
answer=4 since the condition is false it takes y value.
A question mark (?)
. The value to use if the condition is true
A colon (:)
. The value to use if the condition is false
Also just though I'd post the answer to another related question I had,
a = x ? : y;
Is equivalent to:
a = x ? x : y;
If x is false or null then the value of y is taken.
Maybe It can be perfect example for Android,
For example:
void setWaitScreen(boolean set) {
findViewById(R.id.screen_main).setVisibility(
set ? View.GONE : View.VISIBLE);
findViewById(R.id.screen_wait).setVisibility(
set ? View.VISIBLE : View.GONE);
}
They are called the ternary operator since they are the only one in Java.
The difference to the if...else construct is, that they return something, and this something can be anything:
int k = a > b ? 7 : 8;
String s = (foobar.isEmpty ()) ? "empty" : foobar.toString ();
it is a ternary operator and in simple english it states "if row%2 is equal to 1 then return < else return /r"
This question already has answers here:
Ternary Operator
(4 answers)
Closed 4 years ago.
Consider the following code:
i = (i == array.length-1) ? 0 : i + 1;
As I understand, the conditional operator works as follows:
booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse
What does 0 execute?
I do not think the "positive conditional test result" really has a formal name.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html
?: Ternary (shorthand for
if-then-else statement)
using a boolean example
isConditionTrue = 1 == 2 ? true : false;
this in your example
i = (i == array.length-1) ? 0 : i + 1;
has the same result as
if (i == array.length-1)
{i= 0 ;}
else {i = i + 1;}
This is known as the Elvis Operator (see [https://en.wikipedia.org/wiki/Elvis_operator]) and given the following example:
x = A ? B : C;
... it means that if A is evaluated to 'true' than x gets assigned the value B otherwise it gets assigned the value C.
In your example it means, that if 'i==array.length-1' then 'i' is set to '0' otherwise 'i' is set to 'i+1'.
I have a question about IF clause in Java.
I have and expression:
if ((someObject != null & connectedToTheInternet) || operate) {
// some action
}
Is my logic right: if someObject != null equals to true and connectedToTheInternet equals false then we have (someObject != null & connectedToTheInternet) equals false and then we have the following block:
if (false || operate) {
// some action
}
And if operate equals true then // some action will be triggered?
Just a first note: logical AND operator is "&&" and not just "&" (bitwise AND).
Following, your answer is YES... JVM will run conditions following your thinking.
By the way, I suggest you to read something abot short-circuit of these operators: it can be interesting if you are learning.
For example if you have if (a && (b || c) and a==false, then JVM won't evaluate b or c conditions because false && ... will be always false.
The same in the case of if (a || b || c && d): if a==true then JVM will ignore the other parts and consider it as true because true || .... will be always true.
Yes. if-clauses are evaluated from left to right. If no parenthesis are used, && has precedence, even higher precedence has ! (not) - similar to multiplication (AND), addition (OR) and negative numbers (-) in math (e.g. "A && (B || C) != A && B || C == (A && B) ||C") - I recommend to use parenthesis if you are unsure. This makes it possible to combine != null checks and calls to methods in the same if statement (e.g., if (object!=null && object.dosomething())).
Btw. there is a difference between & and && (short-circuit), when & is used, the second condition gets evaluated even if the first is false already. When && is used, Java doesn't check the second condition if the first one is false as the whole term cannot be true anymore - this is only important when the second condition is not a boolean variable but a method (which gets called or not -> side effects; this "skipping" is called short-circuit). Same for || and | where the second operator might not get evaluated if the first is already true (in case of ||).
Normally only ||and && are used.
Just for completeness: & is also the bitwise AND operator in Java.
if (false || operate) {
// some action
}
If operate true then if block executing.
This question already has answers here:
What is the difference between & and && in Java?
(15 answers)
Closed 9 years ago.
I'm doing past paper for exam
public static void triangleTest( int a, int b, int c)
{
if ( a > 0 & b > 0 & c > 0 )
{
if ( a==b || b==c );
{
System.out.println("Equilateral");
}
else if ( a==b || a==c || b!=c )
System.out.println("Scalene");
}
else if ( a+b>c && a+c>b || b+c>a );
{
System.out.println(Isoceles);
}
}
else
{
System.out.println("");
}
}
I have been given this code and told to find mistakes, and when i checked the answers
if ( a > 0 & b > 0 & c > 0 )
this has been identified as mistake and && were meant to be used instead of & I ran the code and it worked fine with &, so my question would be what's what's the reasoning behind this?
& evaluates both values
where as && checks the first one if it's false it sets result as false.
If you are using & it will check second condition although first is false.
While in && it will not check next condition if first is false.
In some case it may cause exceptions.
For ex:
// Some Code
if ( a != null & a.length() > 0 ){
//coding part
}
above code will throw NullPointerException with & if a is null. because it will check second condition every time either first is true or false.
so it will go like this...
// Some Code
if ( a !=null && a.length() > 0 ){
//coding part
}
For more : refer this SO Que
& is a bitwise operator whereas && is a logical and operator.
Principles of short circuit does not apply in bitwise and operator i.e &.
& <-- verifies both operands
&& <-- stops evaluating if the first operand evaluates to false since the result will be false
Short circuiting leads to efficient code
&& is the logical and and it is short circuited. & is the bitwise and. Although for other cases it is very different; for booleans the (practical) difference is just that it doesn't short circuit.
Short circuiting means it skips evaluating conditions that can't affect the outcome. For exampple
if(cheapTest() && expensiveTest() && expensiveTest2())
If the first test is false the expresion must be false, so it can not bother with the expensive tests.
if(FALSE && DONTCARE && DONTCARE)
The reverse is true for | vs ||.
Protection against exceptions
This can be even more important where the second test may raise exceptions if evaluated, for example
if (someObject!=null && someObject.someTest())
In this case if someObject is null then someObject.someTest() never runs, this is a common pattern when null values are expected. Where you to use the bitwise and both tests would run in all cases and if someObject was null you would recieve a NullPointerException
This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 7 years ago.
Two questions about using a question mark "?" and colon ":" operator within the parentheses of a print function: What do they do? Also, does anyone know the standard term for them or where I can find more information on their use? I've read that they are similar to an 'if' 'else' statement.
int row = 10;
int column;
while (row >= 1)
{
column = 1;
while(column <= 10)
{
System.out.print(row % 2 == 1 ? "<" : "\r>");
++column;
}
--row;
System.out.println();
}
This is the ternary conditional operator, which can be used anywhere, not just the print statement. It's sometimes just called "the ternary operator", but it's not the only ternary operator, just the most common one.
Here's a good example from Wikipedia demonstrating how it works:
A traditional if-else construct in C, Java and JavaScript is written:
if (a > b) {
result = x;
} else {
result = y;
}
This can be rewritten as the following statement:
result = a > b ? x : y;
Basically it takes the form:
boolean statement ? true result : false result;
So if the boolean statement is true, you get the first part, and if it's false you get the second one.
Try these if that still doesn't make sense:
System.out.println(true ? "true!" : "false.");
System.out.println(false ? "true!" : "false.");
Thats an if/else statement equilavent to
if(row % 2 == 1){
System.out.print("<");
}else{
System.out.print("\r>");
}
a=1;
b=2;
x=3;
y=4;
answer = a > b ? x : y;
answer=4 since the condition is false it takes y value.
A question mark (?)
. The value to use if the condition is true
A colon (:)
. The value to use if the condition is false
Also just though I'd post the answer to another related question I had,
a = x ? : y;
Is equivalent to:
a = x ? x : y;
If x is false or null then the value of y is taken.
Maybe It can be perfect example for Android,
For example:
void setWaitScreen(boolean set) {
findViewById(R.id.screen_main).setVisibility(
set ? View.GONE : View.VISIBLE);
findViewById(R.id.screen_wait).setVisibility(
set ? View.VISIBLE : View.GONE);
}
They are called the ternary operator since they are the only one in Java.
The difference to the if...else construct is, that they return something, and this something can be anything:
int k = a > b ? 7 : 8;
String s = (foobar.isEmpty ()) ? "empty" : foobar.toString ();
it is a ternary operator and in simple english it states "if row%2 is equal to 1 then return < else return /r"