Skip to content

Commit f1516e0

Browse files
authored
Merge pull request eugenp#622 from eugenp/grzegorz_string_to_int
Add code examples for String to int mini-article
2 parents ecacc8d + 6f38d0b commit f1516e0

1 file changed

Lines changed: 63 additions & 0 deletions

File tree

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package com.baeldung;
2+
3+
import com.google.common.primitives.Ints;
4+
import org.junit.Test;
5+
6+
import static org.assertj.core.api.Assertions.assertThat;
7+
8+
public class StringToIntTest {
9+
10+
@Test
11+
public void givenString_shouldConvertToInt1() throws Exception {
12+
String givenString = "42";
13+
14+
int result = Integer.parseInt(givenString);
15+
16+
assertThat(result).isEqualTo(42);
17+
}
18+
19+
20+
@Test
21+
public void givenString_shouldConvertToInt2() throws Exception {
22+
String givenString = "42";
23+
24+
Integer result = Integer.valueOf(givenString);
25+
26+
assertThat(result).isEqualTo(42);
27+
}
28+
29+
@Test
30+
public void givenString_shouldConvertToInt3() throws Exception {
31+
String givenString = "42";
32+
33+
Integer result = new Integer(givenString);
34+
35+
assertThat(result).isEqualTo(42);
36+
}
37+
38+
@Test
39+
public void givenString_shouldConvertToInt4() throws Exception {
40+
String givenString = "42";
41+
42+
int result = Integer.decode(givenString);
43+
44+
assertThat(result).isEqualTo(42);
45+
}
46+
47+
@Test
48+
public void givenString_shouldConvertToInt5() throws Exception {
49+
String givenString = "42";
50+
51+
Integer result = Ints.tryParse(givenString);
52+
53+
assertThat(result).isEqualTo(42);
54+
}
55+
56+
@Test(expected = NumberFormatException.class)
57+
public void givenInvalidInput_shouldThrow() throws Exception {
58+
String givenString = "nan";
59+
60+
int result = Integer.parseInt(givenString);
61+
}
62+
63+
}

0 commit comments

Comments
 (0)