简体   繁体   中英

How to avoid NullpointerException without null check in java

In below code I would like to skip null check. Please let me know the alternate solution.

 public class NullCheck {



    public static void main(String[] args) {

        String str=args[0];

        if (null != str) //without using this null check how to avoid null pointer exception

        {
            System.out.println("Null check");
        }
        else

        {
            System.out.println("Null value");
        }
    }
}

Thanks

You can avoid many null checks by using Yoda Expressions , for example

if ("Hello".equals(str))

"Hello" , as a literal, is never null and the built-in equals method will check str for null-ness. The alternative str.equals("Hello") would require you to check str first.

Some folk find them obfuscating, and it's not always possible to arrange your syntax accordingly.

I guess theres something like a homework to do? Eventually the teacher wants you to use a Try Catch Block?

try{
   //what you want to do when its not null
}
catch (NullPointerException exp){
   //what happens if its null
}

It try's to perform the code in the Try block, but if a NullPointerException occurs, you can handle it in the Catch block. Maybe, just maybe thats what you want.

I skipped a null check in your code. No value is checked for null, whatsoever.

public class NullCheck {

    static String str;

    public static void main(String[] args) {
    }
}

On more serious note, you could:

  • explain why you want to avoid null check,
  • initialize static String str to = ""; (an empty string) and it will not be null for sure (just make sure that noone can assign null to it)!.

Another alternate solution would to always initialize your variables to something. For stings, this could be an empty string: String string = ""; . For collections, this could be to initialize to empty collections: Collection<T> collection = Collections.emptyList(); or Collection<T> list = new ArrayList<>() if you want to add to it at a later stage.

The problem however, is that at some point, you will need to see if an object is null since not every object has some default, safe initialization value:

Scanner scanner = null;

try
{
    scanner = new Scanner(...);
    ...
}
...
finally
{
    if(scanner != null) scanner.close();
}

Thus, I do not think that you can completely avoid having to make null checks, but you can mitigate it.

我不知道您的检查有什么问题,这似乎是很好的解决方案,但是您可以使用try-catch语句,或者通过默认值“”初始化str对象并检查空字符串,或者使用断言来检查可为空的对象。

Short answer: you can't. Long answer: you can with workarounds, which effectively will be what checking if-else for null is.

Some already provided their answers, i'll give you a tip (not really an answer, since it actually does the opposite): Java 8 introduced generic class: Optional

It internally holds a reference to an object or null. What it gives you is that whenever you would try to invoke a method on the object it holds, to get to the actual object you need to call get() method, which will more likely remind you about checking for existence.

Just a small sample:

package whatever;
import java.util.Optional;

public class Main(){
    public static void main(String[] args) {
        Optional<String> a = Optional.empty();
        Optional<String> b = Optional.ofNullable(notReallyAString);
        Optional<String> c = Optional.of("John Paul II");
        if(a.isPresent()) System.out.println("Empty optional, you shouldnt be able to see this");
        if(b.isPresent()) System.out.println("Optional with a null, shouldnt be able to see this");
        if(c.isPresent()) System.out.println(c.get());  
    }
}

Note however, it is not supposed to be a general-purpose-any-value-volder, you'll more likely only want to use Optional only as a return type of a method to say to the client, that it might be indeed null.

Remember, that trying to get (by get() method) the null element inside the Optional instance will result the NoSuchElementException immediately (but it's still unchecked exception)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM