String to char array java – convert string to char

Filed Under: Java

Sometimes we have to convert String to the character array in java programs or convert a string to char from specific index.

String to char Java

string to char java, string to char array
String class has three methods related to char. Let’s look at them before we look at a java program to convert string to char array.

  1. char[] toCharArray(): This method converts string to character array. The char array size is same as the length of the string.
  2. char charAt(int index): This method returns character at specific index of string. This method throws StringIndexOutOfBoundsException if the index argument value is negative or greater than the length of the string.
  3. getChars(int srcBegin, int srcEnd, char dst[], int dstBegin): This is a very useful method when you want to convert part of string to character array. First two parameters define the start and end index of the string; the last character to be copied is at index srcEnd-1. The characters are copied into the char array starting at index dstBegin and ending at dstBegin + (srcEnd-srcBegin) – 1.

Let’s look at a simple string to char array java program example.


package com.journaldev.string;

public class StringToCharJava {

	public static void main(String[] args) {
		String str = "journaldev";
		
		//string to char array
		char[] chars = str.toCharArray();
		System.out.println(chars.length);
		
		//char at specific index
		char c = str.charAt(2);
		System.out.println(c);
		
		//Copy string characters to char array
		char[] chars1 = new char[7];
		str.getChars(0, 7, chars1, 0);
		System.out.println(chars1);
		
	}

}

In above program, toCharArray and charAt usage is very simple and clear.

In getChars example, first 7 characters of str will be copied to chars1 starting from its index 0.

That’s all for converting string to char array and string to char java program.

Reference: API Doc

Comments

  1. M.king dashti says:

    what are the member of class ?
    Is methods and data variable are the member of a class?

  2. Mahesh says:

    If a String value is “10”, toCharArray returns value 01 instead of the 10…any reason for this?

    1. Pankaj says:

      Can you share your code? Here it is from jshell and it looks perfect.

      jshell> String s = "10";
      s ==> "10"
      
      jshell> s.toCharArray();
      $2 ==> char[2] { '1', '0' }
      
  3. Victr Yao says:


    //Copy string characters to char array

    str.getChars(chars1, 0);

    This overloaded method might just work as well?

  4. JeThou says:

    Does the last of character array is a null or not?

  5. Naresh says:

    I just looked the String interview questions, I am getting soo interesting to study the hole tutorial. Its Nice.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages