Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

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.

  1. Converting a char to a String
  2. Converting a String to a char

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

  1. Mastering Java Strings: Creation, Methods, and Best Practices
  2. Java ArrayList Explained: Usage, Key Methods, and Practical Examples
  3. Java String length() Method: How to Get a String’s Size (Example)
  4. Mastering Java String.indexOf(): Locating Substrings & Practical Examples
  5. Mastering Java's String compareTo() Method: Syntax, Use Cases, and Practical Examples
  6. Easily Convert Strings to Integers in Java: A Step‑by‑Step Guide
  7. Mastering Java's split() Method: A Practical Guide with Code Examples
  8. Reverse a String in Java Using Recursion – Step‑by‑Step Guide
  9. Java Character Wrapper Class: Mastering Char Objects
  10. Java 8 Overview: New Functional, Streaming, and Date-Time APIs