Java String to Int

Java String to Int

0 Comments

Last Updated on June 16, 2019 by Simanta

A common requirement while programming in Java is to convert

String
String to
int
int. UI inputs in Web-based HTML, JSP, or Thymeleaf templates are transferred to backend Java applications as strings. It is the application developer’s responsibility to perform any
String
String to
int
int conversions to fulfill business logic, such as calculating discounts, storing age, and so on.

In this post, I’ll discuss how to convert String in Java to int.

The Integer.parseInt Method

The

Integer.parseInt()
Integer.parseInt() method takes as input a
String
String and returns an
int
int value.

The code to use this method is.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public int convertWithParseInt(String str){
int num = Integer.parseInt(str);
return num;
}
public int convertWithParseInt(String str){ int num = Integer.parseInt(str); return num; }
public int convertWithParseInt(String str){
    int num = Integer.parseInt(str);
    return num;
}

Here is the test code in JUnit.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package springframework.guru;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class StringToIntConverterTest {
private StringToIntConverter stringToIntConverter;
String str;
@Before
public void setUp(){
str = "369";
stringToIntConverter=new StringToIntConverter();
}
@After
public void tearDown(){
str = null;
}
@Test
public void convertWithParseInt() {
int val= stringToIntConverter.convertWithParseInt(str);
System.out.println(val);
assertEquals(val, 369);
}
}
package springframework.guru; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class StringToIntConverterTest { private StringToIntConverter stringToIntConverter; String str; @Before public void setUp(){ str = "369"; stringToIntConverter=new StringToIntConverter(); } @After public void tearDown(){ str = null; } @Test public void convertWithParseInt() { int val= stringToIntConverter.convertWithParseInt(str); System.out.println(val); assertEquals(val, 369); } }
package springframework.guru;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class StringToIntConverterTest {

    private StringToIntConverter stringToIntConverter;
    String str;

    @Before
    public void setUp(){
        str = "369";
        stringToIntConverter=new StringToIntConverter();
    }
    @After
   public void tearDown(){
        str = null;
    }

    @Test
    public void convertWithParseInt() {
        int val= stringToIntConverter.convertWithParseInt(str);
        System.out.println(val);
        assertEquals(val, 369);

    }

}

The output on running the test in InteliJ is this.

Test Output converting string to int in Java

The

Integer
Integer class also provides an overloaded
parseInt()
parseInt() method that additionally accepts the radix (base) to be used while parsing.

Here is the code to use the overloaded method..

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public int convertWithParseIntWithRadix(String str, int radix){
int num = Integer.parseInt(str, radix);
return num;
}
public int convertWithParseIntWithRadix(String str, int radix){ int num = Integer.parseInt(str, radix); return num; }
public int convertWithParseIntWithRadix(String str, int radix){
    int num = Integer.parseInt(str, radix);
    return num;
}

Here is the test code.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@Test
public void convertWithParseIntWithRadix() {
int val= stringToIntConverter.convertWithParseIntWithRadix("1010110", 2);
System.out.println(val);
assertEquals(val, 86);
}
@Test public void convertWithParseIntWithRadix() { int val= stringToIntConverter.convertWithParseIntWithRadix("1010110", 2); System.out.println(val); assertEquals(val, 86); }
@Test
public void convertWithParseIntWithRadix() {
    int val= stringToIntConverter.convertWithParseIntWithRadix("1010110", 2);
    System.out.println(val);
    assertEquals(val, 86);
}

The output on running the test in InteliJ is this.
Java string to int using radix (base)

Handling Parsing Exception

The

parseInt()
parseInt() method throws a
NumberFormatException
NumberFormatException if the
String
String does not contain a parsable
int
int.

Here is a sample code to handle the

NumberFormatException
NumberFormatException gracefully.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public static final int DEFAULT_DEFAULT_PARSED_INT = 0;
public int tryConvertWithParseInt(String str){
try {
int number = Integer.parseInt(str);
return number;
}
catch(NumberFormatException e){
return DEFAULT_DEFAULT_PARSED_INT;
}
}
public static final int DEFAULT_DEFAULT_PARSED_INT = 0; public int tryConvertWithParseInt(String str){ try { int number = Integer.parseInt(str); return number; } catch(NumberFormatException e){ return DEFAULT_DEFAULT_PARSED_INT; } }
public static final int DEFAULT_DEFAULT_PARSED_INT = 0;
public int tryConvertWithParseInt(String str){
    try {
        int number = Integer.parseInt(str);
        return number;
    }
    catch(NumberFormatException e){
        return DEFAULT_DEFAULT_PARSED_INT;
    }
}

This code returns a default

int
int value whenever a
NumberFormatException
NumberFormatException is thrown by the
parseInt()
parseInt() method.

Here is the JUnit test code.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@Test
public void tryConvertWithParseInt() {
int valA = stringToIntConverter.tryConvertWithParseInt(str);
int valB = stringToIntConverter.tryConvertWithParseInt("abc");
System.out.println(valA);
assertEquals(valA, 369);
System.out.println(valB);
assertEquals(valB, 0);
}
@Test public void tryConvertWithParseInt() { int valA = stringToIntConverter.tryConvertWithParseInt(str); int valB = stringToIntConverter.tryConvertWithParseInt("abc"); System.out.println(valA); assertEquals(valA, 369); System.out.println(valB); assertEquals(valB, 0); }
@Test
public void tryConvertWithParseInt() {
    int valA = stringToIntConverter.tryConvertWithParseInt(str);
    int valB = stringToIntConverter.tryConvertWithParseInt("abc");
    System.out.println(valA);
    assertEquals(valA, 369);
    System.out.println(valB);
    assertEquals(valB, 0);

}

The test output is this.
Java string to int output

The Integer.valueOf Method

The Integer class also comes with the static

valueOf()
valueOf() method to convert
String
String to
int
int. The
valueOf()
valueOf() method interprets the
String
String exactly as if it were given to
parseInt()
parseInt(). In fact, the
valueOf()
valueOf() method internally uses the
parseInt()
parseInt() method.

However,

valueOf()
valueOf() returns a new
Integer
Integer object whereas
parseInt()
parseInt() returns a primitive
int
int.

The code to parse

String
String using the
valueOf()
valueOf() method is this.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public Integer convertWithValueOf(String str){
try {
Integer num = Integer.valueOf(str);
return num;
}
catch(NumberFormatException e){
return DEFAULT_PARSED_INT;
}
}
public Integer convertWithValueOf(String str){ try { Integer num = Integer.valueOf(str); return num; } catch(NumberFormatException e){ return DEFAULT_PARSED_INT; } }
public Integer convertWithValueOf(String str){
    try {
        Integer num = Integer.valueOf(str);
        return num;
    }
    catch(NumberFormatException e){
        return DEFAULT_PARSED_INT;
    }
}

Here is the JUnit test code.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@Test
public void convertWithValueOf() {
int val= stringToIntConverter.convertWithValueOf(str);
System.out.println(val);
assertEquals(val, 369);
}
@Test public void convertWithValueOf() { int val= stringToIntConverter.convertWithValueOf(str); System.out.println(val); assertEquals(val, 369); }
@Test
public void convertWithValueOf() {
     int val= stringToIntConverter.convertWithValueOf(str);
     System.out.println(val);
     assertEquals(val, 369);
 }

The test output is this.

Java string to integer output

Note: Similar to parseInt(), the valueOf() method also have an overloaded version that accepts an additional radix value.

Conclusion

Considering Java is a strongly typed language and often interfaces with systems that do not have the type system of Java, converting from a string value to an int value in Java is very common task. As you can see Java provides a number of different ways to convert a string value to an integer value.

 

About jt

    You May Also Like

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.