Concept
Why can’t numeric comparison operators be used to compare strings in Java?
ComputerScienceOne / Comparing Strings and Characters
"Numeric comparison operators cannot be used to compare strings in Java. For example, we could not code something like (\"aardvark\" < \"zebra\"). The Java compiler would not allow you to do this because the comparison operator is for numeric types only. However, the following code would compile and run:\n\n1 String s = \"aardvark\";\n\n2 String t = \"zebra\";\n\n3 boolean b = (s == t);\n\nbut it wouldn’t necessarily give you what you want. To understand why this is okay, recall that a String is an object; the s and t variables are references to that object in memory. When we use the equality comparison, == we’re asking if s and t are the same memory address. In this case, likely they are not and so the result is false. However, similar code,\n\n1 String s = new String(\"liger\");\n\n2 String t = new String(\"liger\");\n\n3 boolean b = (s == t);"
Related Ideas
- How do you compare strings in Java?ComputerScienceOne · Comparisons
- How can you compare String values in Java?ComputerScienceOne · Tokenizing
- Why can’t numeric comparison operators be used to compare strings in C?ComputerScienceOne · Comparing Strings and Characters
- Why can’t numerical comparison operators be used to compare strings in C?ComputerScienceOne · Comparisons
- What is the difference between Comparable and Comparator in Java?ComputerScienceOne · Comparators
- How does a Comparator determine the order of two elements?ComputerScienceOne · Comparators
- How does strcmp() compare the contents of two strings in C?ComputerScienceOne · Comparisons
- How is operator precedence determined in Java?ComputerScienceOne · Order of Precedence