In the previous article we have discussed Java Program to Convert Wrapper Objects to Primitive Types.
In this article we will see how to convert string type to integer type.
Program to Convert String to int
Let’s see some examples of both the types.
Example-1: String types int a = "b"; int b = "BTechGeeks";
Examples-2: int types int a = 5; int b = 57;
Let’s see howtodo it.
Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.
Method 1 : Java Program to Convert String to int Using parseInt() method
String type variable can be converted to Integer by using parseInt()
, let’s see how it actually works.
Here this method is a wrapper class in Java. This method of the Integer class converts the string variables into Integer.
Approach :
- Take a string value and store it in a string variable
input1
. - Then pass that
input1
variable as parameter toparseInt()
method which will convert the string into Integer value and return it . - Store that Integer value in a variable output .
- Display the result .
Program:
import java.util.Scanner; public class Main { public static void main(String[] args) { // creating scanner object Scanner sc = new Scanner(System.in); // input a String through scanner class System.out.print("Enter a string : "); String input1=sc.next(); // converting to Integer int output =Integer.parseInt(input1) ; System.out.println("Converted Integer value is : " + output); } }
Output : Enter a string : 434 Converted Integer value is : 434
Method 2 : Java Program to Convert String to int Using valueOf() method
String type variable can be converted to Integer by using valueOf()
, let’s see how it actually works.
This method returns an object of the Integer class. However, the object will be automatically converted into the primitive type.
Approach :
- Take a string value and store it in a string variable
input1
- Then pass that input1 variable as parameter to
valueOf()
method which will convert the string into Integer value and return it . - store that Integer value in a variable
output
. - Display the result .
Program:
import java.util.Scanner; public class Main { public static void main(String[] args) { // creating scanner object Scanner sc = new Scanner(System.in); // input a String through scanner class System.out.print("Enter a string : "); String input1=sc.next(); // converting to Integer Integer output =Integer.valueOf(input1) ; System.out.println("Converted Integer value is : " + output); } }
Output : Enter a string : 434 Converted Integer value is : 434
Beginners and experienced programmers can rely on these Best Java Programs Examples and code
various basic and complex logics in the Java programming language with ease.
Related Java Program: