Java Program to Convert String to Character

Write a Java program to convert string to character with an example. In Java, the charAt() function returns the first character or single character at the given index position. So, we can use this Java charAt() function to convert the given string into a character. 

In this example, we use this function, and you can see that it is returning the string’s first character.

public class StringToChar {

	public static void main(String[] args) {
		
		String str = "Java";
		
		char ch = str.charAt(0);
		System.out.println("String to Character = " + ch);
	}
}
String to Character = J

If we use this Java charAt function within the for loop or any loop, we can convert the whole string into characters.

public class StringToChar1 {

	public static void main(String[] args) {
		
		String str = "Java";
		
		for(int i = 0; i < str.length(); i++) {
			char ch = str.charAt(i);
			System.out.println("Character at " + i + " Index Position = " + ch);
		}
	}
}
Character at 0 Index Position = J
Character at 1 Index Position = a
Character at 2 Index Position = v
Character at 3 Index Position = a

This Java program allows entering any string and converts it into characters using for loop.

import java.util.Scanner;

public class StringToChar2 {
	private static Scanner sc;

	public static void main(String[] args) {
		String str;
		
		sc= new Scanner(System.in);

		System.out.print("Please Enter any String =  ");
		str = sc.nextLine();
		
		for(int i = 0; i < str.length(); i++) {
			char ch = str.charAt(i);
			System.out.println("Character at " + i + " Index Position = " + ch);
		}
	}
}
Java Program to Convert String to Character 1