How to convert String to int in Java
From our elementary school days, most of us are familiar with the concept of an integer. It’s a number with no fractional portion. In other words, integers are comparable to whole numbers, except they also include negative values. As a result, non-decimal numbers can be both positive and negative. It’s a memory place (or locations) that stores non-decimal or non-fractional positive or negative numbers. The keyword ‘int’ denotes an integer type, which describes the memory required to store the data. As well as having limitations on how it can be used, an integer cannot store fractional numbers. Strings in Java are maintained by a character array. Strings are immutable since arrays are immutable (they cannot be expanded). Each time you make an update to a String, a new String is constructed. So today let us start with How to convert String to Int in Java
What’s The Approach?
- Import the
java.util
package into the class.
- Now within the main method create a new object of
Scanner
class, for exampleScanner sc=new Scanner(System.in);
- Use the
Scanner
class to get the input from the user.
- Apply the
try
andcatch
to prevent unwanted errors from the user.
- We will implement the
Integer.parseInt(String_name)
to convert the string to an integer type
Also Read: Implement Binary Insertion Sort using Java
Java Program to convert String to Int in Java
/* * TechDecode Tutorials * * How to Covert String to Integer * */ import java.util.*; public class String_to_Int { public static void main(String args[]) { // Creating an object of Scanner class Scanner sc=new Scanner (System.in); // taking imput from the user System.out.print("Please Enter the String that is to be converted to interger: "); String s=sc.nextLine(); //using try and catch to prevent Wrong inputs try { // converting string to integer int num= Integer.parseInt(s); //Printing the integer System.out.println("The converted String to Integer is: "+ num); } catch (NumberFormatException ex){ //Displaying message for wrong input System.out.println("Sorry Wrong Input"); } } }
Output:-