×

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

How to take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to...

5 minutes read.

Beautiful Array in Java

In this section, we will be acknowledged about the beautiful array in Java, its characteristics, how it is achieved. What are the types of approaches and what are the tools...

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.

How to create an array in Java

An array is a linear data structure stores a collection of fixed number ofelements of similar type. The size of an array is specified when it is created. The array...

14 minutes read.

Why to use Enum in Java?

In this article, you will be acknowledged about the Enum in java, its uses and mainly its purpose. Enum has various functionalities. Each of them will be discussed. Enum In a computer...

3 minutes read.

Prime Number Program in Java Using a Scanner

In Java, a prime number is one that can only be divided by one or by itself and is greater than one. In other words, only one or itself can...

3 minutes read.

Knapsack problem in Java

We have a collection of items in the knapsack problem. Every object has a weight and a value. These things should go in a knapsack. But there is a weight...

3 minutes read.

Java Queue

The Java.util package has the interface Queue, which does extend the Collection interface. It is used to protect the parts that are managed using the FIFO approach. Being an interface, the...

5 minutes read.

String isnullorempty in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java Math getExponent() Method

The getExponent() method of Math class returns the unbiased exponent of the argument. Syntax: public static int getExponent (double d) Parameters: The parameter ‘d’ represents the double value. Return Value: The getExponent () method returns the...

1 minute read.

Java Future Example

Future is an interface in the Java language that is a part of  java.util.concurrent package. It serves as a symbol for the output of an asynchronous computation. The interface offers ways to determine whether a computation has finished,  wait for it to finish, and receive its result. Once the task or calculation is finished, it cannot be undone. A Future interface offers ways to determine whether the computation is finished, to wait for it to finish, and to receive the computation's results. When the computation...

3 minutes read.

Java Viva Questions and Answers

Question: Explain Java programming language. Answer: It is a high-level programming language. This programming language is based on the principles of object-oriented programming. Large-scale applications can be developed by using this...

16 minutes read.

Java String toUpperCase() methods

Java String toUpperCase() method is used to convert all the characters of the String into upper case. Syntax public String toUpperCase() public String toUpperCase(Locale locale) Returns It returns upper case String. Java String toUpperCase() Example 1: public...

1 minute read.

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of...

3 minutes read.

Java Switch Keyword

In this article we are going to learn the concept of a java switch keyword. Generally, java case keyword is used with the switch statements or keyword.Switch keyword is implemented in...

3 minutes read.

String vs StringBuilder

String vs StringBuilder In this section, we will discuss the comparison between Java String and StringBuilder class. String In Java, a string is treated as an object that represents a sequence of characters....

4 minutes read.

Java Boolean logicalAnd() Method

The logicalAnd() method of Java Boolean class returns the result of implementing logicalAND operation on the specified Boolean operands. Syntax:public static boolean logicalAnd (boolean a, boolean b) Parameters:The parameters ‘a’ and ‘b’...

2 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

Java logger

Logging is a crucial Java feature that aids developers in identifying issues. The logging methodology is included with Java as the programming language. It offers the Logging API, which debuted...

7 minutes read.

nth Prime Number in Java

A number is considered prime if only divisible by one and itself. Prime numbers include, for example, 2, 3, 5, 7, 11, etc. In looking at it another way, a...

5 minutes read.