Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Converting a char to a string

Tags:

java

I have just done this in eclipse:

String firstInput = removeSpaces(myIn.readLine());
String first = new String(firstInput.charAt(0));

However, eclipse complains that:

The constructor String(char) is undefined

How do I convert a char to a string then??

Thanks

EDIT

I tried the substring method but it didn't work for some reason but gandalf's way works for me just fine! Very straightforward!

like image 869
Abs Avatar asked Dec 01 '09 22:12

Abs


People also ask

Can you convert char to string?

You can use String(char[] value) constructor to convert char array to string. This is the recommended way.

How do you replace a single character in a string in Java?

String are immutable in Java. You can't change them. You need to create a new string with the character replaced.

Can I convert to string Java?

Java Convert Int to String Using the ToString Method For example, the Integer class in Java has a static function named toString() that changes a given integer into a string. Let's look at the syntax for that next. Integer. toString(Variable/Number);

How do you store characters in a string?

create a char array, set each of its elements, and then create a String from this char array (that's what would look the most like what you're trying to do); use a StringBuilder, append every character, then transform it into a String.


3 Answers

Easiest way?

String x = 'c'+"";

or of course

String.valueOf('c');
like image 72
Gandalf Avatar answered Sep 19 '22 07:09

Gandalf


Instead of...

String first = new String(firstInput.charAt(0));

you could use...

String first = firstInput.substring(0,1);

substring(begin,end) gives you a segment of a string - in this case, 1 character.

like image 23
Amber Avatar answered Sep 21 '22 07:09

Amber


String x = String.valueOf('c');`

That's the most straight forward way.

like image 30
haffax Avatar answered Sep 19 '22 07:09

haffax