"Hi, Amigo! It's me again. I'd like to tell you about another fairly simple wrapper class. Today we'll be talking about Character, the wrapper for char."
"This class is also quite simple."
Code
class Character
{
private final char value;
Character(char value)
{
this.value = value;
}
public char charValue()
{
return value;
}
static final Character cache[] = new Character[127 + 1];
public static Character valueOf(char c)
{
if (c <= 127)
return cache[(int)c];
return new Character(c);
}
public int hashCode()
{
return (int)value;
}
public boolean equals(Object obj)
{
if (obj instanceof Character)
{
return value == ((Character)obj).charValue();
}
return false;
}
}
"It has the following:"
1) A constructor that takes the internal value and a charValue method that returns it.
2) A valueOf method that returns Character objects, but caches objects with values from 0 to 127. Just like Integer, Short, and Byte.
3) hashCode() and equals methods — again, there's nothing surprising here.
"And it has lots of other useful methods (not shown above). I'll list a few for you here:"
Method | Description |
---|---|
|
Is the character a Unicode character? |
|
Is the character a digit? |
|
Is the character a control character? |
|
Is the character a letter? |
|
Is the character a letter or a digit? |
|
Is this a lowercase letter? |
|
Is this an uppercase letter? |
|
Is the character a space or something similar (there are lots of invisible characters)? |
|
Is the character a titlecase character? |
"Thank you, Kim. I think some of these methods will be useful for me."
GO TO FULL VERSION