o9s
is a microblog
home archives search feed blogroll


Safer String Comparisons

Most programmers will use code like this to compare strings in Java.

if (name.equals("Stephen")) {
  [...]
}

However, even if it feels more unnatural, you should write code like this instead.

if ("Stephen".equals(name)) {
  [...]
}

The reason is that it prevents possible null pointer exceptions. "Stephen" will never be null. name might be.

Posted on 2018-04-09   #java  






← Next post    ยท    Previous post →