Java Program to Convert String to Character

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

In this example, we use this function, and you can see that it returns 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("Output = " + ch);
	}
}
Output = J

Java Program to Convert String to Character using charAt

If we use this 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("At " + i + " = " + ch);
		}
	}
}
At 0 = J
At 1 = a
At 2 = v
At 3 = a

This Java program allows entering any string and converting 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