LAST UPDATED: NOVEMBER 24, 2020
Java Character valueOf() Method
Java valueOf()
method is a part of Character
class. This method returns the Character object representing the specified character value.
It must be noted that if a new Character
instance is not required, this method should generally be used in preference to the constructor Character(char)
, as this method is likely to yield significantly better space and time performance by caching frequently requested values.
Syntax:
public static Character valueOf(char c)
Parameters:
The parameter passed is the character value whose Character instance is to be returned.
Returns:
Returns the Character instance of the parameter passed.
Example 1:
Here, the Character instances of the char value passed are returned.
public class StudyTonight
{
public static void main(String[] args)
{
System.out.println("Equivalent Character object Value = " + Character.valueOf('G'));//returns a Character object representing the character specified
System.out.println("Equivalent Character object Value = " + Character.valueOf('m'));//returns a Character object representing the character specified
}
}
Equivalent Character object Value = G
Equivalent Character object Value = m
Example 2:
Here is a user-defined example where anyone using this code can put a value of his choice and get the equivalent output.
import java.util.Scanner;
public class StudyTonight
{
public static void main(String[] args)
{
try
{
System.out.println("Enter the value");
Scanner sc=new Scanner(System.in);
char ch = sc.next().charAt(0);
System.out.println("Equivalent Character object Value = " + Character.valueOf(ch));//returns a Character object representing the character specified
}
catch(Exception e)
{
System.out.println("Invalid input!!");
}
}
}
Enter the value
J
Equivalent Character object Value = J
************************************************
Enter the value
i
Equivalent Character object Value = i
Live Example:
Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.