Converting Between char and Character
Converting between char
and Character
is a common task in Java programming. Here are the different ways to perform this conversion:
Conversion from char
to Character
To convert a char
to a Character
object, you can use the Character.valueOf()
method:
char c = 'A';
Character charObj = Character.valueOf(c);
Alternatively, you can also use the Character
constructor:
char c = 'B';
Character charObj = new Character(c);
Conversion from Character
to char
To convert a Character
object to a char
primitive, you can use the charValue()
method:
Character charObj = 'C';
char c = charObj.charValue();
You can also use the char
cast operator:
Character charObj = 'D';
char c = (char) charObj;
Both of these methods will extract the underlying char
value from the Character
object.
It's important to note that when converting from Character
to char
, you need to ensure that the Character
object is not null
, as this would result in a NullPointerException
. To handle this case, you can use the Character.isPresent()
method to check if the Character
object has a value before performing the conversion.
Character charObj = null;
if (charObj != null) {
char c = charObj.charValue();
} else {
// Handle the case where charObj is null
}
By understanding the differences between char
and Character
, and the various conversion methods, you can effectively work with both primitive and object representations of characters in your Java applications.