java - why the logical operators change the object -


why when use below code eclipse highlights (!line.equals("")) red , says: null pointer access: variable line can null @ location

but not receive warning message if used : && instead of ||?

code:

string line = br.readline();         if ( (line != null) || (!line.equals("")) ) {         } else {             log.d(tag, "main", "file empty");         } 

this classic "short circuit".

for && case:

if ((line != null) && (!line.equals("")) { 

if line equal null, there no reason compiler process second part of if statement. whole if statement must false. short circuits second part of if statement, , don't null reference exception.

when switch && ||, compiler have process second part of if statement, because if either part true whole thing true. therefore, can null reference exception.

note: if can use stringutils of apache commons-lang both checks in one:

if (stringutils.isnotblank(str)) 

update: || case, if first part true, whole if statement must true, again there no reason process second part of if statement.


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -