Data Types in Java:
Data types represent the different values to be stored in the variable. In java, there are two types of data types:
- Primitive data types
- Non-primitive data types
- For the other primitive types (char, byte, short, int, long, float, and double), there are two kinds of conversion: implicit and explicit.
- Implicit conversions: An implicit conversion means that a value of one type is changed to a value of another type without any special directive from the programmer.
Example codes on how to convert Java String To Int.
- Convert using Integer.parseInt()
- Convert using Integer.valueOf()
- Convert using new Integer(String).intValue()
- Convert using DecimalFormat
- Convert with special radix (not base 10 system)
Convert using Integer.parseInt()
The Integer.parseInt() static method parses the string argument as a signed decimal integer and returns an int value.
Syntax
public static int parseInt(String s) throws Number Format Exception
The parameter s will be converted to a primitive int value. Note that the method will throw a NumberFormatException if the parameter is not a valid int.
Example
[ad type=”banner”]When you run the above code, the output will show this:
The number is: 5678
Note: The resulting value is not an instance of the Integer class but just a plain primitive int value.
Convert using Integer.valueOf()
The Integer.valueOf() static method will return an Integer object holding the value of the specified String.
Syntax
public static Integer valueOf(String s) throws NumberFormatException
Note: The method will throw a NumberFormatException if the parameter is not a valid integer.
Example
This will output:
The number is: 5678
Note: The resulting value is an instance of the Integer class and not a primitive int value.
Convert using new Integer(String).intValue()
Another alternative method is to create an instance of Integer class and then invoke it’s intValue() method.
Example
[ad type=”banner”]We can shorten to:
or just:
Convert using Decimal Format
The class java.text.DecimalFormat is a class that can be used to convert a number to it’s String representation or it can parse a String into it’s numerical representation.
Example
Output
The number is: 5678
Note: The parse() method will throw a ParseException when there are problems encountered with the String.
Convert with special radix
The above examples uses the base (radix) 10. There are cases when we wish to convert a Java String to Integer but using another base.
Both Integer.parseInt() and Integer.valueOf() can receive a custom radix to be used in the conversion.
Example
[ad type=”banner”]output:
255
255
Octal
output:
255
255
Hexadecimal
output:
255
255