Can anyone explain the following to me?
When i run these three strings i get the following outputs:
In other words, why does char work but not the others? I realize you should use arrays.toString or print the arrays out in a loop, but there seems to be some intricate difference here between char and other arrays i do not grasp. Also, if i add something to sysout, e.g. System.out.println(testChar + "\t"); it does not work either. Why?
Tom Gibbins wrote:Thanks for the link, but it doesnt really explain why this works with char arrays but not any others? Why is char special? How is it special? Neither is there anything about why syntax
Basically, the link is saying that the PrintStream class, which is what the System.out instance is, has an overloaded method for char arrays. I guess the designers wanted the capability to treat char arrays like strings -- just like in the C language.
Tom Gibbins wrote:
System.out.println(testChar + "\t");
would not work?
That doesn't work as you expected because the concatenation does a toString() in order to do the concat. And the toString() method for char arrays doesn't return the string that you want.
There are several println methods that take different types as arguments.
There is println(Object), there is println(String) and there is println(char).
If you call an overloaded method, always the most specific one is called.
If you pass String, println(String) will be called. Not println(Object).
The same is true for char.
There is nothing special about char. You can see the difference in behaviour because there exists a method that takes char as an argument.
There is no separate method for String so in this case the most specific method will be println(Object).