Approximate level of required knowledge: Java Syntax quest and some Java Core.
At the end of the first CodeGym 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 is cast to String
without problems.
int x = 5;
String text = "X=" + x;
Also, those who have already studied up to level 10 of the Java Syntax quest know that it is impossible to cast 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's better to do this with a parseInt
class method Integer
. The method parseInt
must convert String
to int
and throws an exception NumberFormatException
if the string cannot be converted to int
.
Example
The main line that converts a string to an integer:
int i = Integer.parseInt (myString);
If the string denoted by variable myString
is a valid integer, such as "1", "200", Java will quietly convert it to the primitive data type int
. If for some reason this fails, this action can throw an exception NumberFormatException
, so to make the program work correctly for any line, we need a little more code. A program that demonstrates the conversion method Java String
to int
, controls for the 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 to a number just won't work. In our example, this string is the name fred. You can talk about codes in which letters are written in the computer, but, technically speaking, fred is not a number at all, and it is better to leave it as a string. Our program is organized so that when 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. So we have shown it to you. Since such a topic has come up, here are a few “hints” for you 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 a method valueOf ()
on the class Integer
instead of a method parseInt ()
.
- If you need to convert strings to additional Java primitive fields, use methods like this
Long.parseLong ()
one.
Answered by: Alice Watson
GO TO FULL VERSION