×

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

Delete a Cycle from a Linked List in Java

Assume a method detectAndRemoveLoop(), which examines if a given Linked List includes a loop and, if so, eliminates this Loop and returns true. This returns false if the list does...

7 minutes read.

How to take Multiple String Input in Java using Scanner class

Scanner class is a class which takes the multiple input data or the single input data through an objects and methods. The Scanner class will be available in the java.util...

3 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

Swastika Pattern in Java

This part teaches us how to create the Swastika Pattern in Java utilizing user-defined columns and rows as well as stars or other special characters.A Java pattern application that is...

2 minutes read.

Java Thread Lifecycle: States and Stages

Multithreading Multithreading is one of the most important features in object-oriented programming, and this multithreading can be implemented by various object-oriented programming languages like Java, Python, and C++. A multithreaded process...

7 minutes read.

Java String Methods

Java String Methods Java String class is the most important class of the java.lang package. It is used to handle the String related operations. It contains a lot of built-in Java...

2 minutes read.

Functional Interface in Java 8

A brief introduction to Interface in Java: Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or...

11 minutes read.

Tetranacci Number in Java

This article mainly describes tetranacci number identification and the Java Program for Tetranacci numbers. Tetranacci number Tetranacci numbers and Fibonacci numbers are related. The key contrast is that a Tetranacci number depends...

3 minutes read.

Method Overloading In Java

If the same class consists of different methods with the same name and the methods can vary by different number of parameters then it is known as Method Overloading. Method...

2 minutes read.

Longest Arithmetic Progression Sequence in Java

The task is to find the length of the largest sequence in an array to form an arithmetic progression. The array arr[] is given. Longest Arithmetic Progression Sequence in Java Algorithm set...

5 minutes read.

Class memory in Java

Anything specifically defined in the Java code is stored either inside the heap or the stack, which is particularly significant. Stack and heap are the two kinds of memory available...

6 minutes read.

How to Solve the Deprecated Error in Java?

Deprecated Java methods should not be used because they are deprecated (often, there are better, more modern alternatives). API update. Until now, Java has kept everything backward compatible and never...

3 minutes read.

Java Double Keyword

In java primitive data types, we have two different types of data types which are Boolean and floating-point data types.In floating data type again we have four types which are...

3 minutes read.

Java Boyer Moore

A string searching or matching technique called the Boyer-Moore algorithm was created in 1977 by Robert S. Boyer and J. Strother Moore. It is the most popular and effective string-matching...

9 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Difference between JIT and JVM in Java

In this tutorial, we will discuss the difference between JIT (Just In Time Compiler) and JVM (Java Virtual Machine) in Java. Before we move to the differences, let's understand what...

4 minutes read.

Can we override Private Method in Java

In this article we will learn the concept of override, private method in java and we will now whether we can override private method in java or not. Override in Java Any...

3 minutes read.

Blockchain in Java

Blockchain is a continuously expanding ledger that maintains an immutable, secure, and chronological record of all transactions that have ever occurred. It can be utilized to securely transfer money, assets,...

9 minutes read.

Why we use static in Java

Many reserved keywords in Java cannot be used as variable names or identifiers. Java uses static keywords frequently because of its effective memory management system. In most cases, you must...

3 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.