Convert String to Numeric Primitive Type Using Integer.valueOf in Java



This article will teach us to convert a string into a numeric primitive type using Integer.valueOf() in Java. By the end, you'll see how this method takes a string of numbers and transforms it into an integer type, making it usable for arithmetic operations or any other number-based logic.

Problem Statement

Write a Java program to convert a numeric string to an integer using the Integer.valueOf() method and display the result. Below is a demostration of the same ?

Input

str = "989"

Output

989

Steps to convert a string into a numeric primitive type

Following are the steps to convert a string into a numeric primitive type ?

  • First, we will create a class named Demo.
  • Inside the main method, define a string variable, say str, and assign it a numeric value in quotes (e.g., "989").
  • Use Integer.valueOf(str) to convert the string into an integer and print the result.

Java program to convert a string into a numeric primitive type

Let us see the complete example of converting a string to an Integer primitive type ?

public class Demo {
    public static void main(String[] args) {
       String str = "989";
       System.out.println(Integer.valueOf(str));
    }
}

Output

989

Code explanation

The Integer.valueOf() method is used in Java to convert a string into a numeric primitive type.

Let's say the following is our string.

String str = "989";

To convert it into a primitive Integer type, use an Integer.valueOf()

Integer.valueOf(str)
Updated on: 2024-11-13T19:19:45+05:30

719 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements