Java Character valueOf Method

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn about the valueOf() method of the Character class in Java. This method returns the Character object representing the specified character value.

Create a new Java file

Create a new file named CharValueOf.java in the ~/project directory. You can use any text editor to create the file.

touch ~/project/CharValueOf.java

Write the Java code

In this step, add the following code to the CharValueOf.java file.

public class CharValueOf {

    public static void main(String[] args) {
        // Step 3 code goes here
    }

}

Use the valueOf() method

In this step, use the valueOf() method to get the Character object for a specific character, and then print it to the console.

char c = 'A';
Character ch = Character.valueOf(c);
System.out.println("Character object for " + c + " is " + ch);

Use valueOf() with user input

In this step, get a character input from the user, and then use the valueOf() method to get the Character object and print it to the console.

Scanner sc = new Scanner(System.in);
System.out.print("Enter a character: ");
char c = sc.next().charAt(0);
Character ch = Character.valueOf(c);
System.out.println("Character object for " + c + " is " + ch);

Run the code

To compile and run the code, use the following commands.

javac CharValueOf.java
java CharValueOf

Summary

In this lab, you learned about the valueOf() method of the Character class in Java. You learned how to get the Character object for a specific character using valueOf() method and how to use it with user input. You also learned how to modify the code to test different characters.

Other Java Tutorials you may like