HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / String / Convert Java String to int

Convert Java String to int

Quick references to convert Java string to int values in java. Included code snippets have examples of converting string values to int or Integer in multiple base or radix.

Integer.parseInt() Method

parseInt() method is overloaded in two forms:

public static int parseInt(String s) throws NumberFormatException {...}
public static int parseInt(String s, int radix) throws NumberFormatException {...}

Both methods throw NumberFormatException is argument string is null or string length is zero i.e. empty string. The first method also throws exception when string is not a parsable integer in base 10.

int intVal = Integer.parseInt("1001");
System.out.println(intVal);

int intVal1 = Integer.parseInt("1001", 8); 	//base 8
System.out.println(intVal1);

int intVal2 = Integer.parseInt("1001", 16);	//base 16
System.out.println(intVal2);

Output:

1001
513
4097

Integer.valueOf() Method

valueOf() method is very similar to parseInt() method – with only one difference that return type is Integer class instead of primitive int. In fact, if you look at sourcecode of valueOf() method, it internally calls parseInt() method.

It is also overloaded in two forms:

public static Integer valueOf(String s) throws NumberFormatException {...}
public static Integer valueOf(String s, int radix) throws NumberFormatException {...}

Both methods throw a NumberFormatException if argument string is not a parsable Integer in base 10 – similar to parseInt() method.

try {
    Integer intVal = Integer.valueOf("1001");
    System.out.println(intVal);

    Integer intVal1 = Integer.valueOf("1001", 8); 	//base 8
    System.out.println(intVal1);

    Integer intVal2 = Integer.valueOf("1001", 16);	//base 16
    System.out.println(intVal2);
}
catch (NumberFormatException nfe) {
	nfe.printStackTrace();
}

Output:

1001
513
4097

Use Integer.decode()

decode() is another method for string to int conversion but only for decimal, hexadecimal and octal numbers.

  • Octal numbers should start with optional plus/minus sign and then suffix ‘0’ i.e. +0100, -02022, 0334, 0404 etc.
  • Decimal numbers should start with optional plus/minus sign i.e. +100, -2022, 334, 404 etc.
  • Hex numbers should start with optional plus/minus sign and then suffix ‘0x’ or ‘0X’ i.e. +0x100, -0x2022, 0x334, 0x404 etc.

It does not have any overloaded form:

public static Integer decode(String nm) throws NumberFormatException

Integer intVal = Integer.decode("+100");
System.out.println(intVal);

Integer intVal1 = Integer.decode("+0100"); 	//base 8
System.out.println(intVal1);

Integer intVal2 = Integer.decode("+0x100");	//base 16
System.out.println(intVal2);

Output:

100
64
256

Caution – Handle NumberFormatException

You should keep you code in try-catch block to avoid any unwanted behavior in application. Any un-parsable number in any of above method with throw NumberFormatException.

int intVal = Integer.parseInt("1001x"); //un-parsable integer
System.out.println(intVal);

This will produce error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "1001x"
	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 com.howtodoinjava.example.StringToIntExamples.main(StringToIntExamples.java:7)

To safeguard your application, use try-catch block handle the exception appropriately.

String stringVal = "1001x";

int intVal = 0;

try
{
	intVal = Integer.parseInt(stringVal);
}
catch(NumberFormatException nfe){
	System.out.println("un-parsable integer :: " + stringVal);
}
System.out.println(intVal);

Output:

un-parsable integer :: 1001x
0

Use above methods to parse Java string to int as per application requirements.

Complete Example

package com.howtodoinjava.example;

public class StringToIntExamples 
{
	public static void main(String[] args) 
	{
		//Using Integer.parseInt() method
		
		int intVal = Integer.parseInt("1001");
		System.out.println(intVal);
		
		//Using Integer.valueOf() method
		//valueOf() returns Integer instance which is converted to int
		
		int intVal2 = Integer.valueOf("1001");
		System.out.println(intVal2);
		
		//Using Integer.decode() method 
		//decode() returns Integer instance which is converted to int
		
		int intVal3 = Integer.decode("1001"); 	
		System.out.println(intVal3);
		
		
		//Base X String to int 
		
		//base 8
		System.out.println( Integer.parseInt("1001", 8) );
		System.out.println( Integer.valueOf("1001", 8) );
		System.out.println( Integer.decode("01001") );
		
		//base 16
		System.out.println( Integer.parseInt("1001", 16) );
		System.out.println( Integer.valueOf("1001", 16) );
		System.out.println( Integer.decode("0x1001") ); 
	}
}

Output:

1001

1001

1001

513
513
513

4097
4097
4097

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

String methods

  • String concat()
  • String hashCode()
  • String contains()
  • String compareTo()
  • String compareToIgnoreCase()
  • String equals()
  • String equalsIgnoreCase()
  • String charAt()
  • String indexOf()
  • String lastIndexOf()
  • String intern()
  • String split()
  • String replace()
  • String replaceFirst()
  • String replaceAll()
  • String substring()
  • String startsWith()
  • String endsWith()
  • String toUpperCase()
  • String toLowerCase()

String examples

  • Convert String to int
  • Convert int to String
  • Convert String to long
  • Convert long to String
  • Convert CSV String to List
  • Java StackTrace to String
  • Convert float to String
  • String – Alignment
  • String – Immutable
  • String – StringJoiner
  • Java – Split string
  • String – Escape HTML
  • String – Unescape HTML
  • String – Convert to title case
  • String – Find duplicate words
  • String – Left pad a string
  • String – Right pad a string
  • String – Reverse recursively
  • String – Leading whitespaces
  • String – Trailing whitespaces
  • String – Remove whitespaces
  • String – Reverse words
  • String – Find duplicate characters
  • String – Check empty string
  • String – Get first 4 characters
  • String – Get last 4 characters
  • String – (123) 456-6789 pattern
  • String – Interview Questions

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)