📜  Java字符串和字符数组的区别

📅  最后修改于: 2021-09-14 02:22:56             🧑  作者: Mango

与 C/C++ 不同,字符数组和字符串在Java是两种不同的东西。字符数组和字符串都是字符的集合,但在属性方面有所不同。


字符串字符数组的区别:

Strings Character Arrays
String refers to a sequence of characters represented as a single data type. Character Array is a sequential collection of data type char.
Strings are immutable. Character Arrays are mutable.
Built in functions like substring(), charAt() etc can be used on Strings. No built in functions are provided in Java for operations on Character Arrays.
‘+’ can be used to appended strings together to form a new string. ‘+’ cannot be used to append two Character Arrays.
The charAt() method can be used to access characters at a particular index in a String. The characters in a Character Array can be accessed normally like in any other language by using [].
Strings can be stored in any any manner in the memory. Elements in Character Array are stored contiguously in increasing memory locations.
All Strings are stored in the String Constant Pool. All Character Arrays are stored in the Heap.
Not preferred for storing passwords in Java. Preferred for storing passwords in Java.
A String can be converted into Character Array by using the toCharArray() method of String class.
Eg: String s = “GEEKS”;
char [] ch = s.toCharArray();
A Character Array can be converted into String by passing it into a String Constructor.
Eg: char[] a = {‘G’, ‘E’, ‘E’, ‘K’, ‘S’};
String A = new String(a);