When carr2 is printed in a new line there are no problems, program runs as I expected. But if I use only one print method
(for example System.out.println("First five elements of "+s1+" are "+carr2)) some unknown elements are get printed for carr2.
What is the reason ?
Why should I use two print methods?
Cannot it be done by using one print method.
Gihan Madushanka wrote:What is the reason ?
you'll get String like [C@abcdef because when use an Object with String JVM calls toString() method of char object which will give you String representation of the Object.
So according to java.lang.Object, it represents memory address of that object.
That's why you will get weird result.
Gihan Madushanka wrote:Why should I use two print methods?
No you don't want to use two print methods.
Use java.lang.String class in Java API. concentrate on Constructors
Again use java API docs. Java API
Supun Lakshan Dissanayake wrote:you'll get String like [C@abcdef because when use an Object with String JVM calls toString() method of char object which will give you String representation of the Object.
It's not because carr2 is an Object. Lots of things that are Objects have meaningful String representations. As I stated above, it's because arrays don't override toString().
according to java.lang.Object, it represents memory address of that object.
Not exactly. According to the documentation for Object.toString(): "The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object." The hashCode in turn is "typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language."
So it may be base on the address, but maybe not. And it doesn't "represent" the address. In fact, on my machine I know for a fact that at least some Objects must be able to have hashCodes that are not their addresses, by virtue of the fact that I have more memory than there are possible values for hashCode.