Java Array Char And String Difference In Array

  • A+
Category:Languages

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);

 


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 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: