• Post Reply Bookmark Topic Watch Topic
  • New Topic

array variable initialization and textual reprezentation of the array object problem  RSS feed

 
Marius Constantin
Ranch Hand
Posts: 62
Java Notepad Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


hello Experts,

The code above crushes with an error saying that list6 was not initialized. How come. list6 should have a null value, right ?

And if I change the code to



it displays something like [B@5baa855, witch should be the reference to the array object, but instead it's a textual representation of the has code of the array object.

Could you please explain me what's going on ?

Thank you for your time, patience and help.

Kind regards,
marius
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(1) No, local variables aren't automatically initialized; you must set them to some value before you can use them.

(2) That's what the toString() method for array objects returns, so that's what gets printed. It would be nice if that method returned something more useful, but alas, it does not. Usefully printing an array in Java involves a for loop to print each element, or using one of the static utility methods in java.util.Arrays.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the first case, no, the variable doesn't get initialised to null. Member variables do, but local variables are "uninitialised", and it's a compile-time error if you try and use them without providing a value first.

In the second case, System.out.println() will print the value of the toString() method of the object. The default value of toString() defined in Object (which is also inherited by array types) gives you a string based on the type of the object and the hash code.

(Edit: or what Ernest said 17 seconds earlier)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!