×

How to Convert String to Integer in Java

How to convert String to int in Java

You need to convert String into int if you want to perform a mathematical operation on string which contains digits. To do so, you need to perform the conversion from String to int.

You can convert String to int in two ways:

  • Using Integer.parseInt() method
  • Using Integer.valueOf() method

Using Integer.parseInt() method

The paresInt() is the static method of Integer wrapper class under java.lang package.

Example-

In the following example, number is a variable of type String that contains digits “10” as string. num1 is a variable of type integer that contains value 20. num2 is the variable of type integer which stores the converted value of str. Integer is a class. paresInt() is the static method that takes str as an argument and returns a primitive int value. sum is a variable of type integer which stores the value after addition. The println statement prints the value of sum.

public class StringTointExample
{
public static void main(String args[])
{
String str="10";
int num1 = 20;
int num2 = Integer.parseInt(str);
int sum = num1+num2;                   //num2 adds the converted value of str into num1
System.out.println("Befor conversion: "+str);
System.out.println("After conversion Sum is:  "+sum);
}
}

Output-

Before conversion:  10
After conversion Sum is:  30

Remember: All characters must be in digits; the number can have a minus sign.

Valid Conversion

  • String number=”-369”;

Invalid Conversion

  • String number=”369a”;
  • String number=”abcd”;

If you define a String as above, Integer.parseInt() throws “NumberFormatException”, because it is not a valid conversion. 

Exception

Exception in thread "main" java.lang.NumberFormatException: For input string: "369a"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at StringToIntExample.main(StringToIntExample.java:6)

Using Integer.valueOf() method

Integer.valueOf() works same as Integer.parseInt(String). It also converts a String to int value. It also throws NumberFormatException.

Example-

In the following example, str is a variable of type String that contains digits “-10” as string. num1 is a variable of type integer that contains value 110. num2 is a variable of type integer that stores the converted value of str. Integer is a wrapper class. valueOf() is the method that returns an integer instance representing the specified int value.  val is a variable that stores the sum of num1 and num2. First println statement prints the String str and second println prints the value of val after performing addition.

public class StringTointExample1
{
public static void main(String args[])
{
String str="-10";
int num1 = 110;
int num2 = Integer.valueOf(str);
int val = num1+num2;           //num2 adds the converted value of str into num1
System.out.println("Before conversion: "+str);
System.out.println("After addition value is: "+val);
}
}

Output-

Before conversion:  -10
After addition value is:  100

Difference Between Integer.valueOf() and Integer.parseInt()

There is a difference between Integer.valueOf() and Integer.parseInt(). The Integer.valueOf() method returns an object of Integer class whereas the Integer.parseInt() method returns a primitive int value.

If you need the primitive int datatype, then use parseInt() method. If you want wrapper Integer object, then use the valueOf() method.


Related Topics

Java Boolean Keyword

Boolean keyword In java programming language we basically have two types of primitive data types, Boolean and Numeric (integer and floating-point data types). In this article we are going to learn...

4 minutes read.

Java 9 Interface Private Method

Java 9 provides us the facility to include private methods inside the java interface. In java 8 and earlier versions, we are supposed to use only constant variables and abstract...

3 minutes read.

Why String in Immutable in Java?

Why String in Immutable in Java Immutable means unchangeable or unmodifiable.  Strings in Java are immutable, it means once a string is created, it cannot be modified or changed. Any change...

2 minutes read.

Java 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

Java Externalization

What is Externalization in Java? Externalization is a concept that is advanced to serialization. Serialization is a concept where we can transfer an object from our JVM ( Java virtual machine...

3 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

Java Regular Expressions

Java Regular Expressions The Java Regex or Regular Expression is an API that defines a pattern for searching or manipulating strings. A regular expression is a pattern that can be as simple as...

8 minutes read.

Convert Integer to Roman Numerals in Java

The main objective of this article is to convert the integers that are decimal values to the roman numbers. Problem statement: Write a software/program/code to convert any integer to a roman number. You...

10 minutes read.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

How to declare string array in Java

Introduction Array is a data structure with a fixed size, which allows us to store elements of similar type. Data of primitive types like int, char, float, string, etc. can be...

2 minutes read.

Math fma () method in java

In java, the Math module constitutes of fma () Method in it. This method can be accessed in two ways which can be differentiated by the parameters which are given...

4 minutes read.

ArrayList VS Linked List

ArrayList VS Linked List Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly. Let’s...

7 minutes read.

Java Substring

What is a substring in Java? Here by the name  " substring " itself, we can easily come to know it is a part of a string or a subset of...

4 minutes read.

How to create a linked list in Java

Introduction: The linked listing is one type of linear statistics shaped like an array. Not like arrays, linked listing factors aren't stored in a contiguous place. The elements have linked...

3 minutes read.

How to add 24 Hours to Date in Java?

In this tutorial, we will learn how to add 24 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Gregorian Calendar Java Current Date

GregorianCalendar class uses the Gregorian and Julian calendars. Dates are calculated by projecting present laws forever backward and forward in time. As a consequence, GregorianCalendar may be utilised to create...

8 minutes read.

Java copy constructor Example

Java provides the copy constructor much like C++ does. However, it is produced by default in C++. While we define our own copy constructor in Java. With an example, we will...

3 minutes read.

Differences between Byte Code and Machine Code

This tutorial will discuss the differences between Byte Code and Machine Code. Before that, let's try to know what byte and machine code is. Introduction Every computer has a set of instructions...

4 minutes read.

Java InetAddress class

InetAddress class The InetAddress class refers to the IP address, both IPv4 and IPv6.An instance of an InetAddress consists of an IP address and possibly its corresponding hostname. It provides a method to get the...

9 minutes read.