Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Array Char And String Difference In Array [duplicate]

While making up some arrays I noticed that

char[] javaArray = {'j','a','v','a'};

prints out

java

but

String[] javaStringArray = {"j","a","v","a"};

only prints the stack location. I know char and String are both very different, but how come the JVM knows to output chars for the first and only a stack location for the second?

I am using IntelliJ and the command System.out.println(javaArray);

like image 762
Clatty Cake Avatar asked Jun 22 '18 18:06

Clatty Cake


People also ask

Is character array and string array same?

No. String is implemented to store sequence of characters and to be represented as a single data type and single entity. Character Array on the other hand is a sequential collection of data type char where each element is a separate entity.

Which is better string or character array in Java?

We should always store the secure information in char[] array rather than String. Since String is immutable if we store the password as plain text it will be available in memory until the garbage collector cleans it.

Is char array better than string?

Since Strings are immutable there is no way the contents of Strings can be changed because any change will produce a new String, while if you use a char[] you can still set all the elements as blank or zero. So storing a password in a character array clearly mitigates the security risk of stealing a password.

How do you find duplicates in string array?

Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.


1 Answers

This happens because PrintStream has a special override for char[], but it lacks such overrides for String[] and other array types:

PrintStream.println(char[] x)

If you call toString() on javaArray when printing, the results would look similar to what you get when you print String[]:

char[] javaArray = {'j','a','v','a'};
System.out.println(javaArray.toString()); // Prints something like [C@1540e19d
like image 87
Sergey Kalinichenko Avatar answered Sep 19 '22 13:09

Sergey Kalinichenko