Copy Char Array to String in Java



Use the valueOf() method in Java to copy char array to string. You can also use the copyValueOf() method, which represents the character sequence in the array specified. Here, you can specify the part of array to be copied.

Let us first create a character array.

char[] arr = { 'p', 'q', 'r', 's' };

The method valueOf() will convert the entire array into a string.

String str = String.valueOf(arr);

The following is an example.

Example

 Live Demo

public class Demo {
   public static void main(String []args) {
      char[] arr = { 'p', 'q', 'r', 's' };
      String str = String.valueOf(arr);
      System.out.println(str);
   }
}

Output

Pqrs

Let us see another example that use copyValueOf() method that convert char array to string.

Example

 Live Demo

public class Demo {
   public static void main(String []args) {
      char[] arr = { 'p', 'q', 'r', 's' };
      String str = String.copyValueOf(arr, 1, 2);
      System.out.println(str);
   }
}

Output

Qr
Updated on: 2020-06-26T12:11:17+05:30

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements