×

How to Convert String to char in Java

How to Convert String to char in Java

There are two methods to convert String to char are:

  • Using charAt() method
  • Using tocharArray() method

Using charAt() method

This is the method of String class that belongs to java.lang package. It returns the character at the specified index value. The value of the index lies between 0 to length()-1 (where length() is the method of String class which returns the number of character in the string ). The signature of the method is given below:

public char charAt(int index)

Example

In the following example, str is a variable of String type that contains "Computer ".  charAt() is a method of String classthat returns the character at the specified index. ch is a variable of type char that stores the returned character. The println statement prints the character return by the method.

public class StringtoCharExample
{
public static void main(String args[])
{
String str="Computer";
char ch=str.charAt(2); //accessing character at index 2 i.e. m
System.out.println("The second character of the String is:"+ch);
}
}

Output

The second character of the String is: m

If the index value is higher than string length or negative, then it throws IndexOutOfBoundsException. In the above example, string length is 7. If we specify the index value negative or higher, then it throws the IndexOutOfBoundsException.

char ch=str.charAt(9); //higher value
char ch=str.charAt(-4); //negative value

Let’s see another example that returns each character.

public class StringtoCharExample1
{
public static void main(String args[])
{
String str="computer";
for(int i=0;i<str.length();i++)
{
char ch=str.charAt(i);
System.out.println("The character " +ch+  is at index: "+i);
}
}
}

Output

The character c is at index: 0
The character o is at index: 1
The character m is at index: 2
The character p is at index: 3
The character u is at index: 4
The character t is at index: 5
The character e is at index: 6
The character r is at index: 7

Using charArray() method

The tocharArray() method converts the String into the character array. It is a predefined method of String class that belongs to java.lang package. It returns the character array, which makes the String. If you want to get all character at a time, you can use a loop.

Example

In this example,”moon” is a string which we want to convert into the character array. char[] is an array that stores the array of characters. tocharArray() is a method that converts String to a character array.

In for loop, we have taken a variable i of type int that represents the index value of character. The variable i initialized with 0 because array index starts from 0. The test condition i<ch.length compares the value of i with the size of the array. i++ increments the value of i on each iteration until the test condition become false.

The println statement prints the character and its index value.

public class StringtoCharExample2
{ 
public static void main(String args[])
{ 
String str="moon";    
char[] ch=str.toCharArray();    
for(int i=0;i<ch.length;i++)
{    
System.out.println("The character " +ch[i]+" is at index: "+i);   
} 
}
}

Output

The character m is at index: 0
The character o is at index: 1
The character o is at index: 2
The character n is at index: 3

Remember

There is a slight difference between length() and length.

  • length() is a method of  the String class that returns the number of characters in the string. The length() method can be used only with strings not with arrays.
  • The length is the property of array that determines the size of array. length can be used only with arrays not with strings.

Related Topics

Dangling Else problem in Java

A language interpretation uncertainty is the hanging other issue. The following two types of condition executed code are both possible in programming: 1. if-then-else form 2. if-then form When dealing with the nested...

3 minutes read.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data...

4 minutes read.

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples. Introduction In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are...

3 minutes read.

Structure of Java Program

Java is well-known as an object-oriented, secure, and platform-independent programming language. The Java programming language allows us to construct a wide variety of programs. Therefore, it is essential to fully...

6 minutes read.

XOR of Array Elements Except Itself in Java

A lot of the biggest IT organisations, including The Google, Amazon, TCS, and The Accenture, etc., question about this issue in their interview processes. By addressing the issue, one hopes to assess...

5 minutes read.

Add numbers represented by Linked Lists in Java

For calculating the sum of the two numbers that are represented by a linked list, and then store the result in a new linked list. A linked list's head node...

7 minutes read.

Decagonal Numbers in Java

This section explains what is a decagonal number and how to write Java programmes that compute decagonal numbers. Both academics and Java programmer interviews regularly question about the Decagonal number...

3 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

Java Switch Keyword

In this article we are going to learn the concept of a java switch keyword. Generally, java case keyword is used with the switch statements or keyword.Switch keyword is implemented in...

3 minutes read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 minutes read.

Use Of Adapter class in Java

An adapter class in Java enables listener interfaces to be implemented by default. The Delegation Event Model is where the idea of listener interfaces first appeared. It is one of...

3 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

Java Command not found

Java Command not found error is displayed if Java is not installed on the computer or if the command prompt cannot find Java.exe to run the program. Our Java software...

3 minutes read.

Maximizing Profit in Stock Buy Sell in Java

In this tutorial, we will deal with a popular problem, a favourite of interviewers. The problem is named as Maximising profit in stock Buy Sell. we will see certain approaches...

6 minutes read.

Practical Number in Java

In this tutorial, we will understand what is meant by practical numbers. We will understand it throughthe aid of examples and implementation in a java programming language. The practical numbers...

5 minutes read.

Mutable and Immutable in Java

Java is a programming language in which everything is treated as an object. Its procedures and functions are centred around objects because it is an object-oriented programming language. Mutable and...

6 minutes read.

Block Swap Algorithm for array rotation in Java

An array and r, the rotation factor by which the array must be rotated, are both provided to us. We must then return the rotated array. A well-known and popular method is...

4 minutes read.

Special Operators in Java

An operator in Java is a special symbol. It is used to perform operations on two or more variables.  We all know basic operations in Java. There are 8 types...

5 minutes read.

Java Boolean compare() method

The compare() method of Java Boolean class compares the specified Boolean values and returns a positive 1 or negative 1 or zero integer value based on the result. Syntax public static int...

2 minutes read.