How to Convert String to Char in Java

Java is an object-oriented programming language with a high level of abstraction. It is a general-purpose programming language designed to allow programmers to write code once and execute anywhere.  This means that compiled Java code can run on any platform that supports Java without requiring recompilation.

Character is a single 16-bit Unicode character is represented by the char data type. It has a value range of ‘/u0000’ (or 0) to ‘/uffff’ (or 65,535 inclusive). The Unicode system’s lowest range is “u0000”. Characters are stored using the char data type.  A string is a collection of characters that may be used as a literal constant or as a variable. A string is a data type that is frequently implemented as an array data structure of bytes (or words) that records a succession of items, most commonly characters. So today with the basic knowledge of Character and Strings let us start with the tutorial on How to Convert String to Char in Java.

 

What’s The Approach?

 

  • Import the “java. util” package to the class.

 

  • Create a Scanner class object.

 

  • Accept the string input from the user.

 

  • Create a char variable to store the characters extracted from the string.

 

  • Use the function “String_variable.toCharArray();”.

 

  • Print the Char datatype array using a for loop.

Also Read: How to convert String to int in Java

 

Java program to Convert String to Char

 

/*
 * TechDecode Tutorials
 * 
 * How to Covert String to Char
 * 
 */
// Import the util package
import java.util.*;
public class String_To_Char
{  
    public static void main(String args[])
    { 
        // creation of Scanner class object
        Scanner sc=new Scanner (System.in);
        System.out.println("Enter the String you want to convert To Char");
        // accpeting user input
        String s=sc.nextLine();
        // converting string to char
        char[] c=s.toCharArray();   
        //printing the char values
        for(int j=0;j<c.length;j++)
        {    
            System.out.println("char at "+j+" index is: "+c[j]);   
        }  
    }
}

Output:-

Leave a Reply

Your email address will not be published. Required fields are marked *