How to Convert Char to String in Java (Examples)

โšก Smart Summary

Converting a char to a String in Java takes a single call to String.valueOf(myChar) or Character.toString(myChar). Moving in the reverse direction uses charAt(index), which pulls one character out of a String by its position.

  • ๐Ÿ”˜ String.valueOf: String.valueOf(myChar) returns a one-character String and states the intent of the conversion most clearly.
  • โ˜‘๏ธ Character.toString: Character.toString(myChar) does the same job and, since Java 9, simply delegates to String.valueOf.
  • โœ… charAt: charAt(index) returns the char at a zero-based position and throws StringIndexOutOfBoundsException outside the valid range.
  • ๐Ÿงช char arrays: toCharArray() splits a String into a char array, and new String(chars) rebuilds the text from that array.
  • ๐Ÿ› ๏ธ No casting: A String can never be cast to a char, because a String is an object rather than a related primitive type.
  • ๐Ÿ“Œ Unicode limit: A char holds one 16-bit UTF-16 code unit, so an emoji needs two chars or Character.toString(codePoint).

Java code converting a char to a String and a String back to a char

In this tutorial, we will study two short programs that move a value between the two ways Java stores text:

  1. Convert a char to a String
  2. Convert a String to a char

The two types are not interchangeable. A char is a primitive that holds exactly one 16-bit UTF-16 code unit, written in single quotes as ‘g’. A String is an object that holds a sequence of those code units, written in double quotes as “Guru99”. Because one is a primitive and the other an object, no cast can bridge them โ€” a library method has to do the work, and Java supplies one for each direction.

Convert Char To String

There are multiple ways to convert a char to a String in Java. Internally a Java String stores its text as an array of code units, which is why a single char slots into one so easily. A char is a 16-bit unsigned data type, two bytes wide, holding values from 0 to 65,535.

We can convert a char to a String using 2 methods โ€” the static toString() method on the Character class, and the static valueOf() method on the String class. Both return a brand-new String one character long, and the two programs below print the same result.

Method 1: Using toString() method

The program below stores the letter g in a char variable and passes it to Character.toString(), which returns that single character as a String. The code is editable, so change the letter and run it again to watch the output follow.

public class CharToString_toString {
  public static void main(String[] args) {
    //input character variable 
    char myChar = 'g';
    //Using toString() method
    //toString method take character parameter and convert string.
    String myStr = Character.toString(myChar);
    //print string value
    System.out.println("String is: " + myStr);
  }
} 

Expected Output :

String is: g

Method 2: Using valueOf() method

The second program swaps in String.valueOf(myChar) and changes nothing else. Since Java 9 the two calls are the same operation: Character.toString(char) is implemented as a call to String.valueOf(char), so neither one is measurably faster than the other.

public class CharToString_valueOf {
  public static void main(String[] args) {
    char myChar = 'g';
    //valueOf method take character parameter and convert string.
    String myStr = String.valueOf(myChar);
    ////print string value
    System.out.println("String is: " + myStr);
  }
}

Expected Output :

String is: g

Other Ways to Convert a char to a String

Four further routes turn up in older code and in interview questions. They all work, but none of them reads as plainly as the two methods above, and two of them allocate more than they need to.

public class CharToStringMore {
  public static void main(String[] args) {
    char myChar = 'g';

    // 1. concatenation with an empty literal
    String byConcat = myChar + "";

    // 2. the Character wrapper instance method
    String byWrapper = Character.valueOf(myChar).toString();

    // 3. a one-element array of code units
    String byArray = new String(new char[]{myChar});

    // 4. the format() helper with the %c conversion
    String byFormat = String.format("%c", myChar);

    System.out.println(byConcat + byWrapper + byArray + byFormat);
  }
}

Expected Output:

gggg

The table sets out when each route is worth using.

Method Example Notes
String.valueOf(char) String.valueOf(myChar) Recommended. One call, no extra object beyond the returned String.
Character.toString(char) Character.toString(myChar) Equally good. Available since Java 1.4 and delegates to String.valueOf since Java 9.
Concatenation myChar + “” Works, and on Java 9 and later it compiles to an invokedynamic call rather than a StringBuilder, so the old warning that it is slow no longer holds. It still hides the intent.
Character wrapper Character.valueOf(myChar).toString() Boxes the char first. Use Character.valueOf, not the new Character(char) constructor, which has been deprecated for removal since Java 9.
char array new String(new char[]{myChar}) Allocates an array and copies it. Reserve it for the case where you already hold a char array.
String.format String.format(“%c”, myChar) By far the slowest, because the format string is parsed at run time. Useful only when the character is part of a larger template.

With both directions of the single-character conversion covered, the reverse operation is next.

Convert String to char

We can convert a String to char using charAt() method of String class. The method takes a zero-based index and returns the char sitting at that position, so reading every character means looping from 0 up to length() minus one. Asking for an index below 0 or at length() and above throws StringIndexOutOfBoundsException.

The program below walks the String Guru99 one position at a time and prints each character with its index.

//Convert String to Character using string method 
package com.guru99;
 
public class StringToChar {
 
