+5 votes
60 views
in Tips & Tricks by (242k points)
reopened
Java: convert string to integer

1 Answer

+3 votes
by (1.6m points)
 
Best answer

Converting a string to the data type int
Convert a string to an integer object

Wondering how to convert a string to int? Our step-by-step guide shows you how to do it!

image image

In Java there are a large number of inputs and values ​​that have to be converted into an integer in order to produce an output. If you want to convert a string (i.e. a variable in which a character string is stored) into an integer, take a look at our instructions.

There are two options for this process:

Converting a string to the data type int

You use the static method for this form of conversion Integer.parseInt(String s) . ParseInt returns a simple int entity. The string may only consist of digits and only contain a plus or minus sign at the beginning.

Example:

Integer.parseInt (“10“);
Integer.parseInt (“+ 10“);
Integer.parseInt (“10.5“);
Integer.parseInt (“10“);
// correct
// correct
// error, period is not allowed
// error, spaces are not allowed
Integer.parseInt(“10“);
Integer.parseInt(“+10“);
Integer.parseInt(“10.5“);
Integer.parseInt(“ 10“);
//korrekt
//korrekt
//Fehler, Punkt ist nicht erlaubt
//Fehler, Leerzeichen sind nicht erlaubt

If a string contains illegal characters, an exception is thrown. There are no spaces , separators , points or commas allowed..

Convert a string to an integer object

For this conversion you use the static mathode Integer.valueOf(String s ). A static method is a method that has a class definition .
A new instance of is java.lang.integer returned.

Example:

Integer i = Integer.valueOf (“10“);
Integer i = Integer.valueOf(“10“);

...