-
Notifications
You must be signed in to change notification settings - Fork 472
Expand file tree
/
Copy pathStringToInt.java
More file actions
26 lines (21 loc) · 506 Bytes
/
Copy pathStringToInt.java
File metadata and controls
26 lines (21 loc) · 506 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Java - Convert String to an Int
class StringToInt {
public static void main(String[] args) {
String s = "222";
int i;
Integer integer;
// returns an int
i = Integer.parseInt(s);
System.out.println(i + 1);
// returns an Integer
integer = Integer.valueOf(s);
System.out.println(integer + 2);
// Best Practice: safely returns an Integer
try {
integer = Integer.valueOf(s);
} catch (NumberFormatException e) {
integer = 0;
}
System.out.println(integer + 3);
}
}