Copy char array to string in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 13-Nov-2018 14:55:03
Advertisements