Menu
Topics Index
...
`


Strings > Character Extraction >
Siva Nookala - 04 Apr 2016
The method toCharArray() is used to convert any String into array of characters.

The format of toCharArray is:
char[] toCharArray()
This method will convert the invoking string object into a character array of same length as of the invoking string and returns it.

The following example demonstrates toCharArray:
StringtoCharArray
class ToCharDemo
{
    public static void main(String arg[])
    {
        String one = "Hyderabad";
        char[] char_one = one.toCharArray();
        System.out.println(one);
        for (int i = 0; i < char_one.length; i++)
        {
            System.out.print(char_one[i] + " ");
        }    
    }
}
OUTPUT

Hyderabad
H y d e r a b a d

DESCRIPTION

The first output line is just the display of String one i.e Hyderabad. The method toCharArray() converts the String object one into character array char_one. The for loop shows the display of each character of char_one i.e H y d e r a b a d.

THINGS TO TRY
  • Try this code and see whether it generates a NullPointerException :
    String one = null;<br>
    char[] char_one = one.toCharArray();
  • Also try with empty string.

Dependent Topics : StringBuffer getChars() Method In Java With Example  Java length() Method | length() Method In Java - Strings 

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App