Convert String Object To Character Array

This example will show you how to use the java String class toCharArray() method to convert a Java String object to a character array.

1. How To Convert Java String Object To Character Array Example Source Code.

  1. ConvertStringToCharArray.java
    public class ConvertStringToCharArray {
    
    	public static void main(String[] args) {
    		
    		/* Declare and initiate the str object with assigned value. */
    		String str = "Java is a popular programming language.";
    		
    		/* Declare a char array without initial value. */
    		char charArr[];
    		
    		/* Invoke toCharArray() method to convert str to char array. */
    		charArr = str.toCharArray();
    		
    		/* Get char count in the array. */
    		int arrLen = charArr.length;
    		
    		/* Declare a Character object array. */
    		Character chaObjArr[] = new Character[arrLen];
    		
    		/* Loop to print each char in the array in reverse order. */
    		for(int i=arrLen-1;i>=0;i--)
    		{
    			/* Get the char value at the specified index. */
    			char cha = charArr[i];
    			
    			/* Print out the char. */
    			System.out.print(cha + " ");
    			
    			/* Cast the char to upper case Character object and save in chaObjArr. */
    			chaObjArr[i] = Character.toUpperCase(cha);
    		}
    		
    		System.out.println("");
    
    		/* Loop in chaObjArr and print out each upper case character. */
    		for(int i=0;i<arrLen;i++)
    		{
    			/* Get each Character object. */
    			Character chaObj = chaObjArr[i];
    			
    			/* Print it's data as String. */
    			System.out.print(chaObj.toString());
    		}
    		
    	}
    
    }
  2. Below is the output when you run the above java code.
    . e g a u g n a l   g n i m m a r g o r p   r a l u p o p   a   s i   a v a J 
    JAVA IS A POPULAR PROGRAMMING LANGUAGE.
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x