Hello, I have got a question regarding „NullPointerException“ – when does it occur? Why does it print „null“ when I print out String s which has no reference Why does it print „NullPointerException“ when i perform an operation on String/Object s which has no reference?
I'll take a crack at this. String objects initialize to null unless you specify what it points at such as: String s = "mystring"; As for the NullPointer - the operation is trying to perform an operation on an object which in this case has been initalized to null. Let me know if that doesn't help.
The member s is a reference to a String instance. s is initialized to the value null. The method System.out.println sees that s has the value null and kindly prints the string "null". It would do the same for any type of reference which has the null value. However, when you do s.getLength() you are saying "send the getLength() message to the object referenced by s." But s does not refer to any object and so you get the NullPointerException. This name obviously comes from Java's C/C++ origins. Maybe it should have been better called "NullReferenceException". That's how I see it. -Barry