Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java have a "NullPointerException" when there are no pointers in Java?

Why do I get an exception called NullPointerException if in Java there is no such concept as a pointer?

like image 702
There is nothing we can do Avatar asked May 07 '10 08:05

There is nothing we can do


People also ask

Why does Java do not have pointers How does Java overcome the need of having pointers?

So overall Java doesn't have pointers (in the C/C++ sense) because it doesn't need them for general purpose OOP programming. Furthermore, adding pointers to Java would undermine security and robustness and make the language more complex.

What is the reason for NullPointerException in Java?

What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.

How do I fix NullPointerException in Java?

In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

Are there no pointers in Java?

Java does not support or allow pointers. (Or more properly , Java does not support pointers that can be accessed and/or modified by the programmer.)


2 Answers

There are no general purpose pointers in Java, that you can easily manipulate by adding and subtracting arbitrary values like in C. This can lead to all sorts of problems for those unused to them.

However, Java still needs to distinguish between an object and "no object". It's just the name of the exception that means you're trying to use an object reference that doesn't have a backing object behind it.

You could just as easily call it NoObjectException or DereferenceException, or one of a myriad of other names to minimise the possibility that people would think Java had general purpose pointers.

But NullPointerException is what the language creators opted for, probably because they were used to coding in C and/or C++.

like image 131
paxdiablo Avatar answered Sep 21 '22 11:09

paxdiablo


Yes this is one of the first annoying things I learned when learning Java LOL. It really should be called NullReferenceException, NoObjectException or DereferenceException as paxdiablo mentioned. References don't even have to represented internally as pointers and you shouldn't have to care. "Most VMs including Sun's use handles, not pointers. A handle is a pointer to a pointer so who knows how they came up with using that?" Oh Microsoft's Java VM actually does use pointers rather than handles so go figure.

like image 44
daveangel Avatar answered Sep 22 '22 11:09

daveangel