Converting Strings to Numeric Values - Java Language Basics

Java examples for Language Basics:String

Solution 1

Use the Integer.valueOf() helper method to convert Strings to int data types.

String one = "1"; 
String two = "2"; 
int result = Integer.valueOf(one) + Integer.valueOf(two); 

Solution 2

Use the Integer.parseInt() helper method to convert Strings to int data types.

String one = "1"; 
String two = "2"; 
int result = Integer.parseInt(one) + Integer.parseInt(two); 
System.out.println(result); 

Full Source Code

Demo Code

public class Main {
    public static void main(String[] args){
       stringsToNumbers();//from   w  w  w .  j ava 2 s .  c  om
       stringsToNumbersParseInt();
    }
    /**
     * Solution #1 using Integer.valueOf()
     */
    public static void stringsToNumbers(){
        String one = "1";
        String two = "2";
        
        int result = Integer.valueOf(one) + Integer.valueOf(two);
        
        System.out.println(result);
        
    }
    
    /**
     * Solution #2 using Integer.parseInt()
     */
    public static void stringsToNumbersParseInt(){
        String one = "1";
        String two = "2";

        int result = Integer.parseInt(one) + Integer.parseInt(two);

        System.out.println(result);
    }
}

Result


Related Tutorials