0

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

asked Aug 4, 2015 at 12:10
2
  • 2
    what's wrong with a good ol' null check? Commented Aug 4, 2015 at 12:13
  • 1
    Initialize str to an empty string, i.e. static String str = ""; Then you only have to check whether it's empty ;) Commented Aug 4, 2015 at 12:13

7 Answers 7

7

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.

answered Aug 4, 2015 at 12:16
Sign up to request clarification or add additional context in comments.

1 Comment

I like this solution! Most often I code like this if I have a chance.
3

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.

answered Aug 4, 2015 at 12:19

Comments

2

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)!.
answered Aug 4, 2015 at 12:14

1 Comment

I want an alternate ways of null check.
1

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)

answered Aug 4, 2015 at 13:34

Comments

1

In Java if you want to avoid explicit null checks and still handle null values gracefully, you can use the Optional class, which was introduced in Java 8.

Here's an example of how you can modify your code using Optional:


import java.util.Optional;
public class NullCheck {
 public static void main(String[] args) {
 String str = args[0];
 Optional.ofNullable(str)
 .ifPresentOrElse(
 s -> System.out.println("Null check"),
 () -> System.out.println("Null value")
 );
 }
}

In this example, Optional.ofNullable(str) creates an Optional instance that wraps the potentially null value. The ifPresentOrElse method takes two parameters - the first is a consumer to be executed if the value is present, and the second is a Runnable to be executed if the value is absent.

This way, you can handle null values without explicitly writing a null check. Keep in mind that while this approach avoids explicit null checks, it's still internally checking for null within the Optional class.

Sabeeh
1,29716 silver badges18 bronze badges
answered Jan 2, 2024 at 15:47

Comments

0

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.

answered Aug 4, 2015 at 12:17

Comments

0

I don't know what is the problem with your check, It seems good solution, but you can use try-catch statement, or initialize str object by default value "" and check empty string, or using assertion to check the nullable object.

answered Aug 4, 2015 at 12:20

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.