Convert String to Char and Char Array in Java

This article will explore how to convert a string into a single character and an array of characters in Java. I will also take the time to explain what strings, characters, and arrays are for those who may not be familiar.

Post On:String to Char and Char Array in Java
Post Type:Java Tutorials
Published On:www.softwaretestingo.com
Applicable For:Freshers & Experience
Get Updates:SoftwareTestingo Telegram Group

What is a Character in Java?

Characters are the most primitive data type. A character is a single entity enclosed inside single quotation marks. It can be anything from a letter, a digit, a punctuation mark, or even a space!

For Example:

char var1 = 'a';
char var2 = '2';
char var3 = '!';
char var4 = ' ';

What is a String in Java?

Strings are one of the objects (reference type) in programming – they’re used to represent text. A string is simply a series of characters, and you can create them by enclosing their content in double quotation marks.

For example:

String vowels = "Software Testingo";

What is an Array in Java?

ArrayArrays are a fundamental data structure that can store a fixed number of elements of the same data type in Java. They’re simple and extremely versatile, making them one of Java’s most popular data structures.

char[] chararray= {'S', 'o', 'f', 't', 'w','a', 'r', 'e'};

Java Strings and Chars

If you’re working with text-based data in Java, you can use two data types that can be used to store text-based data. The first is called a string, which stores a sequence of one or more characters. The second is called char, and it stores an individual character.

For example, If you want to store a student’s name in a fifth-grade math class, you would store it as a string because it contains multiple characters. But if you only wanted to store the first letter of the student’s name, you would use a char data type.

When working with individual characters, the char data type is more efficient than the String class. This is because the String class contains a lot of additional string-based methods, which are unnecessary when only dealing with one character.

Great! Now that we understand the strings, characters, and arrays, let’s move on to the next topic.

Let’s Convert a String to a Character

There are different ways available in Java to convert String to Char. Here are some ways you can convert a string to a character array:

  • Using String.charAt() method
  • Using String.toCharArray() method
  • Using String.codePointAt() method
  • Using String.getChars() method

We will share the different ways with the examples So that it will be easy for you to understand the topic well.

String to Char Using the charAt() method

We can convert a string to a char in Java using the charAt() method of the String class. The charAt() method returns one character at a specified index. The signature of the charAt() method is given below:

public char charAt(int index);
Program: Write a Java Program to Print the First Character Of a String.
package com.softwaretestingo.string;
public class StringToCharExample1 
{
	public static void main(String[] args) 
	{
		String s="Softwaretestingo";  
		char c=s.charAt(0);  
		
		System.out.println("Original String is : "+s);
		System.out.println("1st character is: "+c);  
	}
}

Output:

Original String is : Softwaretestingo
1st character is: S

String to Char Using toCharArray() method

A helpful way to get the character at a specific index in a string is to convert the string into a character array using String.toCharArray().

Program: Write a Java Program to Convert a String to a Character Array.
package com.softwaretestingo.string;
import java.util.Arrays;
public class StringToCharExample2 
{
	public static void main(String[] args) 
	{
		String str="Softwaretestingo";  
		
		// create an array of characters 
		char[] strArray = str.toCharArray();

		// print Array
		System.out.println(Arrays.toString(strArray));
	}
}

Output:

[S, o, f, t, w, a, r, e, t, e, s, t, i, n, g, o]

From the above array, if you want to retrieve a specific character, then we can retrieve the below also:

package com.softwaretestingo.string;
public class StringToCharExample5 
{
	public static void main(String[] args) 
	{
		String str="Softwaretestingo";  
		
		char strChar = str.toCharArray()[0];
		System.out.println("1st character is: "+strChar);  
	}
}

Output:

1st character is: S

String to Char Using codePointAt() method

You can also use the String.codePointAt() method to find the code point value of the character present at a specified index.

Program: Write a Java Program to Retrieve a Character Using the codePointAt() method
package com.softwaretestingo.string;
public class StringToCharExample4 
{
	public static void main(String[] args) 
	{
		String s="Softwaretestingo";  
		
		//The codePointAt return the unicode of the character thats 
		//why we have done the type casting
		char c=(char) s.codePointAt(0);  
		System.out.println("1st character is: "+c);  
	}
}

Output:

1st character is: S

This method is useful for iterating over the code points in a string. It can be used like this:

The String class has a codePointBefore() method that returns the codepoint value before the given index. This is similar to the codePointAt() method, which returns the codepoint value at that index.

package com.SoftwareTestingO.Strings;
public class StringToCharExample7 
{
	public static void main(String[] args) 
	{
		String str="Softwaretestingo";  

		char strChar = (char) str.codePointBefore(1);
		System.out.println("1st character is: "+strChar);
	}
}

String to Char Using getChars() method

The getChars() method is useful when copying characters from a string to a character array. This method copies the characters from the specified start index (inclusive) to the specified end index (exclusive) into the destination character array. The method syntax is:

public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)

Let’s understand the significance of each of the method arguments.

  1. srcBegin: index from where the characters will be copied.
  2. srcEnd: index at which copying will stop. The last index to be copied will be srcEnd-1.
  3. dst: The destination character array. It should be initialized before calling this method.
  4. dstBegin: The start index in the destination array.
package com.softwaretestingo.string;
import java.util.Arrays;
public class StringToCharExample6 
{
	public static void main(String[] args) 
	{
		String str="Welcome to Softwaretestingo Blog";  

		//Destination Array Size is 16
		char[] substringChars = new char[16];

		//We are copied from 11-27 and store in Destination array from index 0 
		str.getChars(11, 27, substringChars, 0);
		System.out.println(Arrays.toString(substringChars)); 
	}
}

Output:

[S, o, f, t, w, a, r, e, t, e, s, t, i, n, g, o]

Note: If the destination array size is smaller than the required size, we will get the StringIndexOutOfBoundsException exception.

Conclusion:

You know how to convert strings to char arrays in Java; try it yourself! If you still have any doubts or questions, comment in the comment section, and we will try to help you ASAP.

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment