Compare strings

This example will show how to compare strings in java. Java String comparison is a very common question among beginner java programmers.

Compare strings .equals

@Test
public void compare_strings_in_java () {
    
    boolean stringEquals = "test".equals("test");
    
    assertTrue(stringEquals);
}

Compare strings compiler interned

@Test
public void compare_strings_compiler_interned_in_java () {

    String leftString = "test";
    String rightString = "test";
    
    if (leftString == rightString) {
        logger.info("yes these are true b/c literals are interned by compiler");
    }
    
    assertEquals(leftString, rightString);
}

Compare concatenated‎ strings

@Test
public void compare_strings_concatenation_in_java () {
    
    String leftString = "test";
    String rightString = "te" + "st";

    if (leftString == rightString) {
        logger.info("yes these are true b/c concatenation "
                + "of string literals happens at compile "
                + "time resulting in same objects");
    }
    
    assertEquals(leftString, rightString);
}

Compare strings ignoring case

@Test
public void compare_strings_ignoring_case_in_java () {
    
    boolean stringEquals = "test".equalsIgnoreCase("TEST");
    
    assertTrue(stringEquals);
}

Compare null strings

@Test
public void compare_strings_with_nulls_in_java () {
    String leftString = null;
    String rightString = null;
    
    if (leftString == rightString) {
        logger.info("yes");
    }
    
    assertEquals(leftString, rightString);
}

Compare null strings w/ exception

@SuppressWarnings("null")
@Test(expected=NullPointerException.class)
public void compare_strings_with_nulls_with_exception_in_java () {
    String leftString = null;
    String rightString = null;
    
    logger.info("strings are objects so if "
            + "access a method on a null object, null pointer exception");
    
    leftString.equals(rightString);
}