Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Ternary Operator to set True or false

I am trying to set a condition and set true or false as follows but it returns false all the time.

boolean checked = (categoriesCursor.getString(3) == "1") ? true
                    : false;

Log.i("Nomad",categoriesCursor.getString(3)+ " "+checked);

When i try to output the values i get the following.

01-12 00:05:38.072: I/Nomad(23625): 1 false
01-12 00:05:38.072: I/Nomad(23625): 1 false
01-12 00:05:38.072: I/Nomad(23625): 1 false
01-12 00:05:38.072: I/Nomad(23625): 1 false
01-12 00:05:38.072: I/Nomad(23625): 1 false
01-12 00:05:38.072: I/Nomad(23625): 0 false
01-12 00:05:38.072: I/Nomad(23625): 0 false
like image 793
Harsha M V Avatar asked Jan 11 '13 18:01

Harsha M V


People also ask

How can a ternary operator return true or false in Java?

The first operand in java ternary operator should be a boolean or a statement with boolean result. If the first operand is true then java ternary operator returns second operand else it returns third operand. Syntax of java ternary operator is: result = testStatement ?

Can a ternary operator return True False?

“Question mark” or “conditional” operator in JavaScript is a ternary operator that has three operands. The expression consists of three operands: the condition, value if true and value if false. The evaluation of the condition should result in either true/false or a boolean value.

Which statement about ternary operator is true?

Ternary Operator in Java A ternary operator evaluates the test condition and executes a block of code based on the result of the condition. if condition is true , expression1 is executed. And, if condition is false , expression2 is executed.

Can we use ternary operator in if condition in Java?

Java ternary operator is the only conditional operator that takes three operands. It's a one-liner replacement for the if-then-else statement and is used a lot in Java programming. We can use the ternary operator in place of if-else conditions or even switch conditions using nested ternary operators.


2 Answers

It returns false all the time because you are comparing references, not strings. You probably meant this instead:

boolean checked = (categoriesCursor.getString(3).equals("1")) ? true
                : false;

Which happens to be equivalent to this:

boolean checked = categoriesCursor.getString(3).equals("1");

And in case categoriesCursor.getString(3) may be null, you will be safer doing this instead:

boolean checked = "1".equals(categoriesCursor.getString(3));
like image 198
K-ballo Avatar answered Sep 20 '22 17:09

K-ballo


Use equals instead of ==

boolean checked = (categoriesCursor.getString(3).equals("1"));
like image 34
Ilya Avatar answered Sep 20 '22 17:09

Ilya