Signup/Sign In

How to convert Java char to String

In Java, we can convert char into a String by using String class. The String class provides valueOf() and toString() methods that return a string as result. Let's see with the examples.

1. By using String.valueOf() Method

The valueOf() method is a part of String class. It is a static method that converts a char into a String value.

Example 1:

Here the char value passed in the method is converted into a String.

public class StudyTonight
{  
	public static void main(String args[])
	{  
		char ch = 'D';  
		String s = String.valueOf(ch); //valueOf() method converts character into String
		System.out.println("The string value is " +s);
	}
}


The string value is D

2. By using Character.toString() method

The toString() method is a part of Character class. It is a static method that can also be used to convert a char to String.

Example 2:

Here, a char value is passed in the method and converted into a String. See the example below.

package com.studytonight;

public class StudyTonight
{  
	public static void main(String args[])
	{  
		char ch = 'M';  
		String s  = Character.toString(ch); 
		System.out.println("The string value is " +s);
	}
}


The string value is M

Example 3:

Here, a char value is passed in the method and converted into a String using concatenation. We used + operator to concatenate char value with an empty string. The + operator returns a string after concatenation.

public class StudyTonight
{  
	public static void main(String args[])
	{  
		char ch = 'D';  
		String s = "" + ch;
		System.out.println("The string is : "+s);
	}
}


The string is : D

Example 4:

Here the char value passed in the method is converted into a String by creating the String instance of the char value.

public class StudyTonight
{  
	public static void main(String args[])
	{  
		char ch = 'D';  
		String s = new String(new char[]{ch});
		System.out.println("The string is : "+s);
	}
}


The string is : D

Example 5:

Here the char value passed in the method is converted into a String using toString().

package com.studytonight;

public class StudyTonight
{  
	public static void main(String args[])
	{  
		char ch = 'D';  
		String s = new Character(ch).toString();
		System.out.println("The string is : "+s);
	}
}


The string is : D



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.