How to Convert String to int in Java

Connect with

How to Convert String to int in Java width=Learn various ways to convert String to int in Java, ways are: without library, using while loop, using java class like Integer.

1. overview of convert string to int in Java

In day-to-day programmer life, you have to convert one data type to another like convert string to int in Java. There are various ways to convert from string to int in Java. It depends, where you want to apply this. If any interview will ask then you can ask him/her, the library can be used or not. if he/she says yes, then reply by using Integer class to convert but if he wanted to check your logic then you have to choose a plain way to convert from string to int. Please ask precondition to Interviewer before replying anything.

2. By using Integer class

If you are using in your project then better to use following approach i.e. Integer class to convert from string to int value.

int i = Integer.parseInt("234");

//OR
int  aIntVal = Integer.valueOf("234").intValue();

Here, in the above code snippet:
Integer.parseInt() method return an int value .
Integer.valueOf() method returns Integer wrapper object from which you can get int value by calling intValue() method.

3. Method to convert by using For Loop

/**
 * This java method convert string to int or number.
 * String can be negative or positive.
 * 
 * @param numStr
 * @return
 */
public static int stringToNumber(String numStr) {

	char ch[] = numStr.toCharArray();
	int sum = 0;
	boolean isFlag = false;
	int i = 0;
	
	if (ch[0] == '-') {
		i = 1;
		isFlag = true;
	}
	
	for (; i < ch.length; i++ ) {
		sum = (sum * 10) + (ch[i] - '0');
	}
	
	// get ascii value for zero
	/*int zeroAscii = (int) '0';
	for (; i < ch.length; i++ ) {
		int tmpAscii = (int) ch[i];
		sum = (sum * 10) + (tmpAscii - zeroAscii);
	}*/
	
	if (isFlag) {
		sum = -sum;
	}
	return sum;
}

4. Using while Loop

/**
 * This method is used to convert from string to int.
 * 
 * @param inutStr
 * @return
 */
public static int strToInt(String inutStr) {
	int i = 0;
	int num = 0;
	boolean isFlag = false;

	// check for negative sign if it's there, set the isNeg=true and
	// initialize i to 1
	if (inutStr.charAt(0) == '-') {
		isFlag = true;
		i = 1;
	}

	while (i < inutStr.length()) {
		// Minus the ASCII code of '0' i.e. 48 to get the value of the
		// charAt(i++).
		num = num * 10 + (inutStr.charAt(i++) - '0');
	}

	if (isFlag) {
		num = -num;
	}
	return num;
}

5. By Using Apache Commons Library

There is an alternate solution is to use Apache Commons’ NumberUtils but I don’t use this just for sake of conversion.

int num = NumberUtils.toInt("1234");

6. Complete Example of string to int

package com.core;

public class StringToNumber {

	public static void main(String[] args) {

		System.out.println("\"-3256\" == " + stringToNumber("-3256"));
		System.out.println("\"3256\" == " + stringToNumber("3256"));
		System.out.println("\"-785\" == " + strToInt("-785"));
	}

	/**
	 * This java method to convert from string to number.
	 * 
	 * @param numStr
	 * @return
	 */
	public static int stringToNumber(String numStr) {

		char ch[] = numStr.toCharArray();
		int sum = 0;
		boolean isFlag = false;
		int i = 0;
		
		if (ch[0] == '-') {
			i = 1;
			isFlag = true;
		}
		
		for (; i < ch.length; i++ ) {
			sum = (sum * 10) + (ch[i] - '0');
		}
		
		// get ascii value for zero
		/*int zeroAscii = (int) '0';
		for (; i < ch.length; i++ ) {
			int tmpAscii = (int) ch[i];
			sum = (sum * 10) + (tmpAscii - zeroAscii);
		}*/
		
		if (isFlag) {
			sum = -sum;
		}

		return sum;
	}

	/**
	 * This method is used to convert from string to int.
	 * 
	 * @param inutStr
	 * @return
	 */
	public static int strToInt(String inutStr) {
		int i = 0;
		int num = 0;
		boolean isNeg = false;

		// check for negative sign if it's there, set the isNeg=true and
		// initialize i to 1
		if (inutStr.charAt(0) == '-') {
		  isNeg = true;
		  i = 1;
		}

		while (i < inutStr.length()) {
		  // Minus the ASCII code of '0' i.e. 48 to get the value of the charAt(i++).
                  num = num * 10 + (inutStr.charAt(i++) - '0');
		}

		if (isNeg) {
			num = -num;
		}
		return num;
	}
}

The Apache utility is nice because if the string is an invalid number format then 0 is always returned. Hence saving you the try-catch block.

7. Reference

Visit Java tutorial for more details

Visit Oracle Java for more details.
Apache NumberUtils API Version 3.4
Happy learning! 🙂 for conversion of string to int in Java.


Connect with

Leave a Comment

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