Java Program to create Character Array from String Objects

Java 8Object Oriented ProgrammingProgramming

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
!
raja
Published on 13-Dec-2018 10:16:10
Advertisements