This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 10 years ago.
I dont know what the question mark (?) stand for in java, I was doing a small program, a Nim-game. were looking in a book, for help and saw this statement:
int pinsToTake = (min >= 2) ? 2 : 1;
I don't understand it, what will ? represent, can it be something to do with if-statement but you put it in a variable? and the : can be something "else"? (this things that I just said can be very misleading)
someval = (min >= 2) ? 2 : 1;
This is called ternary operator, which can be used as if-else. this is equivalent to
if((min >= 2) {
someval =2;
} else {
someval =1
}
Follow this tutorial for more info and usage.
Its ternary operator also referred to as the conditional operator, have a look reference
like Object bar = foo.isSelected() ? getSelected(foo) : getSelected(baz);
eg. operand1 ? operand2 : operand3
if operand1 is true, operand2 is returned, else operand3 is returned
operand1 must be a boolean type
operand1 can be an expression that evaluates to a boolean type
operand1 and operand2 must be promotable numeric types or castable object references, or null
if one of operand2 or operand3 is a byte and the other a short, the type of the returned value will be a short
if one of operand2 or operand3 is a byte, short or char and the other is a constant int value which will fit within the other operands
range, the type of the returned value will be the type of the other
operand
otherwise, normal binary numeric promotion applies
if one of operand2 or operand3 is a null, the type of the return will be the type of the other operand
if both operand2 and operand3 are different types, one of them must be compatible (castable) to the other type
reference
it means:
if(min >= 2)
someval =2;
else
someval =1
Its called a ternary operator
See this java example too
That's a Ternary Operator. Check Oracle's doc for further info. Long story short, it is an if-else statement that can be done in a single line and used inside methods and to define variable values.
Syntax:
boolean_expression ? do_if_true : do_if_false;
Parallelism with if-else statement:
if(boolean_expression)
//do_if_true;
else
//do_if_false;
I didn't use brackets on purpose, since you can only execute one line of code in do_if_true and do_if_false.
Example of use:
boolean hello = true;
String greetings = hello ? "Hello World!" : "No hello for you...";
This will set someString as "Hello World!" since the boolean variable hello evaluates to true. On the other hand, you can nest this expressions:
boolean hello = true;
boolean world = false;
String greetings = hello ? (world ? "Hello World!" : "Hello Stranger!") : "No hello for you...";
In this case, greetings will have as a value "Hello Stranger!";
It's called the Ternary If operator, it's just short-hand for an if...else
"? :" is a ternary operator equivalent to an if else statement.
In your example:
pinsToTake = (min >= 2) ? 2 : 1
if min >= 2 then assign 2 to pinsToTake, else assign 1
max = (a > b) ? a : b;
(a > b) ? a : b; is an expression which returns one of two values, a or b. The condition, (a > b), is tested. If it is true the first value, a, is returned. If it is false, the second value, b, is returned. Whichever value is returned is dependent on the conditional test, a > b. The condition can be any expression which returns a boolean value.
It is called conditional operator.This is how it works.
if min is greater than or equal to 2 ,then first value after ? that is 2 here will be assign to corresponding variable ,otherwise second value that is 1 here will be assign.
This link will tell you all you need.
Summary for archival sakes:
It's called the conditional operator. It's a ternary operator that
takes three terms:
BooleanExpression ? Expr1 : Expr2
The BooleanExpressionis evaluated. If it's true, the value of the
whole expression is Expr1. If it's false, the value of the whole
expression is Expr2.
So it serves the same kind of purpose as an if statement, but it's a
term rather than a whole statement. That means you can embed it in
places where you can't use a whole statement.
Related
I have a piece of code that uses a conditional operator to compare the value of the variable x to 5:
(x >=5 ? x : -x)
What benefit is there to using a conditional operator over a regular if else statement?
Note that is ?: is an expression - it returns a value which must be consumed
z = (x >=5 ? x : -x)
The if construct in Java is not an expression (there are languages where it is) and does not return a value so in this sense they are not equivalent.
An example where they are equivalent is when the if options perform an assignment:
if("Cheese".equals(x)) {
type = "Dairy";
} else {
type = "Maybe not dairy";
}
this is the same as
type = "Cheese".equals(x) ? "Dairy" : "Maybe not dairy";
You can nest ?: to arbitrary depth but really shouldn't - it becomes quite difficult to read:
List<String> cheeses = Arrays.asList("Gouda", "Edam");
String x= "Gouda";
String type = cheeses.contains(x) ? "Gouda".equals(x) ? "Yummy Gouda" : "Cheese - but not Gouda" : "Maybe not dairy";
Ternary operator is not the equivalent of if-else in EVERY possible case. This is because both of possible results of using ternary operator are return values (e. g. simple printing to the console is not a return value so it can't be one of possible results in ternary operator).
Look, you can do it with if-else, but it's not possible with ternary operator:
if (x > 5) {
System.out.println("Statement is true");
else {
System.out.println("Statement is false");
}
You can't do it with ternary operator:
x > 5 ? System.out.println("Statement is true") : System.out.println("Statement is false");
When both of results of using ternary operator are considered as return values, they are then an equivalent of if-else.
Yes, it can be used, but off course in that case using -x doesn't make sense so it depends on what do you want to return when String is an input. You can do this:
("Cheese".equals(x) ? <some object of expected type X> : <some other object of expected type X>)
where X can be String on any other type. And remember to do "string".equals(x) instead of x.equals("string"). This prevents NullPointerException.
For primitive values you can use ==, but for objects you need to use equals method. There are some edge cases when you can use == on String, but they are not relevant to your case I guess and you can read about it outside of this topic.
PS: Some answers talk about if else statement, but that's not what question is about.
Can this be used like an if else on all accounts? For example, can you
compare strings with it?
I am pretty sure that by saying like an if else he means conditional operator which has if else like behaviour, not if else instruction itself.
Yes it can be used in Java; however note that x =="Cheese" isn't the proper way to compare strings in Java, you want something like "Cheese".equals(x).
This question already has answers here:
If without else ternary operator
(10 answers)
Closed 6 years ago.
Is it possible to use a shorthand for ternary assignment expressions of the type
boolean x = false;
// ... code ...
a = x ? b : a; // Assigning a to a is pointless
a += x ? 1 : 0; // Adding 0 to a is pointless
I'm thinking something along the lines of
a = x ? b; // Assign b to a if x is true
a += x ? 1; // Add 1 to a if x is true
Not that it saves a lot of typing, I'm just curious if something like this exists. I just recently discovered the null coalesce operator in PHP 7, which does something kind of similar. To me it looks much cleaner than
if( x ) a = b;
if( x ) a += 1;
since these are assignments, and using a ternary expression looks more natural when reading from left to right. The supposed duplicate question isn't about assignments specifically, which in my opinion are a special use case of the ternary operator.
Unfortunately this is not supported by Java.
From the official oracle doc:
Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement (discussed in the Control Flow Statements section of this lesson).
This operator is also known as the ternary operator because it uses three operands.
In the following example, this operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."
The following program, ConditionalDemo2, tests the ?: operator:
class ConditionalDemo2 {
public static void main(String[] args){
int value1 = 1;
int value2 = 2;
int result;
boolean someCondition = true;
result = someCondition ? value1 : value2;
System.out.println(result);
}
}
Because someCondition is true, this program prints "1" to the screen.
Use the ?: operator instead of an if-then-else statement if it makes your code more readable;
for example, when the expressions are compact and without side-effects (such as assignments).
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
This question already has answers here:
ternary operator not working
(3 answers)
Closed 8 years ago.
Let's say we have following if statement:
int a = 1;
int b = 2;
if(a < b) {
System.out.println("A is less than B!");
}
else {
System.out.println("A is greater or equal to B!");
}
I have been wondering that if ternary operator replaces if statement when if statement consists from one line of code in each sub-block (if and else blocks), then why above example is not possible to write like this with ternary operator?
(a < b) ? System.out.println("A is less than B!") : System.out.println("A is greater or equal to B!");
You can only use ? : for expressions, not statements. Try
System.out.println(a < b ? "A is less than B!" : "A is greater or equal to B!");
Note: this is also shorter/simpler.
Because it doesn't replace an if statement.
The ternary operator only works on expressions and not statements, itself being an expression.
Because it is an expression, it is evaluated rather than executed, and it has to return a (non-void) value. The type of that value is inferred from the types of the two optional expressions specified, and the rules are fairly complex, with some unexpected gotchas.
(So as a rule I only use ?: in the simplest situations to keep the code easy to read.)
I'm came with two different types with same code which give same result.
First one is
public String gender(int num){
if (num==0){
return "Female";
} else{
return "Male";
}
}
Second one is
public String gender(int num){
return num == 0 ? "Female" : "Male" ;
}
Can you tell me what is the different with these two cord patterns? (Not of course code length.) One of my friend told me second code patten is called Unary code in java or something like that. I feel this way is very efficient. So I want to learn about that. Please help me.
Its called ternary operator
return num == 0 ? "Female" : "Male";
means same as
if (num==0){
return "Female";
}else{
return "Male";
}
It's ternary operator and equlas to if-else
result = someCondition ? value1 : value2;
So based up on the condition, the result variable gets a value.
That's short hand form of if else.
Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement. This operator is also known as the ternary operator because it uses three operands. In the following example, this operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."
The statement
return num == 0 ? "Female" : "Male" ;
_________ ^ ^
^ | |
| Return this |__ Return this if expression false
Expression if expression
true
It returns the result of the expression - (num == 0 ? "Female" : "Male")
It checks if num is equal to 0 or not. If yes the result is the first argument ie "Female" else the second argument ie "Male" if num is non zero.
Have a look at this Example in which it is casting the Integer to Double ,
There is no performance advantage in using the conditional operator versus using an if statement
Using ternary provides more better readability to the code. You are trading one line which concisely expresses what you want against nine lines of effectively clutter.
This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 9 years ago.
I came across this syntax:
System.out.println(boolean_variable ? "print true": "print false");
What is this syntax with two dots : called?
Where can I find info about it?
Does it work just for booleans or is it implemented in other different ways?
? : is the conditional operator. (It's not just the : part - the whole of the method argument is one usage of the conditional operator in your example.)
It's often called the ternary operator, but that's just an aspect of its nature - having three operands - rather than its name. If another ternary operator is ever introduced into Java, the term will become ambiguous. It's called the conditional operator because it has a condition (the first operand) which then determines which of the other two operands is evaluated.
The first operand is evaluated, and then either the second or the third operand is evaluated based on whether the first operand is true or false... and that ends up as the result of the operator.
So something like this:
int x = condition() ? result1() : result2();
is roughly equivalent to:
int x;
if (condition()) {
x = result1();
} else {
x = result2();
}
It's important that it doesn't evaluate the other operand. So for example, this is fine:
String text = getSomeStringReferenceWhichMightBeNull();
int usefulCharacters = text == null ? 0 : text.length();
It's the conditional operator, often called ternary operator because it has 3 operands: An example would be:
int foo = 10;
int bar = foo > 5 ? 1 : 2; // will be 1
int baz = foo > 15 ? 3 : 4; // will be 4
So, if the boolean expression evaluates to true, it will return the first value (before the colon), else the second value (after the colon).
You can read the specifics in the Java Language Specification, Chapter 15.25 Conditional Operator ?
It's a ternary operator, meaning that instead of having two operands like many other operators, it has three. Wikipedia on Ternary Operation and how it's used in Java. What it boils down to: the boolean operation (or just a variable) is evaluated. If it evaluates to true, the operator returns the value / executes the code before the :, otherwise the one after it.
That's an if statement.
What's to the left of ? is the condition, what's between the ? and : is the result if the condition is true, and what's to the right of : is the result if the condition is false.
This is ternary operator (http://en.wikipedia.org/wiki/?:). It can be used anywhere when you need a small if expression.
For your questions:
The ?: (both characters together) are called conditional operator (or ternary operator). Only both together will work.
Search for java ternery operator
It only works for boolean
In principle the ternery operator is a shortened if/else. The boolean will be the condition to the if, the part between ? and : is the if branch and the part after this is the else branch.
Please note that the return type of the conditional operator is determined by the first branch.
It's the ternary operator and it works with booleans. It can be used as a shorthand for if-else in some cases, but shouldn't be used for too complicated things as it can be difficult to read.
An example would be assigning value to a variable depending on a condition:
String message = doOperation() ? "Success" : "Error occurred";
System.out.println(message);
In this case, if doOperation returns a boolean telling whether it succeeded or not, the message to be shown can be assigned on a single line.
Please note that this example does not represent good programming practices.
Its ternary operator.
The ternary operator or ?, is a shorthand if else statement. It can be used to evaluate an expression and return one of two operands depending on the result of the expression.
boolean b = true;
String s = ( b == true ? "True" : "False" );
This will set the value of the String s according to the value of the boolean b. This could be written using an if else statement like this:
boolean b = true;
String s;
if(b == true){
s = "True";
}else{
s = "False";
}
Its a short form of if-else statement.
It works in this way
(yourCondition ? STATEMENT1 : STATEMENT2)
The compiler checks for the condition.
IF it returns TRUE then STATEMENT1 will be executed.
ELSE STATEMENT2 will be executed.
The question mark followed by a colon (two dots) is a ternary operator usually called inline if.
In this case it returns a string depending on the value of boolean_variable.
http://en.wikipedia.org/wiki/%3F:
See here. The ternary operator is similar to an if expression but differs in that it is an expression - it has a return value, while if expressions don't. Sometimes you want to use it to make your code a little less cluttered.