Java Conditional operator three possible results - java

How to break the conditional code you can see below into a regular if-statement to understand how it works, since it has three results.
I changed values just to see where its going:
System.out.print(("A"=="A")?("B"=="B")?"1":"2":"3");
/*
if A is False (Output = 3)
if B is False (Output = 2)
if A&B are True (Output = 1)
*/

The conditional (ternary) operator works in the following manner:
(predicate) ? (onTrueValue) : (onFalseValue);
so in your case what we have is :
("A"=="A" ? ("B"=="B" ? "1" : "2") : "3");
Which evals to:
Is A equal to A?
If yes -> return Is B equal to B
If yes -> return 1;
If no -> return 2;
If no -> return 3;
Similar to:
condition1 ? (condition2 ? val1 : val2) : val3;
And some tests for verification
// Prints 1 as both conditions are true.
System.out.println("A"=="A" ? ("B"=="B" ? "1" : "2") : "3");
// Prints 3 as first condition fails.
System.out.println("A"=="notA" ? ("B"=="B" ? "1" : "2") : "3");
// Prints 2 as second condition fails.
System.out.println("A"=="A" ? ("B"=="notB" ? "1" : "2") : "3");
Also note that your are uising the == operator for comparing strings. In this particular case this will give no difference just use it with caution...

Your code can be split like this:
String message;
if ("A" == "A") {
if ("B" == "B") {
message = "1";
} else {
message = "2";
}
} else {
message = "3";
}
System.out.print(message);
A ternary operator works like an if-statement that returns a value. However it can only be places where an expression could stand, so it cannot stand on it's own.
The part before the ? is the condition, the one after is the then expression. Behind the : is the else expression.
Nested ternary ?: operators are very bad to read, and should definetly be avoided.

If i understand you correctly and A, B, and C are booleans, this might be what you want:
System.out.print( ((!A)? "3" : (!B)? "2" : "1"));
For Strings you'd have to make sure to use A.equals(B).

Related

Why does this basic Java boolean expression not work?

Why does this not compute in Java (v1.8). Seems perfectly logical to me....
boolean banana = true;
(banana == true || false) ? System.out.println("True") : System.out.println("False");
Output message: Error: java: not a statement
The ternary conditional operator must return a value. The second and third operands can't be statements that don't return anything. They must be expressions that return a value.
You could switch it to :
System.out.println(banana ? "True" : "False");
Note that banana == true || false is equivalent to banana == true, which is equivalent to banana as banana itself is a boolean type.
The Java Language Specification ยง15.25 says:
It is a compile-time error for either the second or the third operand
expression to be an invocation of a void method.
Better try like this:
System.out.println(banana ? "true" : "false");
What you want is
boolean banana = true;
System.out.println(banana ? "True" : "False");
A ? : operator has to return a value and println is a void method. Not only does it do what you want, it is more concise.
Note
banana == true
is the same as
banana
and
x || false
is the same as
x
Also unless you need to print "True" instead of "true" you can do
System.out.println(banana);
How about this?
System.out.println(banana ? "true" : "false");
The ternary operator always has to return a value which we're printing.
The other way is only using if-else statement, but it's not pretty.
if(banana)
System.out.println("true");
else
System.out.println("false");
You are using it incorrectly.
One use of the Java ternary operator (also called the conditional operator) is to assign the minimum (or maximum) value of two variables to a third variable, essentially replacing a Math.min(a,b) or Math.max(a,b) method call. Here's an example that assigns the minimum of two variables, a and b, to a third variable named minVal is:
minVal = (a < b) ? a : b;
You can do it like this.
if(boolean)
System.out.println("True");
else
System.out.println("False");
I guess because Java won't allow statement like that.
Try using if statement.
boolean banana = true;
if (banana == true || false) System.out.println("True"); else System.out.println("False");
Because there are only false bananas: https://en.wikipedia.org/wiki/False_banana. There is not any one "true" banana. You are likely thinking of the "true plantain", see https://en.wikipedia.org/wiki/True_plantains. Changing your banana to false will allow your code to once again be copacetic with biology.

Java: Ternary operator, not working as should

