Ternary operator to return value- Java/Android
You can do
return (usrname.equals(username) && passwd.equals(password) )? true : false;
true
and false
can be replaced by any return value you want. If it is just boolean then you can avoid ternary operator altogether. Just do
return (usrname.equals(username) && passwd.equals(password));
lets say I need
(usrname.equals(u) && passwd.equals(p)) ? return "member" : return guest";
The correct syntax is:
return (usrname.equals(u) && passwd.equals(p)) ? "member" : "guest";
The general form of the ternary operator is
expression-1 ? expression-2 : expression-3
where expression-1
has type boolean
, and expression-2
and expression-3
have the same type1.
In your code, you were using return
statements where expressions are required. In Java, a return
statement is NOT a valid expression.
1 - This doesn't take account of the conversions that can take. For the full story, refer to the JLS.
Having said that, the best way to write your example doesn't uses the conditional operator at all:
return usrname.equals(username) && passwd.equals(password);