Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If-statement - Check String against variable or variable against String? [duplicate]

Possible Duplicates:
Gracefully avoiding NullPointerException in Java
Multilingual fields in DB tables

Exact duplicate

Gracefully avoiding NullPointerException in Java

What do you like more? I just hate seeing the last one. It just seems backwards.

String randomtext = "stack overflow";

if(randomtext.equals("stack overflow"))
{
      //do something
}

or

String randomtext = "stack overflow";

if("stack overflow".equals(randomtext))
{
     //do something
}
like image 575
Tommy Avatar asked Apr 27 '26 11:04

Tommy


1 Answers

Contrary to what some people think, these two are not functionally equivalent. The first one will throw a NullPointerException if the randomtext is null while the second one won't. This is why I'd choose the latter.

like image 86
mmx Avatar answered Apr 29 '26 00:04

mmx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!