Difference Between Character Array and String

Computer ProgrammingProgrammingMiscellaneous

In this post, we will understand the difference between character array and string.

Strings

  • They are immutable.

  • Once they are defined, they can’t be changed.

  • It refers to a sequence of characters, which is represented as a single data type.

  • It contains built-in functions such as substring(), charAt().

  • The ‘+’ operator can be used to append strings together, which would form a new string.

  • The charAt() method helps access characters at a specific index within a ‘String’.

  • These strings are stored in the ‘String Constant Pool’.

  • It is not preferred to store passwords in strings in Java.

  • A string can be converted to a character array using toCharArray() method of ‘String’ class.

Example

String my_string = "JANE" ;
char [] ch = my_string.toCharArray();

Character Arrays

  • They are mutable.

  • This means their values can be changed.

  • It is a sequential collection of data type ‘char’.

  • It doesn’t have built-in methods to perform operations on character arrays in Java.

  • The ‘+’ operator can’t be used to append two character arrays.

  • The characters in a character array can be accessed using index.

  • The values in a character array are stored in contiguous memory locations.

  • All character arrays are stored in Heap.

  • The passwords can be stored in character arrays in Java.

  • A character array can be converted into a string by passing it to a String Constructor.

Example

char[] my_char = {'J','A','N','E'};
String my_str = new String(my_char);
raja
Published on 24-Mar-2021 13:26:29
Advertisements