Approximate level of required knowledge: Java Syntax quest and a little Java Core.
At the end of the first JavaRush quest we learn about type conversion. In the level 10 lectures, you could see that converting int
to String
is very simple, and in general, almost any primitive type can be converted to String
without problems.
int x = 5;
String text = "X=" + x;
Also, those who have already completed level 10 of the Java Syntax quest know that it is impossible to convert a reference to a number to a reference to a string. So what's the best way to convert a string to a primitive integer? It is better to do this using the parseInt
class method Integer
. The method parseInt
must convert String
to int
and throws an exception NumberFormatException
if the string cannot be converted to type int
.
Example
Basic line that converts a string to an integer:
int i = Integer.parseInt (myString);
If the string denoted by the variable myString
is a valid integer, such as "1", "200", Java will quietly convert it to a primitive data type int
. If for some reason this fails, such an action may throw an exception NumberFormatException
, so in order for the program to work correctly for any string, we need a little more code. A program that demonstrates the method of converting Java String
to int
, control for possible NumberFormatException
:
public class JavaStringToIntExample
{
public static void main (String[] args)
{
String s = "100";
try
{
int i = Integer.parseInt(s.trim());
System.out.println("int i = " + i);
}
catch (NumberFormatException nfe)
{
System.out.println("NumberFormatException: " + nfe.getMessage());
}
}
Discussion
When you study the example above, you will see that the method Integer.parseInt (s.trim ())
is used to turn a string s
into an integer i
, and this happens in the following line of code:
int i = Integer.parseInt (s.trim ())
But sometimes converting a string into a number just won’t work. In our example, such a string is the name fred. We can talk about codes in which letters are written on a computer, but, formally speaking, fred is not a number, and it is better to leave it as a string. Our program is designed so that if you try to convert "fred" to a number, the process Integer parseInt
will throw an exception NumberFormatException
, which you must handle in a block try / catch
. In this case you don't have to use the trim ()
class method String
, but in real programming you should use it. So we showed it to you. Since this topic has come up, here are some “hints” on the topic of classes String
and Integer
:
Integer.toString (int i)
used to convert int
to Java strings.
- If you want to convert an object
String
to an object Integer
(rather than a primitive class int
), use the valueOf ()
on-class method Integer
instead of the parseInt ()
.
- If you need to convert strings to additional primitive Java fields, use methods like this
Long.parseLong ()
one.
Answered by: Alice Watson
GO TO FULL VERSION