Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String and Character Array in Java

I am a student who has just shifted from C++ to Java.

In Java what could be the main reason for defining separate data types for Strings and Char arrays? What is the difference between the two?

Since I have only studied C++, up till now I was under the impression that they are the same thing. Please clarify if possible.

like image 964
iluvthee07 Avatar asked Aug 20 '13 15:08

iluvthee07


1 Answers

String is immutable. Char array is not. A string is implemented with a char array underneath but every time you try to modify it (like with concatenation, replace etc.) it gives you a new String object.

So, String behaves as a constant Char array but comes with certain syntactic sugar that also makes them very easier to use. For example, the addition + operator has been overloaded as a string concatenation operator as well.

like image 168
Ravi K Thapliyal Avatar answered Nov 16 '22 00:11

Ravi K Thapliyal