• Courses
  • Tutorials
  • Jobs
  • Practice
  • Contests
May 25, 2022 |10.7K Views
Java Program to Convert String to an Integer
Description
Discussion

In this video, we will learn about the Java program to Convert String to Integer. In the video java program Given String str containing digits as characters, the task is to convert this given string to integer in Java.

Examples: Input: str = "4567" Output: 4567 Input: str = "223s" Output: 0 Since the String contains other than digits, hence the integer value will be 0.

Algorithm:
Step 1: First we initialize a string s of size m.
Step 2: After that, create a variable of integer type and update the value of the integer variable as the parsed value of string to integer using the method Integer.parseInt.
Step 3: Print the integer variable.

Here we use Integer.parseInt() method for Convert String to Integer and this is the most simple method to convert String to integer. This function parses the string argument as a signed decimal integer.

Syntax for Interger.parseInt(): public static int parseInt(String s) throws NumberFormatException Apart from Interger.parseInt() here we use valueOf() also. The basic difference between parseInt() and valueOf() is that parseInt() parses the string and returns the primitive integer type.

However, valueOf() returns an Integer object.

Note: valueOf() uses parseInt() internally to convert to integer.

Convert String to Integer in Java: https://www.geeksforgeeks.org/how-to-convert-string-to-int-in-java/