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
7 Answers 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.
1 Comment
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.
Comments
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 strto= "";(an empty string) and it will not benullfor sure (just make sure that noone can assign null to it)!.
1 Comment
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)
Comments
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.
Comments
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.
Comments
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.
strto an empty string, i.e.static String str = "";Then you only have to check whether it's empty ;)