Java – 1 – Character.valueOf()

Character.valueOf(char c)


  • Check if the character is less than 127
  • Return the cache value from the private CharacterCache class
  • Otherwise return the new Character
public static Character valueOf(char c) {
    if(c <= 127) { // must cache
        return CharacterCache.cache[(int)c];
        return new Character(c);

CharacterCache class

  • This class has a cache array of size  127 + 1
  • Keep adding the characters from 0 to 127 (‘\u0000‘ to ‘\u007F‘)
  • Next time when the valueOf method is called on Character then we will be returning from the cache
private static class CharacterCache {
    private CharacterCache(){}

static final Character cache[] = new Character[127 + 1];

 static {
        for(int i = 0; i < cache.length; i++)
                 cache[i] = new Character((char)i);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: