String.equals and Nullpointerexception method

Asked

Viewed 531 times

3

Although the doubt is very basic, I would like to understand why the equals in this case:

    String texto = null;

    System.out.println("teste".equals(texto));

Returns false normally (example in ideone), but in the example below:

    String texto = null;

    System.out.println(texto.equals(""));

He bursts the exception NullPointerException, as can also be seen in ideone.

In both cases there is a comparison with null, but the return is different depending on the side on which the null is past, why this occurs?

  • https://en.wikipedia.org/wiki/Yoda_conditions

3 answers

4


It turns out that the NullPointerException will only burst when you try to access some element (understand by element a method or attribute) of an object that is null.

See, in your example

String texto = null;
System.out.println("teste".equals(texto));

Here you are accessing/calling the method equals of string literal test (which is not a null object, of course - "teste" is an object of the type String) and is passing null per parameter, so you are not trying to access any element of a null object.

String texto = null;
System.out.println(texto.equals(""));

Already here, you are accessing/calling the method equals of the variable texto (which is a null object).

4

The difference is that in the first case you are creating an object of type String, whose value is equal to teste. Soon after you call the method equals() of that object. As an argument, you are passing null instead of an object.

In the second case there is no object, that is, the variable texto does not reference any object, so when you try to access the method equals() the variable texto returns null and throws a Nullpointerexception exception.

3

When you do that System.out.println("teste".equals(texto)); you are calling the equals method in a literal string and comparing it to null and what is naturally false.

When you this System.out.println(texto.equals("")); you are calling the equals method from an object null, which is not valid, thus raising the famous NullPointerException.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.