java string to char array and inverse leads to wrong result

1.2k views Asked by At

I want to convert a String to a char [] to perform some bitwise operations on it.

My first approach was to use the java standard functions:

String foo = "123456789"
char [] bar = foo.toCharArray();
System.out.println(bar.toString); //output: [C@4263e7f8

So it seems that the data gets altered using this function. If I do it all manually:

  String foo = "123456789"
  char [] bar = new char[foo.length()];
  for (int i=0; i< foo.length(); i++) {
     bar[i]=foo.charAt(i);
  }

 StringBuilder sb = new StringBuilder();
 for (int i=0; i< bar.length; i++) {
     sb.append(bar[i]);
 }

 System.out.println(sb.toString); //output: 123456789

My question is why I get different data when I use the standard functions. I was expecting that I always get the same data after .toCharArray followed by .toString. I'm not sure how a Java String is represented bitwise. May this be a reason?

4

There are 4 answers

0
Estimate On BEST ANSWER

Whenever you try to print an array by using toString(), it will print hashcode instead of printing the contents. Because:

Java arrays are objects and the direct superclass of an array type is Object.

Therefore when you are trying to call toString method, it will directly call Object's toString method which is:

getClass().getName() + '@' + Integer.toHexString(hashCode())

But when you are using StringBuilder class toString(), it will return a String object :

return new String(value, 0, count);
0
Eran On

foo.toCharArray() doesn't alter the data. If you want to get the original String back, you should call new String(bar).

Calling toString() on an array executes the default implementation of toString method in Object class, which shows the class name (for char arrays it shows [C) and the hashCode of the instance.

If you want to display the characters of that array, use Arrays.toString(bar).

0
HJK On

In the first code snippet, bar is an array object. So when you are trying to print the object, it prints it hashcode

If you use the same logic that building up a string from the char array after bar got created using toCharArray(), you could see the same result.

0
Arjit On

Use

System.out.println(Arrays.toString(bar)); //to print the result in list form
System.out.println(new String(bar)); //to print the result as a string

In JAVA, arraysare objectsthat are dynamically created and may be assigned to variables of type Object. All methods of class Objectmay be invoked on an array.

When you invoke toString() on an object it returns a string that "textually represents" the object. Because an array is an instance of Object that is why you only get the name of the class, the @ and a hex value.