I have been working with Java a couple of years, but up until recently I haven't run across this construct:
int count = isHere ? getHereCount(index) : getAwayCount(index);
This is probably a very simple question, but can someone explain it? How do I read it? I am pretty sure I know how it works.
if isHere is true, getHereCount() is called,
if isHere is false getAwayCount() is called.
Correct? What is this construct called?
Yes, it is a shorthand form of
int count;
if (isHere)
count = getHereCount(index);
else
count = getAwayCount(index);
It's called the conditional operator. Many people (erroneously) call it the ternary operator, because it's the only ternary (three-argument) operator in Java, C, C++, and probably many other languages. But theoretically there could be another ternary operator, whereas there can only be one conditional operator.
The official name is given in the Java Language Specification:
§15.25 Conditional Operator ? :
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
Note that both branches must lead to methods with return values:
It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.
In fact, by the grammar of expression statements (§14.8), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.
So, if doSomething() and doSomethingElse() are void methods, you cannot compress this:
if (someBool)
doSomething();
else
doSomethingElse();
into this:
someBool ? doSomething() : doSomethingElse();
Simple words:
booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse
Others have answered this to reasonable extent, but often with the name "ternary operator".
Being the pedant that I am, I'd like to make it clear that the name of the operator is the conditional operator or "conditional operator ?:". It's a ternary operator (in that it has three operands) and it happens to be the only ternary operator in Java at the moment.
However, the spec is pretty clear that its name is the conditional operator or "conditional operator ?:" to be absolutely unambiguous. I think it's clearer to call it by that name, as it indicates the behaviour of the operator to some extent (evaluating a condition) rather than just how many operands it has.
According to the Sun Java Specification, it's called the Conditional Operator. See section 15.25. You're right as to what it does.
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
The conditional operator is syntactically right-associative (it groups right-to-left), so that a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).
ConditionalExpression:
ConditionalOrExpression
ConditionalOrExpression ? Expression : ConditionalExpression
The conditional operator has three operand expressions; ? appears between the first and second expressions, and : appears between the second and third expressions.
The first expression must be of type boolean or Boolean, or a compile-time error occurs.
condition ? truth : false;
If the condition is true then evaluate the first expression. If the condition is false, evaluate the second expression.
It is called the Conditional Operator and it is a type of Ternary Operation.
int count = isHere ? getHereCount(index) : getAwayCount(index);
means :
if (isHere) {
count = getHereCount(index);
} else {
count = getAwayCount(index);
}
Not exactly correct, to be precise:
if isHere is true, the result of getHereCount() is returned
otheriwse the result of getAwayCount() is returned
That "returned" is very important. It means the methods must return a value and that value must be assigned somewhere.
Also, it's not exactly syntactically equivalent to the if-else version. For example:
String str1,str2,str3,str4;
boolean check;
//...
return str1 + (check ? str2 : str3) + str4;
If coded with if-else will always result in more bytecode.
Ternary, conditional; tomato, tomatoh. What it's really valuable for is variable initialization. If (like me) you're fond of initializing variables where they are defined, the conditional ternary operator (for it is both) permits you to do that in cases where there is conditionality about its value. Particularly notable in final fields, but useful elsewhere, too.
e.g.:
public class Foo {
final double value;
public Foo(boolean positive, double value) {
this.value = positive ? value : -value;
}
}
Without that operator - by whatever name - you would have to make the field non-final or write a function simply to initialize it. Actually, that's not right - it can still be initialized using if/else, at least in Java. But I find this cleaner.
You might be interested in a proposal for some new operators that are similar to the conditional operator. The null-safe operators will enable code like this:
String s = mayBeNull?.toString() ?: "null";
It would be especially convenient where auto-unboxing takes place.
Integer ival = ...; // may be null
int i = ival ?: -1; // no NPE from unboxing
It has been selected for further consideration under JDK 7's "Project Coin."
This construct is called Ternary Operator in Computer Science and Programing techniques. And Wikipedia suggest the following explanation:
In computer science, a ternary operator (sometimes incorrectly called a tertiary operator) is an operator that takes three arguments. The arguments and result can be of different types. Many programming languages that use C-like syntax feature a ternary operator, ?: , which defines a conditional expression.
Not only in Java, this syntax is available within PHP, Objective-C too.
In the following link it gives the following explanation, which is quiet good to understand it:
A ternary operator is some operation operating on 3 inputs. It's a shortcut for an if-else statement, and is also known as a conditional operator.
In Perl/PHP it works as: boolean_condition ? true_value : false_value
In C/C++ it works as: logical expression ? action for true : action for false
This might be readable for some logical conditions which are not too complex otherwise it is better to use If-Else block with intended combination of conditional logic.
We can simplify the If-Else blocks with this Ternary operator for one code statement line.For Example:
if ( car.isStarted() ) {
car.goForward();
} else {
car.startTheEngine();
}
Might be equal to the following:
( car.isStarted() ) ? car.goForward() : car.startTheEngine();
So if we refer to your statement:
int count = isHere ? getHereCount(index) : getAwayCount(index);
It is actually the 100% equivalent of the following If-Else block:
int count;
if (isHere) {
count = getHereCount(index);
} else {
count = getAwayCount(index);
}
That's it!
Hope this was helpful to somebody!
Cheers!
Correct. It's called the ternary operator. Some also call it the conditional operator.
Its Ternary Operator(?:)
The ternary operator is an operator that takes three arguments. The first
argument is a comparison argument, the second is the result upon a true
comparison, and the third is the result upon a false comparison.
Actually it can take more than 3 arguments. For instance if we want to check wether a number is positive, negative or zero we can do this:
String m= num > 0 ? "is a POSITIVE NUMBER.": num < 0 ?"is a NEGATIVE NUMBER." :"IT's ZERO.";
which is better than using if, else if, else.
?: is a Ternary Java Operator.
Its syntax is:
condition ? expression1 : expression2;
Here, the condition is evaluated and
condition returns true, the expression1 will execute.
condition returns false, the expression2 will execute.
public class Sonycode {
public static void main(String[] args) {
double marks = 90;
String result = (marks > 40) ? "passed in exam" : "failed in exam";
System.out.println("Your result is : " + result);
}
}
Output :-
Your result is : passed in exam
It's the conditional operator, and it's more than just a concise way of writing if statements.
Since it is an expression that returns a value it can be used as part of other expressions.
Yes, you are correct. ?: is typically called the "ternary conditional operator", often referred to as simply "ternary operator". It is a shorthand version of the standard if/else conditional.
Ternary Conditional Operator
I happen to really like this operator, but the reader should be taken into consideration.
You always have to balance code compactness with the time spent reading it, and in that it has some pretty severe flaws.
First of all, there is the Original Asker's case. He just spent an hour posting about it and reading the responses. How longer would it have taken the author to write every ?: as an if/then throughout the course of his entire life. Not an hour to be sure.
Secondly, in C-like languages, you get in the habit of simply knowing that conditionals are the first thing in the line. I noticed this when I was using Ruby and came across lines like:
callMethodWhatever(Long + Expression + with + syntax) if conditional
If I was a long time Ruby user I probably wouldn't have had a problem with this line, but coming from C, when you see "callMethodWhatever" as the first thing in the line, you expect it to be executed. The ?: is less cryptic, but still unusual enough as to throw a reader off.
The advantage, however, is a really cool feeling in your tummy when you can write a 3-line if statement in the space of 1 of the lines. Can't deny that :) But honestly, not necessarily more readable by 90% of the people out there simply because of its' rarity.
When it is truly an assignment based on a Boolean and values I don't have a problem with it, but it can easily be abused.
Conditional expressions are in a completely different style, with no explicit if in the statement.
The syntax is:
boolean-expression ? expression1 : expression2;
The result of this conditional expression is
expression1 if boolean-expression is true;
otherwise the result is expression2.
Suppose you want to assign the larger number of variable num1 and num2 to max. You can simply write a statement using the conditional expression:
max = (num1 > num2) ? num1 : num2;
Note: The symbols ? and : appear together in a conditional expression. They form a conditional operator and also called a ternary operator because it uses three operands. It is the only ternary operator in Java.
cited from: Intro to Java Programming 10th edition by Y. Daniel Liang page 126 - 127
Related
I have been working with Java a couple of years, but up until recently I haven't run across this construct:
int count = isHere ? getHereCount(index) : getAwayCount(index);
This is probably a very simple question, but can someone explain it? How do I read it? I am pretty sure I know how it works.
if isHere is true, getHereCount() is called,
if isHere is false getAwayCount() is called.
Correct? What is this construct called?
Yes, it is a shorthand form of
int count;
if (isHere)
count = getHereCount(index);
else
count = getAwayCount(index);
It's called the conditional operator. Many people (erroneously) call it the ternary operator, because it's the only ternary (three-argument) operator in Java, C, C++, and probably many other languages. But theoretically there could be another ternary operator, whereas there can only be one conditional operator.
The official name is given in the Java Language Specification:
§15.25 Conditional Operator ? :
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
Note that both branches must lead to methods with return values:
It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.
In fact, by the grammar of expression statements (§14.8), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.
So, if doSomething() and doSomethingElse() are void methods, you cannot compress this:
if (someBool)
doSomething();
else
doSomethingElse();
into this:
someBool ? doSomething() : doSomethingElse();
Simple words:
booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse
Others have answered this to reasonable extent, but often with the name "ternary operator".
Being the pedant that I am, I'd like to make it clear that the name of the operator is the conditional operator or "conditional operator ?:". It's a ternary operator (in that it has three operands) and it happens to be the only ternary operator in Java at the moment.
However, the spec is pretty clear that its name is the conditional operator or "conditional operator ?:" to be absolutely unambiguous. I think it's clearer to call it by that name, as it indicates the behaviour of the operator to some extent (evaluating a condition) rather than just how many operands it has.
According to the Sun Java Specification, it's called the Conditional Operator. See section 15.25. You're right as to what it does.
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
The conditional operator is syntactically right-associative (it groups right-to-left), so that a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).
ConditionalExpression:
ConditionalOrExpression
ConditionalOrExpression ? Expression : ConditionalExpression
The conditional operator has three operand expressions; ? appears between the first and second expressions, and : appears between the second and third expressions.
The first expression must be of type boolean or Boolean, or a compile-time error occurs.
condition ? truth : false;
If the condition is true then evaluate the first expression. If the condition is false, evaluate the second expression.
It is called the Conditional Operator and it is a type of Ternary Operation.
int count = isHere ? getHereCount(index) : getAwayCount(index);
means :
if (isHere) {
count = getHereCount(index);
} else {
count = getAwayCount(index);
}
Not exactly correct, to be precise:
if isHere is true, the result of getHereCount() is returned
otheriwse the result of getAwayCount() is returned
That "returned" is very important. It means the methods must return a value and that value must be assigned somewhere.
Also, it's not exactly syntactically equivalent to the if-else version. For example:
String str1,str2,str3,str4;
boolean check;
//...
return str1 + (check ? str2 : str3) + str4;
If coded with if-else will always result in more bytecode.
Ternary, conditional; tomato, tomatoh. What it's really valuable for is variable initialization. If (like me) you're fond of initializing variables where they are defined, the conditional ternary operator (for it is both) permits you to do that in cases where there is conditionality about its value. Particularly notable in final fields, but useful elsewhere, too.
e.g.:
public class Foo {
final double value;
public Foo(boolean positive, double value) {
this.value = positive ? value : -value;
}
}
Without that operator - by whatever name - you would have to make the field non-final or write a function simply to initialize it. Actually, that's not right - it can still be initialized using if/else, at least in Java. But I find this cleaner.
You might be interested in a proposal for some new operators that are similar to the conditional operator. The null-safe operators will enable code like this:
String s = mayBeNull?.toString() ?: "null";
It would be especially convenient where auto-unboxing takes place.
Integer ival = ...; // may be null
int i = ival ?: -1; // no NPE from unboxing
It has been selected for further consideration under JDK 7's "Project Coin."
This construct is called Ternary Operator in Computer Science and Programing techniques. And Wikipedia suggest the following explanation:
In computer science, a ternary operator (sometimes incorrectly called a tertiary operator) is an operator that takes three arguments. The arguments and result can be of different types. Many programming languages that use C-like syntax feature a ternary operator, ?: , which defines a conditional expression.
Not only in Java, this syntax is available within PHP, Objective-C too.
In the following link it gives the following explanation, which is quiet good to understand it:
A ternary operator is some operation operating on 3 inputs. It's a shortcut for an if-else statement, and is also known as a conditional operator.
In Perl/PHP it works as: boolean_condition ? true_value : false_value
In C/C++ it works as: logical expression ? action for true : action for false
This might be readable for some logical conditions which are not too complex otherwise it is better to use If-Else block with intended combination of conditional logic.
We can simplify the If-Else blocks with this Ternary operator for one code statement line.For Example:
if ( car.isStarted() ) {
car.goForward();
} else {
car.startTheEngine();
}
Might be equal to the following:
( car.isStarted() ) ? car.goForward() : car.startTheEngine();
So if we refer to your statement:
int count = isHere ? getHereCount(index) : getAwayCount(index);
It is actually the 100% equivalent of the following If-Else block:
int count;
if (isHere) {
count = getHereCount(index);
} else {
count = getAwayCount(index);
}
That's it!
Hope this was helpful to somebody!
Cheers!
Correct. It's called the ternary operator. Some also call it the conditional operator.
Its Ternary Operator(?:)
The ternary operator is an operator that takes three arguments. The first
argument is a comparison argument, the second is the result upon a true
comparison, and the third is the result upon a false comparison.
Actually it can take more than 3 arguments. For instance if we want to check wether a number is positive, negative or zero we can do this:
String m= num > 0 ? "is a POSITIVE NUMBER.": num < 0 ?"is a NEGATIVE NUMBER." :"IT's ZERO.";
which is better than using if, else if, else.
?: is a Ternary Java Operator.
Its syntax is:
condition ? expression1 : expression2;
Here, the condition is evaluated and
condition returns true, the expression1 will execute.
condition returns false, the expression2 will execute.
public class Sonycode {
public static void main(String[] args) {
double marks = 90;
String result = (marks > 40) ? "passed in exam" : "failed in exam";
System.out.println("Your result is : " + result);
}
}
Output :-
Your result is : passed in exam
It's the conditional operator, and it's more than just a concise way of writing if statements.
Since it is an expression that returns a value it can be used as part of other expressions.
Yes, you are correct. ?: is typically called the "ternary conditional operator", often referred to as simply "ternary operator". It is a shorthand version of the standard if/else conditional.
Ternary Conditional Operator
I happen to really like this operator, but the reader should be taken into consideration.
You always have to balance code compactness with the time spent reading it, and in that it has some pretty severe flaws.
First of all, there is the Original Asker's case. He just spent an hour posting about it and reading the responses. How longer would it have taken the author to write every ?: as an if/then throughout the course of his entire life. Not an hour to be sure.
Secondly, in C-like languages, you get in the habit of simply knowing that conditionals are the first thing in the line. I noticed this when I was using Ruby and came across lines like:
callMethodWhatever(Long + Expression + with + syntax) if conditional
If I was a long time Ruby user I probably wouldn't have had a problem with this line, but coming from C, when you see "callMethodWhatever" as the first thing in the line, you expect it to be executed. The ?: is less cryptic, but still unusual enough as to throw a reader off.
The advantage, however, is a really cool feeling in your tummy when you can write a 3-line if statement in the space of 1 of the lines. Can't deny that :) But honestly, not necessarily more readable by 90% of the people out there simply because of its' rarity.
When it is truly an assignment based on a Boolean and values I don't have a problem with it, but it can easily be abused.
Conditional expressions are in a completely different style, with no explicit if in the statement.
The syntax is:
boolean-expression ? expression1 : expression2;
The result of this conditional expression is
expression1 if boolean-expression is true;
otherwise the result is expression2.
Suppose you want to assign the larger number of variable num1 and num2 to max. You can simply write a statement using the conditional expression:
max = (num1 > num2) ? num1 : num2;
Note: The symbols ? and : appear together in a conditional expression. They form a conditional operator and also called a ternary operator because it uses three operands. It is the only ternary operator in Java.
cited from: Intro to Java Programming 10th edition by Y. Daniel Liang page 126 - 127
I have been working with Java a couple of years, but up until recently I haven't run across this construct:
int count = isHere ? getHereCount(index) : getAwayCount(index);
This is probably a very simple question, but can someone explain it? How do I read it? I am pretty sure I know how it works.
if isHere is true, getHereCount() is called,
if isHere is false getAwayCount() is called.
Correct? What is this construct called?
Yes, it is a shorthand form of
int count;
if (isHere)
count = getHereCount(index);
else
count = getAwayCount(index);
It's called the conditional operator. Many people (erroneously) call it the ternary operator, because it's the only ternary (three-argument) operator in Java, C, C++, and probably many other languages. But theoretically there could be another ternary operator, whereas there can only be one conditional operator.
The official name is given in the Java Language Specification:
§15.25 Conditional Operator ? :
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
Note that both branches must lead to methods with return values:
It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.
In fact, by the grammar of expression statements (§14.8), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.
So, if doSomething() and doSomethingElse() are void methods, you cannot compress this:
if (someBool)
doSomething();
else
doSomethingElse();
into this:
someBool ? doSomething() : doSomethingElse();
Simple words:
booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse
Others have answered this to reasonable extent, but often with the name "ternary operator".
Being the pedant that I am, I'd like to make it clear that the name of the operator is the conditional operator or "conditional operator ?:". It's a ternary operator (in that it has three operands) and it happens to be the only ternary operator in Java at the moment.
However, the spec is pretty clear that its name is the conditional operator or "conditional operator ?:" to be absolutely unambiguous. I think it's clearer to call it by that name, as it indicates the behaviour of the operator to some extent (evaluating a condition) rather than just how many operands it has.
According to the Sun Java Specification, it's called the Conditional Operator. See section 15.25. You're right as to what it does.
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
The conditional operator is syntactically right-associative (it groups right-to-left), so that a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).
ConditionalExpression:
ConditionalOrExpression
ConditionalOrExpression ? Expression : ConditionalExpression
The conditional operator has three operand expressions; ? appears between the first and second expressions, and : appears between the second and third expressions.
The first expression must be of type boolean or Boolean, or a compile-time error occurs.
condition ? truth : false;
If the condition is true then evaluate the first expression. If the condition is false, evaluate the second expression.
It is called the Conditional Operator and it is a type of Ternary Operation.
int count = isHere ? getHereCount(index) : getAwayCount(index);
means :
if (isHere) {
count = getHereCount(index);
} else {
count = getAwayCount(index);
}
Not exactly correct, to be precise:
if isHere is true, the result of getHereCount() is returned
otheriwse the result of getAwayCount() is returned
That "returned" is very important. It means the methods must return a value and that value must be assigned somewhere.
Also, it's not exactly syntactically equivalent to the if-else version. For example:
String str1,str2,str3,str4;
boolean check;
//...
return str1 + (check ? str2 : str3) + str4;
If coded with if-else will always result in more bytecode.
Ternary, conditional; tomato, tomatoh. What it's really valuable for is variable initialization. If (like me) you're fond of initializing variables where they are defined, the conditional ternary operator (for it is both) permits you to do that in cases where there is conditionality about its value. Particularly notable in final fields, but useful elsewhere, too.
e.g.:
public class Foo {
final double value;
public Foo(boolean positive, double value) {
this.value = positive ? value : -value;
}
}
Without that operator - by whatever name - you would have to make the field non-final or write a function simply to initialize it. Actually, that's not right - it can still be initialized using if/else, at least in Java. But I find this cleaner.
You might be interested in a proposal for some new operators that are similar to the conditional operator. The null-safe operators will enable code like this:
String s = mayBeNull?.toString() ?: "null";
It would be especially convenient where auto-unboxing takes place.
Integer ival = ...; // may be null
int i = ival ?: -1; // no NPE from unboxing
It has been selected for further consideration under JDK 7's "Project Coin."
This construct is called Ternary Operator in Computer Science and Programing techniques. And Wikipedia suggest the following explanation:
In computer science, a ternary operator (sometimes incorrectly called a tertiary operator) is an operator that takes three arguments. The arguments and result can be of different types. Many programming languages that use C-like syntax feature a ternary operator, ?: , which defines a conditional expression.
Not only in Java, this syntax is available within PHP, Objective-C too.
In the following link it gives the following explanation, which is quiet good to understand it:
A ternary operator is some operation operating on 3 inputs. It's a shortcut for an if-else statement, and is also known as a conditional operator.
In Perl/PHP it works as: boolean_condition ? true_value : false_value
In C/C++ it works as: logical expression ? action for true : action for false
This might be readable for some logical conditions which are not too complex otherwise it is better to use If-Else block with intended combination of conditional logic.
We can simplify the If-Else blocks with this Ternary operator for one code statement line.For Example:
if ( car.isStarted() ) {
car.goForward();
} else {
car.startTheEngine();
}
Might be equal to the following:
( car.isStarted() ) ? car.goForward() : car.startTheEngine();
So if we refer to your statement:
int count = isHere ? getHereCount(index) : getAwayCount(index);
It is actually the 100% equivalent of the following If-Else block:
int count;
if (isHere) {
count = getHereCount(index);
} else {
count = getAwayCount(index);
}
That's it!
Hope this was helpful to somebody!
Cheers!
Correct. It's called the ternary operator. Some also call it the conditional operator.
Its Ternary Operator(?:)
The ternary operator is an operator that takes three arguments. The first
argument is a comparison argument, the second is the result upon a true
comparison, and the third is the result upon a false comparison.
Actually it can take more than 3 arguments. For instance if we want to check wether a number is positive, negative or zero we can do this:
String m= num > 0 ? "is a POSITIVE NUMBER.": num < 0 ?"is a NEGATIVE NUMBER." :"IT's ZERO.";
which is better than using if, else if, else.
?: is a Ternary Java Operator.
Its syntax is:
condition ? expression1 : expression2;
Here, the condition is evaluated and
condition returns true, the expression1 will execute.
condition returns false, the expression2 will execute.
public class Sonycode {
public static void main(String[] args) {
double marks = 90;
String result = (marks > 40) ? "passed in exam" : "failed in exam";
System.out.println("Your result is : " + result);
}
}
Output :-
Your result is : passed in exam
It's the conditional operator, and it's more than just a concise way of writing if statements.
Since it is an expression that returns a value it can be used as part of other expressions.
Yes, you are correct. ?: is typically called the "ternary conditional operator", often referred to as simply "ternary operator". It is a shorthand version of the standard if/else conditional.
Ternary Conditional Operator
I happen to really like this operator, but the reader should be taken into consideration.
You always have to balance code compactness with the time spent reading it, and in that it has some pretty severe flaws.
First of all, there is the Original Asker's case. He just spent an hour posting about it and reading the responses. How longer would it have taken the author to write every ?: as an if/then throughout the course of his entire life. Not an hour to be sure.
Secondly, in C-like languages, you get in the habit of simply knowing that conditionals are the first thing in the line. I noticed this when I was using Ruby and came across lines like:
callMethodWhatever(Long + Expression + with + syntax) if conditional
If I was a long time Ruby user I probably wouldn't have had a problem with this line, but coming from C, when you see "callMethodWhatever" as the first thing in the line, you expect it to be executed. The ?: is less cryptic, but still unusual enough as to throw a reader off.
The advantage, however, is a really cool feeling in your tummy when you can write a 3-line if statement in the space of 1 of the lines. Can't deny that :) But honestly, not necessarily more readable by 90% of the people out there simply because of its' rarity.
When it is truly an assignment based on a Boolean and values I don't have a problem with it, but it can easily be abused.
Conditional expressions are in a completely different style, with no explicit if in the statement.
The syntax is:
boolean-expression ? expression1 : expression2;
The result of this conditional expression is
expression1 if boolean-expression is true;
otherwise the result is expression2.
Suppose you want to assign the larger number of variable num1 and num2 to max. You can simply write a statement using the conditional expression:
max = (num1 > num2) ? num1 : num2;
Note: The symbols ? and : appear together in a conditional expression. They form a conditional operator and also called a ternary operator because it uses three operands. It is the only ternary operator in Java.
cited from: Intro to Java Programming 10th edition by Y. Daniel Liang page 126 - 127
I often use the following if block (no else/elseif clauses;just for a specific check)
if(value==10){system.out.print("true");}
So I tried using it with the ternary:
(a==1)?System.out.println("true");
but it is not working. Mainly, I wanted to know that does ternary operator can act like a single if? (and although I haven't pondered over it, but can it work like an if-else_if-else clause?)
What you are trying to achieve isn't possible. If you must use a ternary, though, try this
String a = (value==10) ? "Yes" : "No";
System.out.println(a);
Otherwise you can also do this,
System.out.println((value==10)?"Yes":"No");
The ternary operator is just shorthand for if-else, but it MUST return something. You need to use the format
something = (x)?(if x==true, return this):(if x==false, return this)
To do what you want, put a ternary inside the print statement. I.E.
System.out.println((a==1)?("true"):(""));
First of all as mentioned by Kevin, the ternary operator should have a left hand assignment variable.
Secondly it should be always accompanied with an else operation
Following expressions works.
String s = a==10 ? "true" : "false";
System.out.println(s);
Adding to the above-mentionned answers, in case of aggregating a string to your expression you can use the below code snippet:
System.out.println("any text you want"+ (value == 10)?"value is greater than 10":"value is lower than 10");
This question already has answers here:
Java: Ternary with no return. (For method calling)
(6 answers)
Closed 7 years ago.
I was wondering how this code would look like with the ternary operator
if (a) {
// pass
} else {
b();
}
We got no(thing) code to execute when a is true but in case a is false there is some code b() which is then executed.
So we write that:
a ? : b();
But I am not sure if that is correct when you let the code for true empty or if you have to replace it with something. Actually I never use the ternary operator but we were asked to do so.
That's not what the conditional operator is for... it's not to execute one statement or another, it's to evaluate one expression or another, and make that the result of the expression.
You should write your code as:
if (!a) {
b();
}
Actually I never use the ternary operator but we were asked to do so.
If you were asked to do so for this particular situation, then I would be very wary of whoever was asking you to do so. My guess is that it was actually not quite this situation...
If you had tried this code, then you would get compiler errors because the ternary operator expects expressions, not statements. The true section doesn't even have an expression or a statement. If b() returns void, then the false section is a statement, not an expression. If b() returns something, then it can be considered an expression and it would be ok.
If you have statements to execute, and you don't have to choose an expression value, then choose if/else over the ternary operator. Your first if/else can be simplified to:
if (!a)
{
b();
}
This isn't possible. Taken from the official Oracle Docs:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25
The conditional operator ? : uses the boolean value of one expression
to decide which of two other expressions should be evaluated.
ConditionalExpression:
ConditionalOrExpression
ConditionalOrExpression ? Expression : ConditionalExpression
The definition of "ternary" is "Composed of 3 parts". If you want only one possible evaluation of your condition, you will just have to use an if statement.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Ternary conditional operator in Python
I've programmed in Java for quite sometime, I'm learning Python in school and I remember in Java for a boolean expression you could do
boolean ? (if boolean is true this happens) : (if boolean is false this happens)
Is their a way to do the above Java code in Python? And what is the statement above properly called?
Yes, use a conditional expression:
somevalue if oneexpression else othervalue
Examples:
>>> 'foo' if True else 'bar'
'foo'
>>> 'foo' if False else 'bar'
'bar'
Before Python 2.5 where this was introduced, people used a combination of and and or expressions to achieve similar results:
expression and truevalue or falsevalue
but if the truevalue part of the expression itself evaluated to something that has the boolean value False (so a 0 or None or any sequence with length 0, etc.) then falsevalue would be picked anyway.
Python:
x if condition else y
Example:
val = val() if callable(val) else val
greeting = ("Hi " + name) if name != "" else "Howdy pardner"
This is often called "the ternary operator" because it has three operands. However, the term "ternary operator" applies to any operation with three operands. It just happens that most programming languages don't have any other ternary operators, so saying "the" is unambiguous. However, I'd call it the if/else operator or a conditional expression.
In Python, due to the way the and and or operators work, you can also use them in some cases for things you'd usually use the ternary operator for in C-derived languages:
# provide a default value if user doesn't enter one
name = raw_input("What is your name? ") or "Jude"
print "Hey", name, "don't make it bad."
# call x only if x is callable
callable(x) and x()
Yes, you can use this (more pythonic):
>>> "foo"'if condition else "bar"
Or, this (more common, but not recommended):
>>> condition and "foo" or "bar"