Open In App

How to Convert a String to a Character in Java?

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

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 program to Convert a String
// to a Character using charAt( ) method
import java.io.*;
import java.util.Arrays;
  
// Driver Class
class StringToChar {
      // Main Method
    public static void main(String[] args)
    {
  
        String givenString = "geeksforgeeks";
        // Create a character array to store characters of
        // The given string
        char[] arr = new char[givenString.length()];
  
        // Iterate over the characters of the given string
        for (int i = 0; i < givenString.length(); i++) {
            // Retrieve each character of the given string
            // Using the charAt() method and assign it to
            // The corresponding index of the character
            // Array
            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,

Method 2: Using toCharArray( ) method




// Java program to convert a String to a character using
// toCharArray()
import java.io.*;
import java.util.Arrays;
  
class StringToChar {
    public static void main(String[] args)
    {
        // Defining a string
        String givenString = "geeksforgeeks";
  
        // Converting the string to a char array
        char[] charArray = givenString.toCharArray();
  
        // Printing the char array
        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:


Article Tags :