Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use char[] instead of String?

In Thread.java, line 146, I have noticed that the author used a char[] instead of a String for the name field. Are there any performance reasons that I am not aware of? getName() also wraps the character in a String before returning the name. Isn't it better to just use a String?

like image 658
Amir Raminfar Avatar asked Nov 21 '11 04:11

Amir Raminfar


People also ask

Why is character array better than string?

Since String is immutable, there is no method defined that allow us to change or overwrite the content of the string. This feature makes string objects unstable for storing secure information such as passwords, SSN, etc. We should always store the secure information in char[] array rather than String.

Is char [] the same as string?

Well, string type is a completely managed class for character strings, while char[] is still what it was in C, a byte array representing a character string for you.

Which is better char array or string?

With plain String, there are much higher chances of accidentally printing the password to logs, monitors or some other insecure place. char[] is less vulnerable.

Which is better char [] or string in Java?

char is a primitive data type whereas String is a class in java. char represents a single character whereas String can have zero or more characters. So String is an array of chars. We define char in java program using single quote (') whereas we can define String in Java using double quotes (").


2 Answers

In general, yes. I suspect char[] was used in Thread for performance reasons, back in the days when such things in Java required every effort to get decent performance. With the advent of modern JVMs, such micro-optimizations have long since become unimportant, but it's just been left that way.

There's a lot of weird code in the old Java 1.0-era source, I wouldn't pay too much attention to it.

like image 65
skaffman Avatar answered Oct 16 '22 12:10

skaffman


Hard to say. Perhaps they had some optimizations in mind, perhaps the person who wrote this code was simply more used to the C-style char* arrays for strings, or perhaps by the time this code was written they were not sure if strings will be immutable or not. But with this code, any time a Thread.getName() is called, a new char array is created, so this code is actually heavier on the GC than just using a string.

like image 21
Denis Tulskiy Avatar answered Oct 16 '22 12:10

Denis Tulskiy