Converting object to int is a simple work in Java. Addressing the problem straight away, we have two ways to work with.

  1. Integer.parseInt()
  2. Integer.valueOf()

The key difference is that parseInt() takes in only String as input. On another hand valueOf() accepts both Strings and Integers.

It must be noticed that parseInt() returns a primitive int type. Whereas valueOf() returns Integer object.

String object to int Java using parseInt()

public class ObjectToInt {
	public static void main(String[] args) {
		String s = new String("1");// String object
		int i = Integer.parseInt(s);
		System.out.println("INT VALUE: "+i);
	}
}

Output

INT VALUE: 1

Convert to int using valueOf()

public class ObjectToInt {
	public static void main(String[] args) {
		String s = new String("1");// String object
		int i = Integer.valueOf(s);
		System.out.println("INTEGER VALUE: "+i);
	}
}

Output
INTEGER VALUE: 1

Basically, int is the primitive data type whereas Integer is the wrapper class.

java.lang.NumberFormatException when changing object to int in Java

If a non-number String is passed to either Integer.parseInt() or Integer.valueOf() they throw a NumberFormatException. It is quite obvious that the Strings may contain a letter or any character that is not a number. For instance,
NumberFormatException Example

public class ObjectToInt {
	public static void main(String[] args) {
		String s = new String("hello");
		int i = Integer.valueOf(s);
		System.out.println("INT VALUE: "+i);
	}
}

Output

Exception in thread "main" java.lang.NumberFormatException: For input string: "hello"

This can be handled with Exception handling. Let’s create a simple try-catch block and fix that.

How to Fixed/solve  java.lang.NumberFormatException for the above coding example?

public class ObjectToInt {
	public static void main(String[] args) {
		try {
			String s = new String("hello");
			int i = Integer.valueOf(s);
			System.out.println("INT VALUE: "+i);
		}catch(NumberFormatException n) {
			System.out.println("NOT A NUMBER!!");
		}
	}
}

Output

NOT A NUMBER!!

Why Covert Java object to int?

Now, if you are wondering why to convert Object to int in java, let’s take a look at this example. Say, we have to accept a comma-separated balance number as a String object and use it to calculate simple interest over a given period of time. Here we have to convert the String object to an int to calculate the simple interest using the formulae. Since arithmetic operations cannot be performed on a String object, the conversion is absolutely necessary.

Though using a double data type would be more practical, we have used int for simplicity. Try on your own for a better understanding. Use any of the two ways available. Here’s the solution for help.

Calculate Interest

public class CalcInterest {
	static int objectToInt(String s) {
		s = s.trim(); // to remove left and right trailing white spaces, if any.
		int num = 0;
		for(int i=0; i<s.length(); i++) {
			if(s.charAt(i) != ',') {
				num = num*10;
				num += Integer.parseInt(s.charAt(i)+"");
			}
		}
		return num;
	}
	public static void main(String[] args) {
		String balance = "1,000"; // dollar
		int rate = 8; // percent
		int time = 4; //years
		int principal = objectToInt(balance);
		int interest = (principal * rate * time)/100;
		System.out.println("Interest on "+balance+"$ for "+time+" years at "+rate+"% interest is "+interest+"$");
	}
}

Output

Interest on 1,000$ for 4 years at 8% interest is 320$

So far, we have only converted objects of String type to int. But you know that objects can be of any type. What if you want to convert a custom Object to int type?

Custom Object to Int

object to int javaSince we are confined to pass only String or Integers(in case of valueOf), we must convert our custom Object to String one way or the other. A simple way to do that is to override toString(). Lets’s take a look at an example. Here we have defined a class called MyNumber with an int value ‘i’.

 

MyNumber Class

class MyNumber{
	int i;
	public MyNumber(int i) {
		this.i = i;
	}
	@Override
	public String toString() {
		return i+"";
	}
}

In line 6, notice the @Override annotation. The toString() method is defined in the Object class. The Object class is the parent class of all the classes in Java by default. So here in our class MyNumber, we redefine (override) the toString method to use as per our convenience.

Main Method

public class ObjectToInt {
	public static void main(String[] args) {
		MyNumber m = new MyNumber(5);
		int i = Integer.parseInt(m.toString());
		System.out.println("INT VALUE: "+i);
	}
}

In the main method, we have created an object of this class MyNumber. Then we used the toString method to pass the int value I as a String. This String object is used as an input to the Integer.parseInt() method to be returned as a primitive int.

More Java tutorials-

Like this article? Follow us on Facebook and LinkedIn. You can also subscribe to our weekly Feed.