	public static void main(String[] args) 
	{
		//input String 
	      String myStr = "Guru99";
	      
	      //find string length using length method.
	      int stringLength =myStr.length();
	      
	      //for loop start 0 to total length
	      for(int i=0; i < stringLength;i++)
	      {
	    	  //chatAt method find Position and convert to character.  
	        char myChar = myStr.charAt(i);
	        
	        //print string to character
	        System.out.println("Character at "+i+" Position: "+myChar);
	      }
 
	}
 
}

Expected 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

Note that a String cannot simply be cast: char c = (char) myStr; does not compile, because a String is an object and a char is a primitive. For a String already known to hold exactly one character, charAt(0) is the whole answer.

Convert a String to a char Array and Back

When every character is needed at once rather than one index at a time, toCharArray() hands back a fresh char array. Turning that array back into text is the job of the String(char[]) constructor or String.valueOf(char[]), and both copy the array defensively, so later edits to the array do not alter the String.

public class StringCharArray {
  public static void main(String[] args) {
    String myStr = "Guru99";

    // the text split into its array of code units
    char[] chars = myStr.toCharArray();
    System.out.println(chars.length);
    System.out.println(chars[0]);

    // the array turned back into text
    System.out.println(new String(chars));
    System.out.println(String.valueOf(chars));

    // one range copied into an array you already own
    char[] part = new char[4];
    myStr.getChars(0, 4, part, 0);
    System.out.println(new String(part));
  }
}

Expected Output:

6
G
Guru99
Guru99
Guru

A fourth method, getChars(srcBegin, srcEnd, dst, dstBegin), copies a range into an array you already own instead of allocating a new one. The end index is exclusive, which is why getChars(0, 4, part, 0) yields Guru rather than Guru9. Out-of-range bounds throw IndexOutOfBoundsException.

The three approaches differ mainly in what they allocate, as summarised below.

Task Call What it allocates
String to char array myStr.toCharArray() A new array; safe on an empty String, where it returns a zero-length array.
char array to String new String(chars) or String.valueOf(chars) A new String plus an internal copy of the array.
Range into an existing array myStr.getChars(0, 4, part, 0) Nothing new; it writes into the array you supply.

Common Errors When Converting char and String in Java

Most of the trouble in these conversions comes from six recurring mistakes rather than from the methods themselves. The table pairs each one with the fix.

Problem Cause Fix
incompatible types: String cannot be converted to char An attempt to cast, such as char c = (char) myStr; Call myStr.charAt(0) instead. There is no cast between an object and a primitive.
StringIndexOutOfBoundsException charAt() called with a negative index, or with length() on an empty String Guard with isEmpty() or compare the index against length() before reading.
String.valueOf(null) throws NullPointerException The bare null matches the char[] overload, which is the most specific one Write String.valueOf((Object) null) when the literal text null is what you want.
Character.toString(65) returns A, not 65 Java 11 added a Character.toString(int) overload that reads its argument as a Unicode code point Use String.valueOf(65) or Integer.toString(65) for the digits 65.
An emoji prints as two garbled symbols Characters above U+FFFF occupy two chars, a high surrogate followed by a low surrogate Read the value with codePointAt(0), then rebuild it with Character.toString(codePoint) on Java 11 and later.
Deprecation warning on new Character(myChar) The Character(char) constructor has been deprecated since Java 9 and marked for removal Use Character.valueOf(myChar), or let autoboxing supply the wrapper.

The same String class supports plenty of neighbouring exercises: reversing a string with recursion, comparing two strings, and printing formatted output.

FAQs

A char is a primitive holding one 16-bit UTF-16 code unit, written in single quotes. A String is an object holding a sequence of those units, written in double quotes, and it carries methods such as length() and charAt() that a primitive cannot.

No. Since Java 9, Character.toString(char) is implemented as a call to String.valueOf(char), so the two run the same code. Pick whichever reads better where you are working; String.format(“%c”, c) is the only route that is genuinely slow.

A char stores one 16-bit code unit, and emoji sit above U+FFFF. Java splits them into a surrogate pair, so they occupy two chars. Read the code point with codePointAt() and rebuild the text with Character.toChars() or Character.toString(codePoint).

The String A. Java 11 added an int overload that reads its argument as a Unicode code point, and 65 is the code point for A. String.valueOf(65) returns the digits 65 instead, which makes the two calls easy to confuse.

Concatenate it with the plus operator, or call append() on a StringBuilder when the addition happens inside a loop. A Java String is immutable, so every concatenation allocates a new object rather than extending the old one.

Not since Java 9. Compact strings replaced the internal char array with a byte array plus a coder flag, so pure Latin-1 text uses one byte per character. Nothing in the public API changed, and charAt() still returns a char.

Machine-learning static analysers flag suspicious conversions that a compiler accepts, such as an unguarded charAt() call or a String.valueOf(null) that resolves to the char array overload. They rank findings by likelihood, which cuts the noise of a plain rule-based scan.

GitHub Copilot reliably produces String.valueOf() and charAt() one-liners, but it also reproduces dated advice from its training data, such as the deprecated new Character(c) constructor. Compile every suggestion and read the deprecation warnings.

Summarize this post with: