Java char conversion
In this chapter you will learn:
- How to get char value from Character object
- How to get the numeric value for a char
- How to convert character to String
- How to convert int value to char value
Get char value from Character object
char charValue()
returns the value of this Character object.
public class Main{
public static void main(String[] argv){
System.out.println(new Character('a').charValue());
}
}
The output:
Get the numeric value for a char
static int getNumericValue(char ch)
returns the int
value that the specified Unicode character represents.
public class Main {
public static void main(String[] argv) {
Character character1 = new Character('a');
Character character2 = new Character('b');
System.out.println(character1.toString());
/*j a v a 2 s .c om*/
System.out.println(Character.getNumericValue(character2));
}
}
The output:
Convert character to String
The following methods convert char type to string.
static String toString(char c)
returns a String object representing the specified char.String toString()
returns a String object representing this Character's value.
public class Main {
public static void main(String[] argv) {
Character character1 = new Character('a');
Character character2 = new Character('b');
System.out.println(character1.toString());
//from java 2 s . co m
System.out.println(Character.toString(character2));
}
}
The output:
Convert int value to char value
The following code displays printable Characters.
public class Main {
public static void main(String[] args) {
// j a va 2 s . c om
for (int i = 32; i < 127; i++) {
System.out.write(i);
// break line after every eight characters.
if (i % 8 == 7)
System.out.write('\n');
else
System.out.write('\t');
}
System.out.write('\n');
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Primitive Data Types