String to long Conversion in Java

String to long Conversion in Java

String to long Conversion: Sometimes, we obtain the values in string format 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 long 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 long 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 long 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 long conversion, it is required Long class and parseLong() method and explained in the following program.

Parsing Example with String to long conversion


String to long
Output screenshot on String to long Example

parseLong() is a method of wrapper class Long which converts string str to long l1. Now l1 can be used in arithmetic operations.

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

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

View all for 65 types of Conversions

Leave a Reply

Your email address will not be published. Required fields are marked *