How to Convert a String to a Character in Java?
Last Updated :
21 Feb, 2024
String and char are fundamental and most commonly used datatypes in Java. A String is not a primitive data type like char. To convert String to char, we have to perform character-based operations or have to process individual characters.
In this article, we will learn how to Convert a String to a Character in Java.
Methods to Convert a String to a Character
- Using charAt( ) method
- Using toCharArray( ) method
Program to Convert a String to a Character in Java
Below are the code implementations of the two methods.
Method 1: Using charAt( ) method
We can convert the String to a character using the charAt( ) method.
Java
import java.io.*;
import java.util.Arrays;
class StringToChar {
public static void main(String[] args)
{
String givenString = "geeksforgeeks" ;
char [] arr = new char [givenString.length()];
for ( int i = 0 ; i < givenString.length(); i++) {
arr[i] = givenString.charAt(i);
}
System.out.println(Arrays.toString(arr));
}
}
|
Output
[g, e, e, k, s, f, o, r, g, e, e, k, s]
Explanation of the above Program:
In the above program,
- First, we have imported all the required packages like java.io for input output operations and java.util.Arrays for using arrays.
- Now in main method we initialize variable named givenString of type String with the value.
- Now we define a character array of length same as givenString and reference it by the reference variable arr.
- Start a loop to iterate over each character of the given string.
- The charAt( ) method retrieves the character at index i from the givenString and store it at index i at of array arr.
- Now we use Arrays.toString() method to print the array of the characters retrieved from givenString.
Method 2: Using toCharArray( ) method
Java
import java.io.*;
import java.util.Arrays;
class StringToChar {
public static void main(String[] args)
{
String givenString = "geeksforgeeks" ;
char [] charArray = givenString.toCharArray();
System.out.println(Arrays.toString(charArray));
}
}
|
Output
[g, e, e, k, s, f, o, r, g, e, e, k, s]
Explanation of the above Program:
- First, we import all the required packages like java.io for input output operations and java.util.Arrays for using arrays.
- Now, in the main method we initialize variable named givenString of type String with the value.
- Now we define a character array and assign it to reference variable charArray.
- After that we have used toCharArray( ) method to convert givenString into a character array.
- Then it prints charArray by using toString( ) method.
Share your thoughts in the comments
Please Login to comment...