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
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 ?
“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.
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.
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.
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));
Use equals
instead of ==
boolean checked = (categoriesCursor.getString(3).equals("1"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With