pablo
pablo

Reputation: 31

Using Value of 1 for boolean in Java

I'm following this tutorial for creating reminder in android. In the source code that it provides it used the value of "1" for a boolean method.

Here is the code snippet I'm talking about:

public static boolean showRemainingTime(){
    return "1".equals(sp.getString(TIME_OPTION, "0"));
}

Why "1" is used in this example given that in java the value of boolean is either true or false?

Sorry for my lame question!

Upvotes: 1

Views: 121

Answers (2)

Kevin Krumwiede
Kevin Krumwiede

Reputation: 10288

String literals are full-fledged String objects. This may make more sense to you:

String str = "1";
return str.equals(sp.getString(TIME_OPTION, "0"));

It might also make more sense if it were written this way:

return sp.getString(TIME_OPTION, "0").equals("1");

The problem with this version is that if getString(...) returned null, calling equals(...) would throw a NullPointerException. That may not be possible in this particular case, but calling methods on string literals is a good habit to get into.

Upvotes: 3

Eran
Eran

Reputation: 393781

The showRemainingTime method is not returning the String "1". It returns true if the String returned by sp.getString(TIME_OPTION, "0") is equal to the String "1", and false otherwise.

Upvotes: 4

Related Questions