Can "This" Ever Be Null in Java

Can this ever be null in Java?

No it can't. If you're using this, then you're in the instance so this isn't null.

The JLS says :

When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method was invoked (§15.12), or to the object being constructed.

If you invoked a method from an object, then the object exists or you would have a NullPointerException before (or it's a static method but then, you can't use this in it).


Resources :

  • JLS - this keyword

How to check a Long for null in java

Primitive data types cannot be null. Only Object data types can be null.

There are 8 primitive types in Java:















































Data TypeSizeDescription
byte1 byteInt8
short2 bytesInt16
int4 bytesInt32
long8 bytesInt64
float4 bytesSingle
double8 bytesDouble
boolean1 bitBoolean

Is this in any way useful if (this != null)?

this can never be null in Java so this kind of code is never useful.

Avoiding NullPointerException in Java

This to me sounds like a reasonably common problem that junior to intermediate developers tend to face at some point: they either don't know or don't trust the contracts they are participating in and defensively overcheck for nulls. Additionally, when writing their own code, they tend to rely on returning nulls to indicate something thus requiring the caller to check for nulls.

To put this another way, there are two instances where null checking comes up:

  1. Where null is a valid response in terms of the contract; and

  2. Where it isn't a valid response.

(2) is easy. As of Java 1.7 you can use Objects.requireNonNull(foo). (If you are stuck with a previous version then assertions may be a good alternative.)

"Proper" usage of this method would be like below. The method returns the object passed into it and throws a NullPointerException if the object is null. This means that the returned value is always non-null. The method is primarily intended for validating parameters.

public Foo(Bar bar) {
this.bar = Objects.requireNonNull(bar);
}

It can also be used like an assertion though since it throws an exception if the object is null. In both uses, a message can be added which will be shown in the exception. Below is using it like an assertion and providing a message.

Objects.requireNonNull(someobject, "if someobject is null then something is wrong");
someobject.doCalc();

Generally throwing a specific exception like NullPointerException when a value is null but shouldn't be is favorable to throwing a more general exception like AssertionError. This is the approach the Java library takes; favoring NullPointerException over IllegalArgumentException when an argument is not allowed to be null.

(1) is a little harder. If you have no control over the code you're calling then you're stuck. If null is a valid response, you have to check for it.

If it's code that you do control, however (and this is often the case), then it's a different story. Avoid using nulls as a response. With methods that return collections, it's easy: return empty collections (or arrays) instead of nulls pretty much all the time.

With non-collections it might be harder. Consider this as an example: if you have these interfaces:

public interface Action {
void doSomething();
}

public interface Parser {
Action findAction(String userInput);
}

where Parser takes raw user input and finds something to do, perhaps if you're implementing a command line interface for something. Now you might make the contract that it returns null if there's no appropriate action. That leads the null checking you're talking about.

An alternative solution is to never return null and instead use the Null Object pattern:

public class MyParser implements Parser {
private static Action DO_NOTHING = new Action() {
public void doSomething() { /* do nothing */ }
};

public Action findAction(String userInput) {
// ...
if ( /* we can't find any actions */ ) {
return DO_NOTHING;
}
}
}

Compare:

Parser parser = ParserFactory.getParser();
if (parser == null) {
// now what?
// this would be an example of where null isn't (or shouldn't be) a valid response
}
Action action = parser.findAction(someInput);
if (action == null) {
// do nothing
} else {
action.doSomething();
}

to

ParserFactory.getParser().findAction(someInput).doSomething();

which is a much better design because it leads to more concise code.

That said, perhaps it is entirely appropriate for the findAction() method to throw an Exception with a meaningful error message -- especially in this case where you are relying on user input. It would be much better for the findAction method to throw an Exception than for the calling method to blow up with a simple NullPointerException with no explanation.

try {
ParserFactory.getParser().findAction(someInput).doSomething();
} catch(ActionNotFoundException anfe) {
userConsole.err(anfe.getMessage());
}

Or if you think the try/catch mechanism is too ugly, rather than Do Nothing your default action should provide feedback to the user.

public Action findAction(final String userInput) {
/* Code to return requested Action if found */
return new Action() {
public void doSomething() {
userConsole.err("Action not found: " + userInput);
}
}
}

How to tell Java that a variable cannot possibly be null?

After just trying to execute the code regardless of Eclipse complaining, I noticed that it does indeed run without problems. So apparently it was just a warning being set to "error" level, despite not being critical.

There was a "configure problem severity" button, so I set the severity of "Potential null pointer access" to "warning" (and adjusted some other levels accordingly). Now Eclipse just marks it as warning and executes the code without complaining.

In Java, is it possible to declare a field that can never become null?

Technically references are nullable. Even though you can use final to make sure that the compiler won't let you leave a variable null, you can use reflection to remove its finality and set it to null.

If you count out reflection, then let's say native code or Unsafe or bytecode instrumentation or so on and so on. In the end, the internal representation allows nulls, so depending on how far you'll go there'll be a way to make a variable null if you really want to, unless you specify constraints about what's allowed/possible, such as whether a SecurityManager is involved.

If you're asking the question because you're afraid that your variable isn't safe enough from NullPointerExceptions, then using final, Objects.requireNonNull() and good design is enough.

Can new Double(String) ever return a null?

Read the specifications: section 15.9.4 of the JLS:

The value of a class instance creation expression is a reference to the newly created object of the specified class. Every time the expression is evaluated, a fresh object is created.

A constructor therefore can never return null. However, an java.lang.OutOfMemoryError may occur.

Can an int be null in Java?

int can't be null, but Integer can. You need to be careful when unboxing null Integers since this can cause a lot of confusion and head scratching!

e.g. this:

int a = object.getA(); // getA returns a null Integer

will give you a NullPointerException, despite object not being null!

To follow up on your question, if you want to indicate the absence of a value, I would investigate java.util.Optional<Integer>

Best way to check for null values in Java?

Method 4 is best.

if(foo != null && foo.bar()) {
someStuff();
}

will use short-circuit evaluation, meaning it ends if the first condition of a logical AND is false.



Related Topics



Leave a reply



Submit