compare 2 strings java code example

Example 1: java how to compare strings

System.out.println("hey".equals("hey")); //prints true

/*
	always use .equals() instead of ==,
    because == does the compare the string content but
    loosely where the string is stored in.
*/

Example 2: string compare java ==

// These two have the same value
new String("test").equals("test") // --> true 

// ... but they are not the same object
new String("test") == "test" // --> false 

// ... neither are these
new String("test") == new String("test") // --> false

Example 3: how to compare strings java

if (aName.equals(anotherName))
        { 
            System.out.println(aName + " equals " + anotherName);
        }
        else 
            { 
                System.out.println(aName + " does not equal " +anotherName );
                           
            }

Example 4: string compare java

// These two have the same value
new String("test").equals("test") // --> true 

// ... but they are not the same object
new String("test") == "test" // --> false 

// ... neither are these
new String("test") == new String("test") // --> false

Example 5: how to know if String is the same java

String1.equals(String2)

Example 6: compare two strings java

String string1 = "using equals method";String string2 = "using equals method";        String string3 = "using EQUALS method";String string4 = new String("using equals method"); assertThat(string1.equals(string2)).isTrue();assertThat(string1.equals(string4)).isTrue(); assertThat(string1.equals(null)).isFalse();assertThat(string1.equals(string3)).isFalse();

Tags:

Java Example