Zero comparison

This may seem like a real dumb question, but please bear with me :) so I have an if condition in my code like if ((msgBO.getEmpId().equals("") == false )) { // do something }My question is: if I do the above statement how msgBO.getEmpId().equals(null) == false will it have any meaning or so I try to compare two different things ?

+3
source share
7 answers

Yes, there is a big difference between ""(empty string) and null(no String at all).

Any object reference may point to null. This means “no data” or “nothing”. An empty string ""represents a string with no length.

An example of this is the following:

String one = null;
String two = "";
int oneLength = one.length();
int twoLength = two.length();

The first call lengthwill cause NullPointerException. And the second will return 0.

+7

. ,

msgBO.getEmpId.equals(null) == false

a.k.a.

!msgBO.getEmpId.equals(null)

( , equals ), null:

, x.equals(NULL) .

( )

, , , msgBO.getEmpId != null, equals. , msgBO.getEmpId != null, equals - NullPointerException, . :

msgBO.getEmpId != null && msgBO.getEmpId.equals("...stuff...")

"...stuff...".equals(msgBO.getEmpId)
+2

"" ( ) null . .equals(null) a String true.

0

A null String 0 - Java. :

  • getEmpId - -, , , , , ( ).
  • getEmpId / null, equals() NullPointerException - : if("foo".equals(variable))
  • , ==, . : if(!msgBO.getEmpId.equals("")) if(!msgBO.getEmpId != null)
0

,

msgBO.getEmpId == null

0

.

msgBO.getEmpId.equals("") msgBO.getEmpId String

msgBO.getEmpId.equals(null) msgBO.getEmpId null. , NullPointerException, msgBO.getEmpId - null. , null, : msgBO.getEmpId == null.

, , , msgBO.getEmpId. String, null . String, , , msgBO.getEmpId. , null , null, "" , "".

0

You are trying to compare two different things. It can still work, but one checks for an empty string and one checks to see if the variable is equal.

Also a faster check to see if the string is empty is just to check

if (string.length == 0).

(You will get an exception, however, if the string is null, so do not do this if null checks if you do not want to handle null case with catch excluded).

0
source

Source: https://habr.com/ru/post/1786448/


All Articles