Method String.equals and NullPointerException

3

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

    String texto = null;

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

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

    String texto = null;

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

It pops up the NullPointerException exception, as can also be seen in the ideone .

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

asked by anonymous 22.03.2016 / 15:57

3 answers

4

It happens that NullPointerException will only pop when you attempt to access some element (by element, understand 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 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 equals method of the texto variable (which is a null object).

    
22.03.2016 / 16:01
4

The difference is that in the first case you are creating an object of type String , whose value is equal to teste . Then you call the equals() method of this 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 equals() method, the texto variable returns null and throws a NullPointerException exception. >     

22.03.2016 / 16:02
3

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

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

    
22.03.2016 / 16:01