Java 17 Recipes
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
Solution
Use the built-in equals(), equalsIgnoreCase(), compareTo(), and compareToIgnoreCase() methods to compare the values contained within the strings. The following is a series of tests using different string-comparison operations. As you can see, various if statements are used to print messages if the comparisons are equal. String one = "one"; String two = "two"; String var1 = "one"; String var2 = "Two"; String pieceone = "o"; String piecetwo = "ne"; // Comparison is equal if (one.equals(var1)){ System.out.println ("String one equals var1 using equals"); } Chapter 3 StringS 82 // Comparison is NOT equal if (one.equals(two)){ System.out.println ("String one equals two using equals"); } // Comparison is NOT equal if (two.equals(var2)){ System.out.println ("String two equals var2 using equals"); } // Comparison is equal, but is not directly comparing String values using == if (one == var1){ System.out.println ("String one equals var1 using =="); } // Comparison is equal if (two.equalsIgnoreCase(var2)){ System.out.println ("String two equals var2 using equalsIgnoreCase"); } String piecedTogether = pieceone + piecetwo; // Comparison is equal if (one.equals(piecedTogether)){ System.out.println("The strings contain the same value using equals"); } // Comparison is NOT equal using == if (one == piecedTogether) { System.out.println("The string contain the same value using == "); } // Comparison is equal if (one.compareTo(var1) == 0){ System.out.println("One is equal to var1 using compareTo()"); } if (one.compareToIgnoreCase(var1) == 0){ System.out.println("One is equal to var1 using compareToIgnoreCase()"); } Chapter 3 StringS 83 Results in the following output. String one equals var1 using equals String one equals var1 using == String two equals var2 using equalsIgnoreCase The Strings contain the same value using equals One is equal to var1 using compareTo() One is equal to var1 using compareToIgnoreCase() Download 3.2 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling