Java Program to create Character Array from String Objects


Use the toCharArray() method in Java to create character arrays from string objects. The following is our string.

String str = "This is it!";

Now, let us create character array from the above string.

char[] strArr = str.toCharArray();

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str = "This is it!";
      char[] strArr = str.toCharArray();
      for(char res: strArr) {
         System.out.println(res);
      }
   }
}

Output

T
h
i
s

i
s

i
t
!

Let us see another example in which we are creating string using new operator.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str = new String("This is another string!");
      char[] strArr = str.toCharArray();
      for(char res: strArr) {
         System.out.println(res);
      }
   }
}

Output

T
h
i
s

i
s

a
n
o
t
h
e
r

s
t
r
i
n
g
!

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

204 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements