Monday, December 28, 2009

2 Methods to Convert a Number in String into Integer

When taking integer values from the command-line, the numbers are stored in String argument args[] which is given as a parameter to the main() method.


In the above image, the numbers in the yellow box are the parameters to the main() method

To convert, numbers in String format into int or float datatype, we have the following 2 methods.

Method 1: Using parseInt() method
The parseInt( String s )" method, converts the given number in string s into an Integer. This number can now be assigned to variable of int datatype or object of Integer class.

Similarly, we can use parse methods for Float, Double etc.

Note: parseInt() method and similar methods in Float, Short etc are static methods, hence there should be called with corresponding Classname as prefix to there method-call

Method 2: Using valueOf() Method
This is another static method. It is also available in datatypes other than Integer
Syntax:
   (Integer.valueOf( String s ).intValue())
The intValue() method is used to return the value of Integer object as int

No comments:

Post a Comment