This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strings, Strings[] and null

 
Dale DeMott
Ranch Hand
Posts: 515
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Ross
Bartender
Posts: 2205
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic