What is int in Java

Internet Java: convert strings to integers

display

Fortunately, there are already methods in Java for converting a string into an integer. In our instructions, we will show you how to use this function and what problems can arise with it.

Convert string to integer

Java provides you with an interface for converting data types from the type String to a Integer. The static function parseInt is part of the class Integer. The method is used as follows:



The int-Variable now contains the value 42. You can also use the static method valueOf use if instead of a int-variable IntegerObject you want to create.



This method has the same effect, but delivers a Integer-Object.

Conversion from another base

There may be times when you want to convert a string from a number system other than the tens system. An example of this would be binary or hexadecimal numbers. Fortunately, this can be done by modifying the code slightly. The functions parseInt and valueOf offer the possibility to pass a second parameter in the function call, which determines the base of the number in the string.




The variable numberInt now contains the value 5, because it was specified in the function call that the number in the numberString is a binary number.

Similarly, we can also create integer objects from a string.




The Integer-Object numberInteger now receives the value 41688 because the numberString is a hexadecimal number, which we have specified by means of 16 in the function call.

Possible exception

The methods parseInt and valueOf can both one NumberFormatException throw, if the arguments do not allow conversion. Consider the following code example:





Here you will find that trying "abc123"To convert to a decimal number will obviously fail. In this case, a NumberFormatException issued. If you try to convert the same string into the hexadecimal system:





Accordingly, it makes sense to make sure beforehand whether a conversion can take place at all. In addition to this, you should of course also use exception handling if you cannot ensure that the strings are in the correct format.