From d6be7a2528828a51449b392ead093eecd6845e9d Mon Sep 17 00:00:00 2001 From: Kayvan Tehrani Date: Sat, 23 Oct 2021 20:16:51 +0330 Subject: [PATCH] resolving (BAEL-5148) Get String Character by Index in Java (#11340) * resolving (BAEL-5148) Get String Character by Index in Java * changing method name from *_thenCorrect() to *_thenSuccess() * reverted README changes according to the editor suggestion * extra snippet removed inorder to comply with the article edits --- .../stringapi/StringCharAtUnitTest.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 core-java-modules/core-java-string-apis/src/test/java/com/baeldung/stringapi/StringCharAtUnitTest.java diff --git a/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/stringapi/StringCharAtUnitTest.java b/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/stringapi/StringCharAtUnitTest.java new file mode 100644 index 0000000000..5d31b337ef --- /dev/null +++ b/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/stringapi/StringCharAtUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.stringapi; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class StringCharAtUnitTest { + @Test + public void whenCallCharAt_thenSuccess() { + String sample = "abcdefg"; + assertEquals('d', sample.charAt(3)); + } + + @Test() + public void whenCharAtNonExist_thenIndexOutOfBoundsExceptionThrown() { + String sample = "abcdefg"; + assertThrows(IndexOutOfBoundsException.class, () -> sample.charAt(-1)); + assertThrows(IndexOutOfBoundsException.class, () -> sample.charAt(sample.length())); + } + + @Test + public void whenCallCharAt_thenReturnString() { + String sample = "abcdefg"; + assertEquals("a", Character.toString(sample.charAt(0))); + assertEquals("a", String.valueOf(sample.charAt(0))); + } + +} \ No newline at end of file