Java Integer ValueOf String Method

JavaJavaBeginner
Practice Now

Introduction

The valueOf(String s) method is a method of the java.lang package and is a part of the Integer class. It returns an Integer object from the string that is passed as an argument. In this lab, you will learn how to use the valueOf method to return an Integer object for a given string.

Setting Up Your Environment

To set up your environment for this program, you'll need to follow these steps:

  1. Open your terminal
  2. Navigate to the project directory using the following command:
cd ~/project
  1. Create a new Java file using the following command:
touch ValueOf.java
  1. In the text editor that opens, type the following code:
import java.lang.Integer;
import java.util.Scanner;

public class ValueOf {
  public static void main(String[] args) {
    try {
      System.out.println("Enter a string to convert to an Integer: ");
      Scanner sc = new Scanner(System.in);
      String str = sc.next();
      Integer num = Integer.valueOf(str);
      System.out.println("The Integer value is: " + num);
    } catch (NumberFormatException e) {
      System.out.println("Invalid input! Please enter only an integer.");
    }
  }
}
  1. Save the file by pressing Ctrl+O, then Enter. Exit the text editor by pressing Ctrl+X.

Compiling Your Code

Now that you have written the program, you can compile it by running the following command:

javac ValueOf.java

If there are no errors in your code, the compiler will generate a .class file for the program.

Running Your Code

To run the program, use the following command:

java ValueOf

You will see the following prompt:

Enter a string to convert to an Integer:

Enter the string that you want to convert to an integer and press Enter. If the string is a valid integer, you will see its value printed to the console. If it is not a valid integer, you will see an error message.

Testing Your Program

Try running the program with various input values. Here are some examples:

Enter a string to convert to an Integer:
123
The Integer value is: 123
Enter a string to convert to an Integer:
1a2b3c
Invalid input! Please enter only an integer.
Enter a string to convert to an Integer:
-456
The Integer value is: -456

Summary

In this lab, you have learned how to use the valueOf(String s) method of the Integer class to return an Integer object for a given string. You have also learned how to create a Java program that uses this method, compile it, and run it.

Other Java Tutorials you may like