Tutorials

Java String Methods


String toCharArray() method


In java, toCharArray( ) method helps in converting the given String into character array.

For example, given String → "Rajneesh"

If you apply method toCharArray() on the above String then this will result in converting it into an array containing characters of the given String. The array will comprise of the characters of the original String.

 

See the diagrammatic representation of applying the toCharArray() on String "Rajneesh"

 

toCharArray Java by tutorialsinhand.com

 

Example on java toCharArray()

Given below is a simple java program to convert a String into character array.

We have used for each loop to iterate over the character array that is formed after applying toCharArray on original String.


public class CharArrayDemo {

         public static void main(String[] args){

                    String str = "Test the code";                               
                    char[] strToChar = str.toCharArray();
                            
                    for(char c : strToChar){
                        System.out.println(c);
                    }

                }

}

OUTPUT:

T
e
s
t
 
t
h
e
 
c
o
d
e
 

Practice programs:

  1. Write a java program to find out the number of spaces in the String "I Love my family" (use of toCharArray() is must)


Please Share this page
Views : 227
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!