Java lang string equals null

Java string null check by != null or !str.equals(null)? [duplicate]

@RohitJain are there any types of String which aren’t objects? There is no primitive equivalent as far as I know.

4 Answers 4

1st one is better (and the only option), because 2nd one will throw NPE , when your value is actually null . As simple as that.

String str = null; str.equals(null); // will throw `NPE`. 

So basically, the test which you wanted to perform itself triggers a NullPointerException in the 2nd case. So, it is no choice.

@Cratylus. Why would he test for non-null if there is no possibility of null value at all? And if there is a possibility of null value, then there is NPE in 2nd case.

  1. always return false if it does not throw an exception, and
  2. throw an exception if str is null

The point of a null check is to make sure the reference, in this code str , actually refers to an object. If it is null, you can’t call any methods on it, including equals , without throwing a NullPointerException . which the point of null checks is to avoid happening.

So !str.equals(null) causes the very problem null checks are meant to prevent and doesn’t do what you think at all. Never do this.

+1, i made the same point about str.equals(null) would always return false, but my answer not clear about the concrete question.. 🙂

query != null better as !query.equals(null) will throw an exception when query is actually null. Also query != null is easily readable

query != null compares if the object is null . query.equals(«something») compares the value inside of that object. string = . so in this case use query != null .

Linked

Hot Network Questions

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Why do I get a NullPointerException when comparing a String with null?

Previous to this statement, I declare the stringVariable and set it to a database field. In this statement, I am trying to detect if the field had a null value, but unfortunately it breaks! Any thoughts?

Читайте также:  All about session in php

You’re calling a method on a variable containing null. equals() isn’t special, it will still throw a NPE.

4 Answers 4

To test whether stringVariable is null .

The equals method (and every other method) requires stringVariable to not be null .

if stringvariable is already null, it doesn’t exist as a String object anymore, so it won’t even have a .equals method! So in the event when stringvariable is null, what you are really doing is null.equals(null) , at which point you’ll get the NullPointerException because null doesn’t have a .equals() method.

While the approved comment does, in fact, help to answer the «spirit» of the OP question,(they just ask for «any thoughts») I believe this answer expands a bit more on the «why» to help future readers.

It is never wise to call a method, be it equals() or otherwise,on a variable which may be null. That is why one usually does something like:

if ( var != null && var.method(something) ) < // var.method() was true >else < // var is null or var.method is false >

In your special case it would be sufficient to do

when working with Strings it can pay to check out Apache Commons StringUtils.

It always pays to check out the apache commons libraries as they have lots of optimized utilities (for Strings, Collections, Dates and such) which tend to be better than home-written ones.

Источник

Compare two objects in Java with possible null values

I want to compare two strings for equality when either or both can be null . So, I can’t simply call .equals() as it can contain null values. The code I have tried so far :

boolean compare(String str1, String str2)

Note that it is a bit confusing that you call the method compare , it has a different meaning for strings. You should call it equals .

12 Answers 12

Since Java 7 you can use the static method java.util.Objects.equals(Object, Object) to perform equals checks on two objects without caring about them being null .

If both objects are null it will return true , if one is null and another isn’t it will return false . Otherwise it will return the result of calling equals on the first object with the second as argument.

this approach defers the type check until the runtime of the program. two consequences: it will be slower at runtime and IDE won’t let you know if you by accident try to compare different types.

Читайте также:  Opencart 3 twig php

@averasko When you use Object.equals(Object) there is no compile time type check. The Objects.equals(Object, Object) works very much the same as a normal equals , and re inference/checks by IDE, those rules are heuristics that are also supported for Objects.equals(Object, Object) (eg IntelliJ IDEA 2016.2 has the same check for both the normal equals and the one from Objects).

@SimonBaars This isn’t running a function on a null object, this is a static method that you pass two arguments, which can be null, or a reference to an object.

imho this should be the accepted answer. I don’t want to reinvent the wheel in every single application I write

This is what Java internal code uses (on other compare methods):

public static boolean compare(String str1, String str2)

Why not just change the String types to Objects — making it more generic? And then it is the same as what you will get if you move to Java 7.

