String name; if (name.equals("") {} How to avoid null pointer error NullPointerException?

Here is the application scenario :

record.getName() Return to a String Variable of type name

this name It could be null

I found that a programmer wrote such a piece of code

It's easy to write in this way NullPointerException   This is a serious mistake , When name=null When , In the following sentence
name.equals("") When executed , It will run abnormally ( because null It's impossible for an object to have equal Method can be called ),

Not at all name == null Judgment of . Cause program crash

public class ContactsService {String name = record.getName(); //
if name Empty string itself , Pass value nameEn if (name.equals("") || name == null) {
dto.setName(record.getNameEn()); } else {dto.setName(record.getName());}
Change to the following , No exceptions

String name = record.getName(); // if name Empty string itself , Pass value nameEn if (name == null ||
name.equals("")) { dto.setName(record.getNameEn()); } else {
however , There's another problem , If name It's a space string ? need trim() operation

Here is Frank Elegant code for . Under no circumstances NullPointerException!

public class ContactsService { // if name Empty string itself , Pass value nameEn String name =
record.getName(); name = name == null ? "" : name.trim(); if (name.equals(""))
{ dto.setName(record.getNameEn()); } else { dto.setName(record.getName());}

©2019-2020 Toolsou All rights reserved,
html Writing about cherry trees , Writing about cherry trees It's unexpected Python Cherry tree (turtle The gorgeous style of Library ) Browser kernel ( understand )HashMap Explain in detail java Four functional interfaces ( a key , simple )os Simple use of module Some East 14 Pay change 16 salary , Sincerity or routine ?