String Conversion int

String Conversion int

Summary: By the end of this tutorial "String Conversion int", you get acquainted with the conversion of string to double data type.

Sometimes, we obtain the values in string fomrat in Java. Printing the value is no problem (as long as user gets the same output) as it prints the same value as data type prints. For example, a int value is obtained in string format as in command-line arguments or from TextField's getText() method. The string value is to be converted into int format to use in caluclations as strings (or any objects in Java) cannnot be multiplied or used in any arithmetic operation. To convert, casting does not work as string and int are incompatable for conversion either implicitly or explicitly. It requires extra effort in coding known as "parsing operation". Parsing operation involves the usage of a wrapper class and parseXXX() method. For string to int conversion, it is required Integer class and parseInt() method and explained in the following program.

Program on String Conversion int
public class StringToDataType
  public static void main(String args[])
    String str = "10";
    System.out.println(str);           // printing is no problem

    int x = Integer.parseInt(str);     // conversion
    System.out.println(x * x);         // using in multiplication                  

parseInt() is a method of wrapper class Integer which converts string str to int x. Now x can be used in arithmetic operations.

Using the same technique, it is possible to convert string to other data types byte, short, long, float, double, character and boolean.

Note: The other way int to string is also possible.

View all for 65 types of Conversions

Leave a Comment

Your email address will not be published.