I have some sample code and it looks like it uses a ternery operator but it takes 3 items. So I am really confused, the ones I have seen in other languages take only 2, i.e. true and false.
Here is the code
Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(R.xml.app_tracker)
: (trackerId == TrackerName.GLOBAL_TRACKER) ? analytics.newTracker(PROPERTY_ID)
: analytics.newTracker(R.xml.ecommerce_tracker);
what i wish to do is remove the line
: analytics.newTracker(R.xml.ecommerce_tracker);
So it would now be
Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(R.xml.app_tracker)
: (trackerId == TrackerName.GLOBAL_TRACKER) ? analytics.newTracker(PROPERTY_ID);
but it states it is missing a : (colon) in the IDE. So maybe this isn't a ternery operator after all ?
THe ide I am using is Android Studio.
I know it must be something simple, but i can't figure it out.
Any ideas ?
What you have there is nested ternary operators. Think of them as the following (pseudo-code below)
condition ? answerifTrue : secondternaryoperator;
where secondternaryoperator =
secondcondition ? answerifTrue : answerIfFalse;
Basically, this is two ternary operators combined. If the first condition is true it simply returns answerifTrue. But if the condition is false, it runs the second ternary operator to determine what to return based on a second condition. A singular ternary operator simply looks like this;
condition ? answerifTrue : answerIfFalse;
So if you want to create a single ternary operator from both you need to determine which answer you want if the first condition is false, for example;
Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(R.xml.app_tracker) : analytics.newTracker(PROPERTY_ID);
I imagine however, that what you need isn't well suited to ternary operators anyway and you might need to restructure the statement entirely into if else blocks or a switch statement.
Hm, as far as I understand that use case you have to do something like this:
Tracker t = null;
if (trackerId == TrackerName.APP_TRACKER) {
t = analytics.newTracker(R.xml.app_tracker);
} else if (trackerId == TrackerName.GLOBAL_TRACKER) {
t = analytics.newTracker(PROPERTY_ID);
} else {
t = analytics.newTracker(R.xml.ecommerce_tracker);
}

Conditions in Ternary Operator - Java

I have a simple if/elseif condition which I'm trying to convert it into a return statement with Ternay Operator for code redundancy but I have not been able to.
Any help would be appreciated, Thanks.
Here's my code snippet :
if (val.equals("a")||val.equals("s")){
return true;
}
else if (val.equals("b")||val.equals("t")) {
return false;
}
return true;
Could someone please suggest on how to proceed with return statement(Ternary Operator) for the above if/else-if ?
There's no need for a conditional operator here. Your code will return true so long as val is neither b nor t:
return !(val.equals("b") || val.equals("t"));
or:
return !val.equals("b") && !val.equals("t");
The first condition around a and s is completely irrelevant, as the "default" return true at the bottom already includes those cases.
EDIT: Now that you've changed the return type to int, this would be reasonable to use with the conditional operator:
return val.equals("b") || val.equals("t") ? 0 : 1;
return !(val.equals("b") || val.equals("t"))
The rest is redundant, val cannot equal "a" or "s" and equal "b" or "t" at the same time, so you basically need to check if it equals "b" or "t", and return false in this case, and true in any other case.
return !(val.equals("b") || val.equals("t"));
This is the only condition that returns false - so you don't need to check the first condition.
return !(val.equals("b") || val.equals("t"))
Try the follwing:
boolean b = ( val.equals("b") || val.equals("t") ) ? false : true;
return b;

Ternary operator to return value- Java/Android

Just switched to Java from php
I encountered following issue
I want to rewrite
if(usrname.equals(username) && (passwd.equals(password))){
return true;
}
else{
return false;
}
as
(usrname.equals(username) && passwd.equals(password) )? return true : return false;
it is not working(syntax error)
however,
int a=1;
int b=2;
int minVal = a < b ? a : b;
is working
Why ternary operator are not behaving correctly while returning value depending on some condition
EDIT
return (usrname.equals(username) && passwd.equals(password));
could be solution if it return boolean .
lets say i need
(usrname.equals(username) && passwd.equals(password) )? return "member": return "guest";
You can do
return (usrname.equals(username) && passwd.equals(password) )? true : false;
true and false can be replaced by any return value you want. If it is just boolean then you can avoid ternary operator altogether. Just do
return (usrname.equals(username) && passwd.equals(password));
lets say I need
(usrname.equals(u) && passwd.equals(p)) ? return "member" : return guest";
The correct syntax is:
return (usrname.equals(u) && passwd.equals(p)) ? "member" : "guest";
The general form of the ternary operator is
expression-1 ? expression-2 : expression-3
where expression-1 has type boolean, and expression-2 and expression-3 have the same type1.
In your code, you were using return statements where expressions are required. In Java, a return statement is NOT a valid expression.
1 - This doesn't take account of the conversions that can take. For the full story, refer to the JLS.
Having said that, the best way to write your example doesn't uses the conditional operator at all:
return usrname.equals(username) && passwd.equals(password);
Why redundant boolean
Just use
return (usrname.equals(username) && passwd.equals(password));
By the way you can simplify:
return (usrname.equals(username) && passwd.equals(password) )? return true : return false;
To:
return usrname.equals(username) && passwd.equals(password);
The ternary operator work similar in php than Java, I think you have made a silly mistake, maybe "username" have a space or another white character
String a1 = "a";
String b1 = "b";
String a2 = "a";
String b2 = "b";
System.out.println((a1.equals(a2)&&b1.equals(b2))?"true":"false");
it return "true"
Java ternary operator is an expression, and is thus evaluated to a single value.
As per the Javadocs, for below given expression
result = someCondition ? value1 : value2;
if the boolean condition is true then assign the value of value1 to the result, else assign value2 to the result. Both value1 and value2 should be of same value type.
Hence the correct syntax of a return statement would be
return boolean_condition ? value_when_true : value_when_false

What is a Question Mark "?" and Colon ":" Operator Used for? [duplicate]

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"

Categories