Saturday, April 17, 2010

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.

0 comments:

Post a Comment

Stats

ලාංකීය සිතුවිලි

lankeeya sithuwili

Blog Catalogs

 

Let's Learn Java API. Copyright 2010 All Rights Reserved