0

I was messing around with some code and ran into a null pointer exception that was the result of an un-initialized variable. So I was just wondering: is there a way to verify that an object actually exists before attempting to handle it, thereby avoiding such an error?

Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
Ryan H.
  • 43
  • 2
  • 9
  • 2
    You can test if an object has been assigned a value by using `if (null == object)` or `if (null != object)` or combinations of – MadProgrammer Jul 02 '18 at 22:26
  • I think you're misusing your terms. `null` does not mean uninitialized. It just means `null`. You are allowed to initialize a variable to null. (`Object a = null;`) An uninitialized variable cannot actually be used (`Object a; if (a == null) // compile error`). – killjoy Jul 02 '18 at 23:57

4 Answers4

5

There are three scenarios:

  1. If the variable is a method parameter or a catch variable, it is guaranteed to be initialized because that is taken care of by Java semantics

  2. If the variable is a local variable, it is guaranteed to be initialized because the compiler won't let you access a local variable that is not definitely assigned.

  3. If the variable is a class (static) or instance variable, then it will either be explicitly initialized in the declaration, or default initialized1.

In the 3rd case, the default initial value is null for a reference type, zero for a numeric type or false for boolean. It is always possible to test if a variable has that (known) value before using it.

HOWEVER, you don't know if it has that value because it was not initialized, or if that value was explicitly assigned. For example:

  if (object != null) {
    // Object has been initialized
  } else {
    // ...
  }

In the else case, we do not know for sure that the variable has been initialized. It could have been explicitly initialized to null. It could have been initialized to something else, and then had null assigned to it.

However you probably just want to know if the variable is null or not. You can determine that using an == null test, as above ... or in other ways; e.g. using the ternary operator or Objects.nonNull (Java 8 and later).


1 - There are some edge cases for class variables, where a variable declared with an initializer may still be observed in the default initialized state.


The suggestion to catch and recover from NPEs is a bad idea for a number of reasons. One reason is that it is hard to be sure what caused any given NPE. (as it the specific variable you are concerned with ... or something else? For example:

   SomeClass sc = // may be null
   try {
       sc.someMethod();
   } catch (NullPointerException ex) {
       // We don't know for sure if 'sc' was null, or if the NPE
       // happened within the `someMethod()` call.
   }

In short, this approach is liable to give misleading results.


A couple of other ways to deal with the problem of uninitialized variables:

  • Use @NotNull annotations and a static code analyzer.
  • Use Optional.

However neither of these is "bombproof" in real world Java.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Thanks! This is a much more comprehensive answer than I could've hoped for! Very much appreciated! – Ryan H. Jul 06 '18 at 02:37
1

How to tell if a variable has been initialized?

if (object != null) {
    // Object has been initialized
} else {
    // Object is null, which means not yet initialized
}

How to handle a not yet initialized variable, in other word, null object?

try {
    // Do something with the object
} catch (NullPointerException e) {
    e.printStackTrace();
}
Wei
  • 1,028
  • 8
  • 27
  • 1
    I daresay one never actually writes code to catch a null pointer exception. Such an exception is typically the results of a programming error that should be corrected either by ensuring proper initialization or by checking it before initializing it. – Edwin Dalorzo Jul 02 '18 at 22:40
  • I realized that, which is why I am using Kotlin. The OP may be new to Java, IMHO it may be able to shown someone that it is possible to do. Your comment too may be able to help other people. Thanks mentioning it. – Wei Jul 02 '18 at 22:47
0

Just check simply with a if-clause if object ain't null. If that's the case it has been initialized. Else it was not yet and also remove these redundant try catch clauses with NullPointerException since you can easily check and avoid null object types.

Example:

//your code below, the String object is just an example
String text = null;

if(text!=null) {
    //object has been initialized
} else {
    //object has not been initialized
}
sero583
  • 15
  • 6
0

The most general way is:

Object obj
//whatever code...
if(obj != null){
//obj exists
} 
else{
/*Handle the case where object doesn't exist, typically - trying to initialize it, but that's not the only case, actually lots of options available.*/}

However, if you know any information about the object type, or about the reason it may have been not initialized, it's always better to use something more specific. For example org.apache.commons.lang.StringUtils.isBlank(String str) for strings

Also: https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#isNull-java.lang.Object- https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#requireNonNull-T- And some other methods near the 2above

Ivan B
  • 23
  • 5