Java Character valueOf() Example

Java is an object-oriented language where each real life entity can be referred as an object. Towards this goal, Java comes with java.lang.Integer class to represent primitive data type int as an object, java.net.URL class to represent a simple system address like 127.0.0.1 as an object, java.io.File class to give a hard disk file an object form, java.lang.String class to to represent some name in an object form, java.util.Date to represent system date as an object and finally java.lang.Character class to give data type char, an object form etc.

For example,

char ch = 'A';
Character c1 = new Character(ch);

Wherever, you would like to use char ch as an object in Java coding, use c1. Object c1 practically represents char ch as an object. That is, c1 wraps around ch to give ch an object form. For this reason, Character class is known as wrapper class for primitive data type char.

Following is the signature of Character class as defined in java.lang package.

public final class Character extends Object implements Serializable, Comparable

Character class was introduced in Java API with JDK 1.0, the starting version of Java.

The Character class provides many methods to find for what type the character belongs like lowercase letter or a digit etc. and few methods to convert characters from one type to another like lowercase to uppercase etc.

Following is the method signature as defined Character class

  • public static Character valueOf(char ch): Returns an object of Character representing the char ch. Introduced with JDK 1.5.

With this introduction let us go into an example.

There are two ways to get an object of Character representing a char.

1. Character ch1 = new Character('A');

2. Character ch2 = Character.valueOf('A');

Usage of the second type yields performance; but for both ways are one and same. The parameter for Character constructor is always a single parameter field of type char.

Following example illustrates how to use valueOf(char) method.

public class CharacterFunctionDemo
{
  public static void main(String args[])
  {
    Character ch1 = new Character('A');
    Character ch2 = Character.valueOf('A');

    System.out.println("Printing char A using Character constructor: " + ch1); 
    System.out.println("Printing char A using valueOf() method: " + ch2);
  }
}


Java Character valueOf() Example
Output screenshot on Java Character valueOf() Example

String class also comes with valueO)f() method; would you like to have this example also?.

Leave a Comment

Your email address will not be published.