From d085dae380f3dc8398d936750a5352926b90fdbb Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Sat, 29 Apr 2023 01:06:34 +0200 Subject: [PATCH] [BAEL-6434_charAndString] Difference Between "char" and "String" (#13907) --- ...ifferenceBetweenCharAndStringUnitTest.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 core-java-modules/core-java-char/src/test/java/com/baeldung/charandstring/DifferenceBetweenCharAndStringUnitTest.java diff --git a/core-java-modules/core-java-char/src/test/java/com/baeldung/charandstring/DifferenceBetweenCharAndStringUnitTest.java b/core-java-modules/core-java-char/src/test/java/com/baeldung/charandstring/DifferenceBetweenCharAndStringUnitTest.java new file mode 100644 index 0000000000..b4e1da6d71 --- /dev/null +++ b/core-java-modules/core-java-char/src/test/java/com/baeldung/charandstring/DifferenceBetweenCharAndStringUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.charandstring; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; + +import org.junit.jupiter.api.Test; + +public class DifferenceBetweenCharAndStringUnitTest { + + @Test + void whenPlusTwoChars_thenGetSumAsInteger() { + char h = 'H'; // the value is 72 + char i = 'i'; // the value is 105 + assertEquals(177, h + i); + assertInstanceOf(Integer.class, h + i); + } + + @Test + void whenPlusTwoStrings_thenConcatenateThem() { + String i = "i"; + String h = "H"; + assertEquals("Hi", h + i); + } + + @Test + void whenPlusCharsAndStrings_thenGetExpectedValues() { + char c = 'C'; + assertEquals("C", "" + c); + + char h = 'H'; // the value is 72 + char i = 'i'; // the value is 105 + assertEquals("Hi", "" + h + i); + assertEquals("Hi", h + "" + i); + assertEquals("177", h + i + ""); + } + + @Test + void whenStringChars_thenGetCharArray() { + char h = 'h'; + char e = 'e'; + char l = 'l'; + char o = 'o'; + + String hello = "hello"; + assertEquals(h, hello.charAt(0)); + assertEquals(e, hello.charAt(1)); + assertEquals(l, hello.charAt(2)); + assertEquals(l, hello.charAt(3)); + assertEquals(o, hello.charAt(4)); + + char[] chars = new char[] { h, e, l, l, o }; + char[] charsFromString = hello.toCharArray(); + assertArrayEquals(chars, charsFromString); + } +} \ No newline at end of file