Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Java Wrapper Classes :: Converting String Values Into Integer Values

What is Java API ?
Java Api is a short term for Java Application Programming Interface. Java API contains thousands of classes which are very useful for java programmers. Programmers can use these already provided java classes to enhance their productivity. Java documentation is available in following site.
http://java.sun.com/javase/6/docs/

This is the first example of Learn Java API blog. I assume the readers of this blog have basic knowledge of java programming.
Integer wrapper class can be used to manipulate Integer variables. We use parseInt() method in Integer class for this example.

//© learnjavaapi.blogspot.com
class ConvertInt{
public static void main(String srgs[]){
String n1="12";
String n2="45";
int num1,num2;
//String concatenation
System.out.println(n1+n2);
//Integer conversion
try{
num1=Integer.parseInt(n1);
num2=Integer.parseInt(n2);
System.out.println(num1+num2);
}catch(NumberFormatException e){
System.out.println("Please give a valid number!");
}
}
}

Output :

Explanation :
n1 and n2 contain String values of given number. Statement in line 08 performs a string concatenation because of n1 and n2 are string values. Hence you can see the output as 1245 twelve and forty five .
Statement in line 13 performs numeric add operation. hence the 2nd output is 57 which is equal to 12+45 . A NumberFormatException  will be thrown if an error occur while converting numbers.


This post first appeared on Let's Learn Java API, please read the originial post: here

Share the post

Java Wrapper Classes :: Converting String Values Into Integer Values

×

Subscribe to Let's Learn Java Api

Get updates delivered right to your inbox!

Thank you for your subscription

×