开发者

condition in if statements

开发者 https://www.devze.com 2023-02-16 00:15 出处:网络
can if condition contain strings? for example string s=\"abs\"; if(s) or if(s==null) or if(s.equals(\"\"))

can if condition contain strings? for example

string s="abs";
if(s) or if(s==null) or if(s.equals(""))
开发者_JS百科

which among the above are correct? Also write for integers..

int value=5;

say

if(value) then condition

is it correct?


The condition in an if statement must be a boolean expression.

That means that it must be something that is of type boolean.

Both String and int are not boolean, so the following two do not work:

if (someString) {}
if (someInt) {}

Of course, you can have boolean expressions that contains String values in some way. The following will work:

if (someString == null) {}
if (someString.equals("")) {}

They both compile but act differently. The first one will check if someString has been set to null (i.e. it references no String object at all). The second one wil lcheck if someString references an empty String (one with a length of 0)).


I would suggest considering another option,

if("expected".equals(s))

The advantage of this approach is that when s == null this expression is false rather than throwing a NullPointerException.


In Java you cannot do if (s) if s is not boolean.


In java expect boolean, nothing is allowed in if condition check.

And even the assignment is not allowed in java unlike any other languages. But special case like

boolean b =false;
if(b=true)
    System.out.println("true");

works fine.

as b=true evaluates to the boolean value.

0

精彩评论

暂无评论...
验证码 换一张
取 消