Difference Between String and Character Array in Java



On technical groud, we can say that both a character array and string contain the sequence of characters and used as a collection of characters. But there are significant differences between both which we would discuss below.

The following are the important differences between String and Character array.

Sr. No. Key String Character array
1 Implementation String is implemented to store sequence of characters and to be represented as a single data type and single entity. Character Array on the other hand is a sequential collection of data type char where each element is a separate entity.
2 Internal implementation String internal implementation makes it immutable in nature. Character array is mutable in nature on the other hands.
3 Built-in Functions As String is a class so is provided with various built-in function substring(), charAt() etc. No built in functions are provided in Java for operations on Character Arrays.
4 Concatenation String can be concatenated either by using + operator or using its built in function concate(). Character array could not use either of these function/operator to get concatenated.
5 Storage Strings could be get stored in any random order in the part of memory which is known as SCP (String Constant Pool). Elements in Character Array are stored contiguously in increasing memory locations which is known as Heap.
6 Conversion A String can be converted into Character Array by using the toCharArray() method of String class. On the other hand, a Character Array can be converted into String by passing it into a String Constructor.

Example of String vs Character Array

 Live Demo

JavaTester.java

public class JavaTester{
   public static void main(String[] args) {
      String s = "HELLO";
      char [] ch = s.toCharArray();
      char[] a = {'H', 'E', 'L', 'L', 'O'};
      String A = new String(a);
      System.out.println(s);
      System.out.println(A);
   }
}

Output

HELLO
HELLO
Updated on: 2019-09-18T14:27:27+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements