From d26bdb76218acdd77f0f5880e2f447627604fd78 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 21 Aug 2016 11:32:16 +0200 Subject: [PATCH 1/2] Add code examples for String to int mini-article --- .../java/com/baeldung/StringToIntTest.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 core-java-8/src/test/java/com/baeldung/StringToIntTest.java diff --git a/core-java-8/src/test/java/com/baeldung/StringToIntTest.java b/core-java-8/src/test/java/com/baeldung/StringToIntTest.java new file mode 100644 index 0000000000..a683f40de4 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/StringToIntTest.java @@ -0,0 +1,53 @@ +package com.baeldung; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class StringToIntTest { + + @Test + public void givenString_shouldConvertToInt1() throws Exception { + String givenString = "42"; + + int result = Integer.parseInt(givenString); + + assertThat(result).isEqualTo(42); + } + + + @Test + public void givenString_shouldConvertToInt2() throws Exception { + String givenString = "42"; + + Integer result = Integer.valueOf(givenString); + + assertThat(result).isEqualTo(42); + } + + @Test + public void givenString_shouldConvertToInt3() throws Exception { + String givenString = "42"; + + Integer result = new Integer(givenString); + + assertThat(result).isEqualTo(42); + } + + @Test + public void givenString_shouldConvertToInt4() throws Exception { + String givenString = "42"; + + int result = Integer.decode(givenString); + + assertThat(result).isEqualTo(42); + } + + @Test(expected = NumberFormatException.class) + public void givenInvalidInput_shouldThrow() throws Exception { + String givenString = "nan"; + + int result = Integer.parseInt(givenString); + } + +} From 6f38d0b12e2852fe12d4aef841e7591f7581836a Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 22 Aug 2016 16:28:38 +0200 Subject: [PATCH 2/2] Add Guava example --- .../src/test/java/com/baeldung/StringToIntTest.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/core-java-8/src/test/java/com/baeldung/StringToIntTest.java b/core-java-8/src/test/java/com/baeldung/StringToIntTest.java index a683f40de4..9f1c611e04 100644 --- a/core-java-8/src/test/java/com/baeldung/StringToIntTest.java +++ b/core-java-8/src/test/java/com/baeldung/StringToIntTest.java @@ -1,5 +1,6 @@ package com.baeldung; +import com.google.common.primitives.Ints; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -43,6 +44,15 @@ public class StringToIntTest { assertThat(result).isEqualTo(42); } + @Test + public void givenString_shouldConvertToInt5() throws Exception { + String givenString = "42"; + + Integer result = Ints.tryParse(givenString); + + assertThat(result).isEqualTo(42); + } + @Test(expected = NumberFormatException.class) public void givenInvalidInput_shouldThrow() throws Exception { String givenString = "nan";