I coded a sample Java program:
String str="JAVA is awesome";
char[] ch=str.toCharArray();
System.out.println("The value of ch is : " + ch);
It is showing an unexpected result with some random ascii value... What is the problem?
I coded a sample Java program:
String str="JAVA is awesome";
char[] ch=str.toCharArray();
System.out.println("The value of ch is : " + ch);
It is showing an unexpected result with some random ascii value... What is the problem?
You really don't need this step char ch[]=new char[n];
As javadoc says String#toCharArray()- returns a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.
And in this line System.out.println("The value of ch is : " + ch);
Just 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.
So this few lines below should do what you want to achieve
String str="JAVA is awesome";
char[] ch = str.toCharArray();
System.out.println(java.util.Arrays.toString(ch));
Where Arrays.toString(char[] ch) - Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space).
This line
System.out.println("The value of ch is : " + ch);
Will print out
The value of ch is : //And the hash code of your array, which is just an object in Java
If you want meaningful data, use the Arrays.toString()
overloaded method...
System.out.println("The value of ch is : " + Arrays.toString(ch));
Take a look at the Javadocs for the Array.toString() method to see when it may be useful in your case.
This code:
System.out.println("The value of ch is : " + ch);
is equivalent to this
System.out.println("The value of ch is : " + ch.toString());
As ch
is an array object it inherits toString()
method from Object.toString(). This 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.
Try to use one of these for the output you need:
System.out.println("The value of ch is : " + new String(ch)); //prints ch array as String
System.out.println("The value of ch is : " + String.valueOf(ch)); //prints ch array as String
System.out.println("The value of ch is : " + Arrays.toString(ch)); //prints every letter separately