Java program to convert char array to String

We can write a java program to convert the char array to string by creating a new string. It should be allocated a sequence of characters present in a char array. As we discussed that String is immutable in java, the new modification of the string does not affect the new string which is allocated. We pass the char array to the string constructor and we can use copyOf() to copy the characters of the array.

we have another way to convert char array to string. we do it by using value() method in java. The char sequence in the specified array can also be done using copyValueOf() method where we simply specify that part of the array which is to be copied.

This is how we create the first array:

char[] ar = {a , b, c , d};

Now, the value() method will convert the whole array into a string.

String s = String.valueOf(ar); 

Java program to convert char array to a String using String.valueOf()

public class DeveloperHelps {
   public static void main(String []args) {
      char[] arr = { 'a', 'b', 'c', 'd' };
      String s = String.valueOf(arr);
      System.out.println(s);
   }
}

The output of the above program will be:

abcd

In this program, we have used String.valueOf() which iterates the characters and gives the final output.

Now we will discuss about another method which is copyValueOf(). This method copies only the required part of the array. For instance the user has mentioned to only copy the first two characters of the array. The output will be the first two characters only.

Let’s see the program below to understand this method better.

public class DeveloperHelps  {
   public static void main(String []args) {
      char[] arr = { 'a', 'b', 'c', 'd' };
      String s = String.copyValueOf(arr, 1, 2);
      System.out.println(s);
   }
}

The output of the program will be:

bc

In this program, the output is clear as stated by the user which is the first two characters of the string. Not a as we know that we initialize the array from 0.

Leave a comment

Your email address will not be published.