Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java how does one turn a String into a char or a char into a String?

Tags:

java

string

char

Is there a way to turn a char into a String or a String with one letter into a char (like how you can turn an int into a double and a double into an int)? (please link to the relevant documentation if you can).

How do I go about finding something like this that I'm only vaguely aware of in the documentation?

like image 556
David Avatar asked Mar 11 '10 22:03

David


People also ask

Which method will you use to convert string to char?

String str = "Tutorial"; Now, use the toCharArray() method to convert string to char array. char[] ch = str.

How do you create a char in java?

You can create a Character object with the Character constructor: Character ch = new Character('a'); The Java compiler will also create a Character object for you under some circumstances.

What does char () do in java?

The char keyword is a data type that is used to store a single character. A char value must be surrounded by single quotes, like 'A' or 'c'.


2 Answers

char firstLetter = someString.charAt(0); String oneLetter = String.valueOf(someChar); 

You find the documentation by identifying the classes likely to be involved. Here, candidates are java.lang.String and java.lang.Character.

You should start by familiarizing yourself with:

  • Primitive wrappers in java.lang
  • Java Collection framework in java.util

It also helps to get introduced to the API more slowly through tutorials.

  • Manipulating characters in a String
like image 72
polygenelubricants Avatar answered Sep 24 '22 19:09

polygenelubricants


String.valueOf('X') will create you a String "X"

"X".charAt(0) will give you the character 'X'

like image 42
BryanD Avatar answered Sep 25 '22 19:09

BryanD