Why do I get an exception called NullPointerException
if in Java there is no such concept as a pointer?
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 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.
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.
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.)
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++.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With