From f499f86cc89eb9277625183532782cc2a3cfc384 Mon Sep 17 00:00:00 2001 From: fpistritto Date: Thu, 9 Nov 2017 04:13:42 +0100 Subject: [PATCH] BAEL-1272: Java String Pool (#2952) * Add StringPool unit tests * Refactor tests to use AssertJ instead of JUnit asserts --- .../stringpool/StringPoolUnitTest.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java b/core-java/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java new file mode 100644 index 0000000000..4bbf63f87e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.stringpool; + +import org.junit.Test; +import static org.assertj.core.api.Assertions.*; + +public class StringPoolUnitTest { + + @Test + public void whenCreatingConstantStrings_thenTheirAddressesAreEqual() { + String constantString1 = "Baeldung"; + String constantString2 = "Baeldung"; + + assertThat(constantString1).isSameAs(constantString2); + } + + @Test + public void whenCreatingStringsWithTheNewOperator_thenTheirAddressesAreDifferent() { + String newString1 = new String("Baeldung"); + String newString2 = new String("Baeldung"); + + assertThat(newString1).isNotSameAs(newString2); + } + + @Test + public void whenComparingConstantAndNewStrings_thenTheirAddressesAreDifferent() { + String constantString = "Baeldung"; + String newString = new String("Baeldung"); + + assertThat(constantString).isNotSameAs(newString); + } + + @Test + public void whenInterningAStringWithIdenticalValueToAnother_thenTheirAddressesAreEqual() { + String constantString = "interned Baeldung"; + String newString = new String("interned Baeldung"); + + assertThat(constantString).isNotSameAs(newString); + + String internedString = newString.intern(); + + assertThat(constantString).isSameAs(internedString); + } +}