Single expression in ternary operator in Java - java

I know you can have
String answer = (5 == 5) ? "yes" : "no";
Is it somehow possible to have only:
String answer = (5 == 5) ? "yes";
It gives a compile error when I try.
NOTE: (5==5) is just an example. In its place will be statement which could be either true or false.

if one line is important
String answer = (5 == 5) ? "yes": null;
Since a String's default value is null.

You're looking for an if statement:
if (5 == 5)
answer = "yes";
Your idea is impossible because an expression (such as the conditional value) must always have a value.
In your code, if 5 != 5, the expression would have no value, which wouldn't make any sense.

No. you can't have it. You need to specify both the ? and :.
Use a straight if.

Related

refactoring if else to Single line conditional statement in Java?

I want to write single line if else check. But i am getting error.
Please help
if(x == 1) {
System.out.println("aaa");
}else {
System.out.println("bbb");
}
Is there a way to make above code as single like below. Getting compile error in below line
x == 1 ? System.out.println("aaa") : System.out.println("bbb");
Please help. I might be making a silly error i guess.
The second and third arguments of the conditional ternary expression must be expressions, so they can't be System.out.println("aaa").
Instead, so you can write:
System.out.println (x == 1 ? "aaa" : "bbb");
Now you have a ternary conditional expression that produces a value (either "aaa" or "bbb"), and that value is passed to System.out.println.
The ternary operator can only be used with expression returning a value. In your case, System.out.println("aaa") is not expression and can't be used.
You can use:
System.out.println(x == 1 ? "aaa" : "bbb");

What is this if-statement called? [duplicate]

This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 8 years ago.
So i was just wondering if there was actually a name for this if-statement:
public void checkEvenNumber(number) {
return ((number % 2 == 0) ? true : false)
}
Or if it is just called an if-statement.
Yes. That's an example of a ternary operator.
JLS-15.25 Conditional Operator ? : describes it as,
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
It is called a terniary operator. However in this case, terniary operator isn't needed as the function it can be simplified to look like this:
public boolean isEvenNumber(int number) {
return number % 2 == 0;
}
Please note that I changed the name of the function to match what it actually does.
The ternary operator, so-called as it has 3 components:
The condition
The expression returned if it's true
The expression returned if it's false
that's a function (as i recognize it), you pass parameter(s) to it and it is passes it/them down to the function (where you do your stuff) and it returns only 1 variable.
You may also refer it as inline if statement
Here's a link for your reading up: http://en.wikipedia.org/wiki/%3F:
If you are familiar with how if-statements work in MS Excel, it shouldn't be too hard to understand.
By the way, your code should change to:
public void checkOddNumber(number) {
return ((number % 2 != 0) ? true: false)
}

What does the "?" key do in Java? [duplicate]

This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 8 years ago.
I've been trying to Google it, but googling the key "?" doesn't really work out that good.
I really want to know what it does and when to use it.
Thanks!
I've seen it a couple times, but here is an example of one I just saw
String name = perms.calculateRank().getColor() + player.getName();
//This is a custom ranking system ^
player.setPlayerListName(name.length() > 15 ? name.substring(0, 16) : name);
player.setDisplayName(name + ChatColor.RESET);
Chat.sendMessage(player, "Tab Name Set");
This is a ternary operator. In Java specifically, it is called the Conditional Operator. It is a way of writing short-hand simple if..else statements. For example:
if (a == b) {
c = 123;
} else {
c = 456;
}
is the same as:
c = a == b ? 123 : 456;
It is also used for a wildcard generic.
public List<?> getBizarreList();
The ternary operator someBoolean ? x : y evaluates to x if someBoolean is true, and y otherwise.
It is called ternary operator and it is only operator that takes 3 operands. In better sense, it is conditional operator that represent shorter format
General Syntax :
boolean expression ? value1 : value2
your example:
player.setPlayerListName(name.length() > 15 ? name.substring(0, 16) : name);
as same as
if( name.length() > 15)
player.setPlayerListName(name.substring(0, 16));
else
player.setPlayerListName(name);

Java: boolean in println (boolean ? "print true":"print false") [duplicate]

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.

What does "?" mean in Java? [duplicate]

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.

Categories