Converting a Char to a String in Java – Practical Examples and Best Practices
What You’ll Learn
In this concise guide, we’ll walk through the most common ways to (1) convert a char to a String and (2) convert a String back to a char in Java. These techniques are essential for string manipulation, file I/O, and API integration.
- Converting a
charto aString - Converting a
Stringto achar
Converting a Char to a String
A char in Java is a 16‑bit Unicode scalar value. Internally, a String is just an array of char values, so the conversion is straightforward. Java offers two idiomatic approaches:
Method 1: Character.toString()
public class CharToStringToString {
public static void main(String[] args) {
char myChar = 'g';
String myStr = Character.toString(myChar);
System.out.println("String is: " + myStr);
}
}
Output:
String is: g
Method 2: String.valueOf()
public class CharToStringValueOf {
public static void main(String[] args) {
char myChar = 'g';
String myStr = String.valueOf(myChar);
System.out.println("String is: " + myStr);
}
}
Output:
String is: g
Converting a String to a Char
When you need to work with individual characters of a string, the charAt(int index) method is the go‑to solution. Below is a typical usage pattern that iterates over every character in a string.
public class StringToChar {
public static void main(String[] args) {
String myStr = "Guru99";
int length = myStr.length();
for (int i = 0; i < length; i++) {
char myChar = myStr.charAt(i);
System.out.println("Character at " + i + " Position: " + myChar);
}
}
}
Output:
Character at 0 Position: G Character at 1 Position: u Character at 2 Position: r Character at 3 Position: u Character at 4 Position: 9 Character at 5 Position: 9
Java
- Mastering Java Strings: Creation, Methods, and Best Practices
- Java ArrayList Explained: Usage, Key Methods, and Practical Examples
- Java String length() Method: How to Get a String’s Size (Example)
- Mastering Java String.indexOf(): Locating Substrings & Practical Examples
- Mastering Java's String compareTo() Method: Syntax, Use Cases, and Practical Examples
- Easily Convert Strings to Integers in Java: A Step‑by‑Step Guide
- Mastering Java's split() Method: A Practical Guide with Code Examples
- Reverse a String in Java Using Recursion – Step‑by‑Step Guide
- Java Character Wrapper Class: Mastering Char Objects
- Java 8 Overview: New Functional, Streaming, and Date-Time APIs