I know that String
is immutable so if you change a string it will make a separate string so I thought that a char
array might be a better option. I looked up if char
is immutable and a lot of people say it is and some people say it is just the wrapper class that is immutable. I want to know if char
is immutable and if using a char
array is a better option than using a String if the word that is stored will change often

- 11
- 2
-
Use StringBuffer? – Fullstack Guy Sep 09 '18 at 07:03
-
3Use a String. Make your code robust and readable instead of trying to make it faster for no good reason. – JB Nizet Sep 09 '18 at 07:03
2 Answers
char is immutable because it is a primitive. Check out this answer: Are Java primitives immutable?
Regardless, arrays are mutable. You can change the value of the char array by changing the values in the array.
Is using a char array more efficient? theoretically yes, however you will be giving up a lot of the functionality given by using String. This will force you to implement stuff yourself, which will probably be less efficient than just using String.
My advice, start with String, if your whole application performance is dependant on this, you can start thinking of other solutions.
Don't solve problems you do not have :-)

- 5,948
- 6
- 33
- 52
In Java all primitive types are mutable by default and immutable if and only if they are defined with the final
modifier. Using a char
array as a mutable alternative to String
is wrong. Use StringBuilder
instead.

- 577
- 3
- 14
-
final and mutability are orthogonal concepts. Is a final String immutable? Read the discussion here: https://stackoverflow.com/questions/18037082/are-java-primitives-immutable – galusben Sep 09 '18 at 20:11
-
`String` is not primitive, so your comment has no sense in discussion of my answer. Read the original question and my answer to it again. – Rostislav Krasny Sep 09 '18 at 20:28
-
My point is that final does not make something immutable. You are confusing immutability with final. Please read https://www.google.com/amp/s/www.geeksforgeeks.org/final-vs-immutability-java/amp/ – galusben Sep 09 '18 at 20:53
-
I'm not confusing anything. @Ammawn has asked two questions: 1) "I want to know if `char` is immutable"; 2) "... if using a `char` array is a better option than using a `String` if the word that is stored will change often". Also read my answer in https://stackoverflow.com/questions/18037082/are-java-primitives-immutable regarding mutability of primitive types in Java. – Rostislav Krasny Sep 09 '18 at 21:09