Thinking in Java Fourth Edition Bruce Eckel Chapter 2 Exercise 14

Exercise 14: Write a method that takes two String arguments and uses all the boolean comparisons to compare the two Strings and print the results. For the == and !=, also perform the equals( ) test. In main( ), call your method with some different String objects.

Solution:

public class StringCompare
{  
    static void f(boolean b)
    {
        if(b == true)
        {
            System.out.println(true);
        }
        else
        {
            System.out.println(false);
        }
    }
    static void stringTest(String s, String t)
    {
        f(s == t);
        f(s.equals(t));
        f(t.equals(s));
        f(s != t);
    }  
    public static void main(String[] args)
    {
        String s = "one", t = "two";
        StringCompare.stringTest(s, t);    
    }
}

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *