Posted In: Java Core, String

How to convert a String to an int in Java

Techniques used

1. Using Integer Class
2. Using BigInteger Class
3. Apache Commons IOUtils

<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.5</version>
</dependency>

4. Guava library

<dependency>
	<groupId>com.google.guava</groupId>
	<artifactId>guava</artifactId>
	<version>23.0</version>
</dependency>

 

package com.example.java.core;

import java.io.IOException;
import java.math.BigInteger;

import org.apache.commons.lang3.math.NumberUtils;

import com.google.common.primitives.Ints;

public class ConvertStringToInt {

	public static void main(String[] args) throws Exception {
		new ConvertStringToInt().convertStringToInt();
	}

	private void convertStringToInt() throws IOException {
		int i = 0;
		String number = "1234";

		// parseInt
		i = Integer.parseInt(number);
		System.out.println("i = " + i);

		// Apache NumberUtils
		i = NumberUtils.toInt(number);
		System.out.println("i = " + i);

		// Guava
		i = Ints.tryParse(number);
		System.out.println("i = " + i);

		// BigInteger
		BigInteger bigint = new BigInteger(number);
		System.out.println("i = " + bigint.intValue());
	}
}

by , on August 22nd, 2017

  • Categories