Java Integer parseInt Method

JavaJavaBeginner
Practice Now

Introduction

Java parseInt(String s, int radix) method is used to parse a string value as a signed decimal Integer object in a specified integer radix value, which is part of the Integer class provided by the java.lang package. In this lab, we will learn how to use this method in Java programming.

Write the Java code

Next, we will write the Java code in the newly created file ParseIntMethod.java.

import java.util.Scanner;

public class ParseIntMethod {
   public static void main(String[] args) {
      try {
         System.out.print("Enter the value: ");
         Scanner sc = new Scanner(System.in);
         String s = sc.nextLine();
         System.out.print("Enter the radix: ");
         int radix = sc.nextInt();
         System.out.println("Entered value and Base value is: " + s + " and " + radix);
         System.out.println("Equivalent Integer object is " + Integer.parseInt(s, radix));
      } catch (NumberFormatException e) {
         System.out.println("Invalid Input!!");
      }
   }
}

In the above code, we have created a class named ParseIntMethod that contains the main() method. The program prompts the user to enter a string value and a radix value. Then, it will parse the string value into a signed integer value relative to the radix value that the user has input. Finally, the program will display the equivalent signed integer value as the output. If the user inputs an invalid value, the program will catch the exception and print "Invalid Input!!".

Compile and run the Java program

Next, in the terminal, we need to navigate to the ~/project directory and run the following command to compile the Java program:

javac ParseIntMethod.java

Then, run the Java program using the following command:

java ParseIntMethod

Test the program

The program will ask the user to input the value and the radix value. After inputting the values, the program will parse the string value relative to the radix value and display the equivalent signed integer value. Let's try to enter a value and it's represented radix to test the program.

Enter the value: 5A
Enter the radix: 16
Entered value and Base value is: 5A and 16
Equivalent Integer object is 90

In the above output, the entered string value is "5A", and the radix value is 16. After parsing and conversion, the equivalent signed integer object is 90, which is displayed as the output.

Summary

In this lab, we have learned how to use the Java parseInt(String s, int radix) method to parse a string value into a signed decimal integer object relative to a specified radix value. We also learned how to implement the method in a Java program and how to compile and run the program in the Ubuntu terminal.

Other Java Tutorials you may like