File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Strings, Strings[] and null Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Strings, Strings[] and null" Watch "Strings, Strings[] and null" New topic
Author

Strings, Strings[] and null

Dale DeMott
Ranch Hand

Joined: Nov 02, 2000
Posts: 515
Okay.. so here's the situation.. when I have String[] and don't initialize the array, I get null objects within the compiler and it brings down my app, however when I have a String that is not initialized, String prints out null when I try to print out the value but DOES NOT crash. Why the difference.

VS.


By failing to prepare, you are preparing to fail.<br />Benjamin Franklin (1706 - 1790)
Rob Ross
Bartender

Joined: Jan 07, 2002
Posts: 2205
Your program probably doesn't actually crash; I'm guessing you get an ArrayIndexOutOfBoundsException?
System.out.println(myTest.myString[0]);
when you make this declaration:
String[] myString;
You are saying "hey, I have this variable called myString, and it can reference (point to) arrays of String."
But you haven't made it point to anything yet. So when you try to access an element from it, the VM is going to complain.
Now, when you write
String myString;
This also creates a reference to an object of type String, and as above, it doesn't yet actually reference anything. Since it's an instance variable it gets the default null value.
When you try to print null in a println statement, println() is smart enough to actually handle printing null values.
The difference between your first and second examples is that you are getting an exception during the accessing of a non-existant element, and that is why the program is terminating.
If you had actually created an array:
String[] myString = new String[1];
When you refer to myString[0], this element actually exsits now, so you won't get the exception. The *value* of this element is null because you haven't assigned it anything yet, however, the element itself exists, unlike in your previous example.

Rob


Rob
SCJP 1.4
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Strings, Strings[] and null