Java toString method in char[] [duplicate] - java

This question already has answers here:
Why does the toString method in java not seem to work for an array
(9 answers)
How to convert a char array back to a string?
(14 answers)
Closed 9 years ago.
I thought the toString method will make a char array to a String, but I was wrong.
char[] k=new char[2];
k[0]='k';
k[1]='k';
System.out.println(k.toString());
This code will output: [C#112f614.
What exactly happened in this code k.toString()?
Should I never call toString method in a char array?
Thanks!
Happy New Year!

You want to use Arrays.toString(char[]{'a','b'});
You can use
char data[] = {'a', 'b', 'c'};
String str = new String(data);
See the javadoc
public String(char[] value)
Allocates a new String so that it
represents the sequence of characters currently contained in the
character array argument. The contents of the character array are
copied; subsequent modification of the character array does not affect
the newly created string. Parameters: value - The initial value of the
string
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html
Calling toString on an array will call the toString method from Object. Which will return you the hashCode
public String toString() Returns a string representation of the
object. In general, the toString method returns a string that
"textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is
recommended that all subclasses override this method. 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. In other words, this method returns a string equal to the
value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
Returns: a string representation of the object.

Because arrays are objects. So calling toString() result to call the toString() method herited from the object class which is :
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
In [C#112f614, [C means that it's an array of char.
If you want to print the content of your array, use Arrays.toString(char[] a)

What exactly happened in this code k.toString()? Should I never call toString method in a char array?
The toString method of a char array inherits the default toString behavior from Object, which is to simply print a unique identifier derived from the object's location in memory. So unless you want that unique identifier, there's not much point in calling k.toString(). (k being your char array)

You should likely never call toString on any sort of array. The Arrays class has many utility methods for creating string representations of arrays.

A partial answer to this question: "What exactly happened in this code k.toString()?"
toString() is inherited from java.lang.Object and not overridden. The implementation just print the canonical class name plus the #-letter plus the hashcode. That is all. Therefore calling this methode is not useful for applications and is just for debugging purposes in IDEs to at least enlighten which type of object is there.

String can take a char array as a constructor.
String s = new String(k);

Related

String literal with toCharArray() producing garbage in Java

I wanted to create a char array of the alphabet. I looked at this post:
Better way to generate array of all letters in the alphabet
which said this:
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
So in my code I have:
public class Alphabet {
private char[] letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
public String availableLetters(){
return letters.toString();
}
}
When I call the function availableLetters() from main() and printit to the console, it outputs this garbage:
[C#15db9742
What am I doing wrong?
The array is correct, the problem is that you are not printing it correctly.
If you print your array one character at a time, you would get a correct result:
for (char c : letters) {
System.out.print("'" + c + "' ");
}
demo
Unfortunately, Java standard class library does not provide a meaningful override of toString() for arrays, causing a lot of trouble for programmers who are new to the language.
If you want to print it in array form, then use:
System.out.println(Arrays.toString(letters));
BTW: The [C#15db9742 is not really garbage. It's what gets printed out when a class does not override the toString() method.
From Object.toString():
Returns a string representation of the object. In general, the
toString method returns a string that "textually represents" this
object. The result should be a concise but informative representation
that is easy for a person to read. It is recommended that all
subclasses override this method. 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. In other
words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
You can pass the char array to the String constructor or the static method String.valueOf() and return that instead.

Why is this printing the memory address of array

So this first code returns the memory address of the integer array, but I want it to print out the actual array.
import java.util.Arrays;
public class FinalsReview{
int[] list = new int[]{12, 435,546, 7, 24, 4, 6, 45, 21, 1};
public static void main(String[]args){
FinalsReview hello = new FinalsReview();
System.out.print(hello.create());
}
public int[] create(){
Arrays.toString(list);
return list;
}
}
However, the following code prints the actual array.
import java.util.Arrays;
public class FinalsReview{
int[] list = new int[]{12, 435,546, 7, 24, 4, 6, 45, 21, 1};
public static void main(String[]args){
FinalsReview hello = new FinalsReview();
hello.create();
}
public void create(){
System.out.println(Arrays.toString(list));
}
}
Why does the first one return the memory address?
it is not memory address, it is the hashCode() and classname that is how toString() is defined in Object, when you don't specify toString() method for int[] class you inherit it from Object
and that is implemented like
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
while this Arrays.toString(list) is explicitly iterates over the Collection and printing value of each element
and why that from http://bugs.java.com/view_bug.do?bug_id=4168079
One caveat: the toString() method is often used in printing diagnostics.
One would have to be careful if very large arrays were involved. The
Lisp language deals with this using the print-level/print-length mechanism.
Something similar would be needed in Java as well. In practice, the
'toString' method provided in every class should be preferred as the
brief option suitable for use in concise diagnostics, and a more verbose
representation provided by additional application-specific conversion methods
if needed by the application logic.
Regardless of its technical merit, however, it is doubtful that we can make
such a change at this late date due to compatibility/stability concerns.
william.maddox#Eng 1998-08-31
I concur. It would definitely have been the right thing in 1.0, or
maybe even 1.1, but it's almost certainly too late for all of these changes
except perhaps the toString change. One consolation is that it's amazingly easy
It's because you're returning the array from the method create, and when you attempt to print it, the display is what Jigar Joshi described. Simply calling Arrays.toString(list) will not reformat the array so that it will give the output that you expect when you try to print it.
If you want it to print the elements of the array, have your method return String instead, and use return Arrays.toString(list).
Arrays.toString(list) merely returns a String that is being printed at System.out.println(Arrays.toString(list)), however in your first method you are just returning the Array without saving the result of Arrays.toString(list). You're only printing yourList.toString(), so to say:
int[] myList = ... //initialize
String s = Arrays.toString(list); //Save the returned String in a variable
System.out.println(myList); //Prints myList.toString()
System.out.println(s); //Prints out the contents of the array
The line
System.out.print(hello.create());
is evaluated by first invoking the create() method, the passing its return value (a reference to an object of type int[]) to the print() method of System.out. That method's Javadoc reads:
Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().
and the Javadoc of String.valueOf() reads:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
Ok, our array reference isn't null, so what does its toString method do? The answer is in section 10.7 of the Java Language Specification, which reads:
The members of an array type are all of the following:
The public final field length, which contains the number of components of the array. length may be positive or zero.
The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].
A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.
All the members inherited from class Object; the only method of Object that is not inherited is its clone method.
Therefore, the toString method must be inherited from Object. The Javadoc of Object.toString reads:
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
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. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
... and that's why you see the type and hashCode of the array object when you print your array. (Incidentally, a hash code is not quite the same as a memory address. For one, several objects may have the same hash code; otherwise java would be limited to about 4 billion objects per application).
That's why Arrays.toString is a useful method to have, as it returns a String with the contents of the array. (You do invoke this method in create(), and it builds that String, but then you don't do anything with that String object, which is why it isn't printed).
In your first example, you are running Arrays.toString(list); but youare throwing away the result (a single String), and returning the original value of list. System.out.println is then trying to convert the whole int[] array into a string, which it doesn't know how to do, so it is giving you the unexpected output.
In the second example, you are running the same utility function, but this time passing its output to System.out.println. The input to System.out.println is now the string you wanted.
What you need to do is make the create function return the String given by Arrays.toString(list), rather than the original int[].

implicit toString() call in sysout - unexpected behavior [duplicate]

I was experimenting with toCharArray() and found some strange behavior.
Suppose private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();
System.out.println(HEX_CHARS);
/* prints 0123456789abcdef */
System.out.println("this is HEX_CHARS "+HEX_CHARS);
/* prints [C#19821f */
Any theoretical reason behind this?
It is because the parameter to println is different in the two calls.
The first parameter is called with char[] and the second is called with a string, where HEX_CHARS is converted with a call to .toString().
The println() have an overriden method that accepts a charArray.
The first line calls the method
print(char[] s)
on the PrintStream which prints what you expect. The second one calls the method
print(String s)
Where is concatenating the string with the toString implementation of the array which is that ugly thing you get ([C#19821f).
Arrays are objects, and its toString methods returns
getClass().getName() + "#" + Integer.toHexString(hashCode())
In your case [C#19821f means char[] and #19821f is its hashcode in hex notation.
If you want to print values from that array use iteration or Arrays.toString method.
`System.out.println(Arrays.toString(HEX_CHARS));`
The strange output is the toString() of the char[] type. for some odd reason, java decided to have a useless default implementation of toString() on array types. try Arrays.toString(HEX_STRING) instead.

Strange toCharArray() behavior

I was experimenting with toCharArray() and found some strange behavior.
Suppose private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();
System.out.println(HEX_CHARS);
/* prints 0123456789abcdef */
System.out.println("this is HEX_CHARS "+HEX_CHARS);
/* prints [C#19821f */
Any theoretical reason behind this?
It is because the parameter to println is different in the two calls.
The first parameter is called with char[] and the second is called with a string, where HEX_CHARS is converted with a call to .toString().
The println() have an overriden method that accepts a charArray.
The first line calls the method
print(char[] s)
on the PrintStream which prints what you expect. The second one calls the method
print(String s)
Where is concatenating the string with the toString implementation of the array which is that ugly thing you get ([C#19821f).
Arrays are objects, and its toString methods returns
getClass().getName() + "#" + Integer.toHexString(hashCode())
In your case [C#19821f means char[] and #19821f is its hashcode in hex notation.
If you want to print values from that array use iteration or Arrays.toString method.
`System.out.println(Arrays.toString(HEX_CHARS));`
The strange output is the toString() of the char[] type. for some odd reason, java decided to have a useless default implementation of toString() on array types. try Arrays.toString(HEX_STRING) instead.

How to find character array length in Android

I had used the following code to find the length
String str=strLenData.toString();
int ipLen= str.length();
return ipLen;
ipLen would return 11 every time. whatever be the actual value of strLenData. when I call toString() function, value of str: "[C#40523f80". Now I have to use char[] and i need to know the end (or length) of char[].
How do I do it?
If I understand correctly the strLenData variable is a char[]? In that case, you can just do
return strLenData.length;.
I don't think strLenData is charSequence or something. its just a regular object and may be it does't have toString() method. so toString() method of Object class gets called which just returns the HashCode value of The Objects Reference.
so make sure strLenData.toString() can be used.
ipLen is returning 11 always because you are converting an char array to String equivalent by using toString() method.
if you want to create String by an char array use.
String str = new String(strLenData);
Or if you want just want to get length of your char array use answer given by Steven.
use strLenData.length;

Categories

Resources