Java Program to Convert String to char

In the previous article we have discussed Java Program to Convert String to Date

In this article we will see how to convert a String type to char type.

Program to Convert String to char

Let’s see some example first of both the types.

Example-1: String type

String a = "BtechGeeks";
String b= "B";
Example-2: char type

String a = 88;
String b= 'B';

Before going into the program , let’s see some examples of string type and char type.

Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

Method 1 : Java Program to Convert String to char Using for Loop:

We can divide the string to character  by using  for loop let’s see how it works.

Approach :

  1. Take a string value and store it in a string  variable input1
  2. Iterate a for loop from 0 to inputted string length .
  3. For each Iteration display the index value .

Program :

import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        // creating scanner object
        Scanner sc = new Scanner(System.in);
        // input a string through scanner class
        System.out.print("Enter a string : ");
        String input1=sc.next();
        // converting to character
        System.out.println("Converted Character are :");
        for(int i=0; i<input1.length();i++)
        System.out.println(input1.charAt(i));
    }
}
OUTPUT:

Enter a string : BtechGeeks
Converted Character are :
B
t
e
c
h
G
e
e
k
s

Method 2 : Java Program to Convert String to char Using toCharArray() method:

We can convert  string to character  by using toCharArray() method let’s see how it works.

toCharArray() method is a method of String class which  converts  string into character array.

Approach :

  1. Take a string value and store it in a string  variable input1
  2. Iterate a for loop from 0 to inputted string length.
  3. For each Iteration display the index value .

Program :

import java.util.Scanner;

public class Main

{
    public static void main(String[] args)
    {
        // creating scanner object
        Scanner sc = new Scanner(System.in);
        // input a string through scanner class
        System.out.print("Enter a string : ");
        String input1=sc.next();
        // converting to character
        char[] output=input1.toCharArray();
        System.out.println("Converted Character are :");
        for(int i=0; i<output.length ;i++)
        System.out.println(output[i] );
    }
}
OUTPUT: 

Enter a string : BtechGeeks
 Converted Character are : 
B 
t 
e 
c 
h 
G
e 
e 
k 
s

Are you a job seeker and trying to find simple java programs for Interview? This would be the right
choice for you, just tap on the link and start preparing the java programs covered to crack the
interview.

Related Java Program:

Leave a Comment