Convert string to int

String in java is a unique data type and it is the most common data type that is used in programs.  Whatever we place in “ ”(Double quotes) treated as a string.
Suppose we have a string “12345” and we want to convert string to int, Java provides some ways to parse string to int.

Convert string to int

There are two ways to convert java string to int, Let’s discuss one by one with example.
1. Integer.parseInt() – returns primitive data
2. Integer.valueIf() – return non primitive data

Integer.parseInt()

Java parseInt() method present in the Integer class that is used to convert string to int java.  It can access by className as it is a static method of Integer class. It throws NumberFormatException if the string cannot be converted to an int type.

public class StringToInt
{
   public static void main(String args[])
   {
	   String s1 = "12345";
	   String s2 = "100";
	   
	   int a = Integer.parseInt(s1);
	   int b = Integer.parseInt(s2);
	   
	   int intValue = 1;
	   System.out.println(intValue + a);
	   System.out.println(intValue + b);
   }
}

Output: 12346
101

NumberFormatException in Integer.parseInt()

The parseInt() method converts the string to int only if the string has numbers. If it not in number format then it throws an exception.

public class StringToInt
{
   public static void main(String args[])
   {
	   String s1 = "ABC12345";
	   try
	   {
		   int a = Integer.parseInt(s1);
	   }
	   catch(NumberFormatException e)
	   {
		   System.out.println("Invalid integer");
	   }
	   
   }
}

Output: Invalid integer

Integer.valueOf()

The Integer valueof() method exists in the Integer class that is used to convert string to an Integer object. This method returns the object of the Integer class that holds int value.  It can access by className as it is a static method of Integer class. It throws NumberFormatException if the string cannot be converted to an int type.

public class StringToInt
{
   public static void main(String args[])
   {
	   String s1 = "12345";
	   String s2 = "100";
	   
	   int a = Integer.valueOf(s1);
	   int b = Integer.valueOf(s2);
	   
	   int intValue = 1;
	   System.out.println(intValue + a);
	   System.out.println(intValue + b);
   }
}

Output: 12346
101

NumberFormatException in Integer.valueOf()

The valueOf() method converts the string to Integer only if string has numbers. If it has alphabet also it throws exception.

public class StringToInt
{
   public static void main(String args[])
   {
	   String s1 = "ABC12345";
	   try
	   {
		   int a = Integer.valueOf(s1);
	   }
	   catch(NumberFormatException e)
	   {
		   System.out.println("Invalid integer");
	   }
	   
   }
}

Output: Invalid integer

Leave a Comment