Quick Java question?

Started by
2 comments, last by ugor 19 years, 10 months ago
I have the following code: public static void main(String args[]) { Object word[] = new Object[5]; word[0] = "h"; word[1] = "e"; word[2] = "l"; word[3] = "l"; word[4] = "o"; System.out.println(word); } now when i run the program this is the output i get: [Ljava.lang.Object;@7259da , now am i doing something wrong because the output that i was expecting to get was ''hello''.
Advertisement
println uses Object.toString when it has a non-string type passed to it, so you're effectivly doing:
System.out.println( word.toString() );

And since arrays in Java are actually objects themselves, you get a standard toString provided for you which gives you some details about it. If you want to get the output "hello" then you can do:
String output = "";
for (int i=0; i output += word;
System.out.println(output);


[edited by - PouyaCatnip on May 30, 2004 2:55:30 PM]
Additionally, Strings are immutable in Java, so you can never modify characters of them.

Either use a StringBuffer or an array of char

 char word[] = new char[5]; word[0] = ''h''; word[1] = ''e''; word[2] = ''l''; word[3] = ''l''; word[4] = ''o''; System.out.println(new String(word));


Or something.

Note that in Java, chars are different from Strings, and you must use single quotes to specify constant chars (as opposed to constant strings which is what your existing example does)

Mark
Right now you are making an array of Objects (which array is itself an Object), which all happen to be Strings, and then trying to print the array object itself. The array itself has a string representation which is implicitly requested within the PrintStream.println() method (PrintStream being the type of the System.out object). This representation is accessed using the Object.toString method, and by default (i.e. unless overridden in a subclass) prints:

- the type of the object, i.e. what you would get from Object.getClass().getName().
- an ''@'' sign.
- the location in memory of the object (although you''re not supposed to know that that''s what it means, really), which is the default Object.hashcode().

If you iterate through the array and print each Object, it will work, because each happens to be a String. System.out.println() is overloaded for String arguments. (Also, String.toString() is overloaded such that the String just returns itself).

But if you just want to store the word "Hello" in memory and print it out, then just use a single String :/

This topic is closed to new replies.

Advertisement