Hey! you shouldn’t have a compare method returning true/false. Equals is not the same as compare. Compare should be useful for sorting. You should return <0 , ==0 or>0 to indicate which one is lower/grater than the other

i suggest using Objects.equals(Object, Object) as Mark Rotteveel has pointed out in his answer (please upvote it)

@Eric that doesn’t really make it less of a good answer. I am sure you wouldn’t argue the best answer is always the one containing only code which is compatible with every java version that has always existed

For these cases it would be better to use Apache Commons StringUtils#equals, it already handles null strings. Code sample:

public boolean compare(String s1, String s2)

If you dont want to add the library, just copy the source code of the StringUtils#equals method and apply it when you need it.

For those on android, who can’t use API 19’s Objects.equals(str1, str2), there is this:

android.text.TextUtils.equals(str1, str2); 
/** * Returns true if a and b are equal, including if they are both null. * 

Note: In platform versions 1.1 and earlier, this method only worked well if * both the arguments were instances of String.

* @param a first CharSequence to check * @param b second CharSequence to check * @return true if a and b are equal */ public static boolean equals(CharSequence a, CharSequence b) < if (a == b) return true; int length; if (a != null && b != null && (length = a.length()) == b.length()) < if (a instanceof String && b instanceof String) < return a.equals(b); >else < for (int i = 0; i < length; i++) < if (a.charAt(i) != b.charAt(i)) return false; >return true; > > return false; >

Using Java 8:

private static Comparator nullSafeStringComparator = Comparator .nullsFirst(String::compareToIgnoreCase); private static Comparator metadataComparator = Comparator .comparing(Metadata::getName, nullSafeStringComparator) .thenComparing(Metadata::getValue, nullSafeStringComparator); public int compareTo(Metadata that)

Or you can also use the below method using Java

Читайте также:  Событие вызова функции python

public static boolean compare(String first, String second)

Since version 3.5 Apache Commons StringUtils has the following methods:

static int compare(String str1, String str2) static int compare(String str1, String str2, boolean nullIsLess) static int compareIgnoreCase(String str1, String str2) static int compareIgnoreCase(String str1, String str2, boolean nullIsLess) 

These provide null safe String comparison.

Compare two string using equals(-,-) and equalsIgnoreCase(-,-) method of Apache Commons StringUtils class.

StringUtils.equals(-, -) :

StringUtils.equals(null, null) = true StringUtils.equals(null, "abc") = false StringUtils.equals("abc", null) = false StringUtils.equals("abc", "abc") = true StringUtils.equals("abc", "ABC") = false 

StringUtils.equalsIgnoreCase(-, -) :

StringUtils.equalsIgnoreCase(null, null) = true StringUtils.equalsIgnoreCase(null, "abc") = false StringUtils.equalsIgnoreCase("xyz", null) = false StringUtils.equalsIgnoreCase("xyz", "xyz") = true StringUtils.equalsIgnoreCase("xyz", "XYZ") = true 

You can use java.util.Objects as following.

public static boolean compare(String str1, String str2)
boolean compare(String str1, String str2) < if(str1==null || str2==null) < //return false; if you assume null not equal to null return str1==str2; >return str1.equals(str2); > 
boolean compare(String str1, String str2)
boolean compare(String str1, String str2)

OK, so what does «best possible solution» mean?

If you mean most readable, then all the possible solutions are pretty much equivalent for an experienced Java programmer. But IMO the most readable is this

 public boolean compareStringsOrNulls(String str1, String str2) < // Implement it how you like >

In other words, hide the implementation inside a simple method that (ideally) can be inlined.

(You could also «out-source» to a 3rd party utility library . if you already use it in your codebase.)

If you mean most performant, then:

  1. the most performant solution depends on the platform and the context,
  2. one of the «context» issues is the relative (dynamic) frequency of occurrence of null arguments,
  3. it probably doesn’t matter which version is faster . because the difference is probably too small to make a difference to the overall application performance, and
  4. if it does matter, the only way to figure out which is fastest ON YOUR PLATFORM is to try both versions and measure the difference.

Источник

Оцените статью