Java Ternary Operator to set True or false
Solution 1
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));
Solution 2
Try using this
(categoriesCursor.getString(3).equals("1")) ? true : false;
Solution 3
Use equals
instead of ==
boolean checked = (categoriesCursor.getString(3).equals("1"));
Solution 4
First there's no need for ternary operator. Then you must use equals()
instead of ==
. Because ==
operator checks whether the references to the objects are equal.
Solution 5
Firstly, to compare strings, you'll have to use the equals
method:
categoriesCursor.getString(3).equals("1")
Secondly, you don't need the ternary operator here. equals
already results in a boolean, so simply assign it:
boolean checked = categoriesCursor.getString(3).equals("1");
Harsha M V
I turn ideas into companies. Specifically, I like to solve big problems that can positively impact millions of people through software. I am currently focusing all of my time on my company, Skreem, where we are disrupting the ways marketers can leverage micro-influencers to tell the Brand’s stories to their audience. People do not buy goods and services. They buy relations, stories, and magic. Introducing technology with the power of human voice to maximize your brand communication. Follow me on Twitter: @harshamv You can contact me at -- harsha [at] skreem [dot] io
Updated on January 12, 2020Comments
-
Harsha M V over 4 years
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
-
Harsha M V over 11 yearswhat does the last statement do ?
-
K-ballo over 11 years@HarshaMV: It checks whether
"1"
is equal to the string you got from the cursor. -
fge over 11 years@HarshaMV: Java has string constants, and they behave as String objects; all methods available to the
String
class are also available toString
constants.