Java: Ternary operator, not working as should - java

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);
}

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");

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.

Conditional operator for odd or even

I'm trying to write a program that that will find if there's an equal number of odds and even numbers in a given one, it's working great but it want to use conditional operator instead of these 4 rows (the // rows),
I'm getting this:
Syntax error on token "%", invalid AssignmentOperator
Can someone tell me why? What's wrong?
while(number!=0) {
//if(number%2==0)
//even++;
//else
//odd++;
number%2==0 ? even++ : odd++;
number/=10;
}
number%2==0 ? even++ : odd++;
This is not a statement. The result of a ternary must be assigned to something:
int x = number % 2 == 0 ? even++ : odd++;
However, this is stylistically quite awkward. I would use an if-else (i.e., what you originally had) over this pattern. Here you've created a temporary variable that you're never going to reuse, for the sole purpose of using a ternary.
It requires a variable at the left side at where you can place the value after the condition.
int tmp = (number%2 == 0)?even++:odd++;
number%2==0 ? even++ : odd++;
This statement is not assigning any value to number.As per my knowledge its always recommended for use if-else instead of ternary operator.
Because, in ternary operator the false/else part is compulsory to write, where in if-else else/false part is optional.
while(number!=0) {
//if(number%2==0)
//even++;
//else
//odd++;
int temp= number%2==0 ? even++ : odd++;
number/=10;
}
Now, temp variable is holding the value .

What does "?" and ":" do in boolean statements? [duplicate]

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

OR and AND functions in java?

What are the OR and AND operators in Java? I've tried or, system.or, and all sorts of stuff, but haven't found anything.
Well let me break it up for you..........
Short Circuit And & Or operator:
AND Gate : &&
OR Gate : ||
Non-Short Circuit And & Or operator:
AND Gate : &
OR Gate : |
Difference between Short and Non-Short Circuit Operator:
if (false && true) // As the 1st statement is false it won't evaluate the 2nd condition
if (false & true) //Even though the 1st statement is false, it will still evaluate the 2nd condition
Um, what do you mean by "logic gates"? Do you mean || and &&?
|| is what you use for OR.
&& is what you use for AND.
Check Summary of Operators # Oracle
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html
and is && and or is ||
See: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Are you looking for || which is OR and && which is AND operators?
Or -> ||
And -> &&
As an example
if a == 1 and b == 2 -> if (a == 1 && b == 2)
there have to import logicgate.*
is should able to let the program use AND , OR , and NOT gate (not sure for others)
example :
create variable using AND class and 2 extra variable for process
And and = new And();
int no1 = 10 , no2 = 20;
next, do the process using AND gate logic
int answer = and.doOperation(no1,no2);
same workflow using others logic gates

Categories