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
- Why can’t numeric comparison operators be used to compare strings in C?ComputerScienceOne · Comparing Strings and Characters
- How can comparison operators be used with characters in C?ComputerScienceOne · Comparing Strings and Characters
- Why can’t numerical comparison operators be used to compare strings in C?ComputerScienceOne · Comparisons
- Why can numeric comparison operators not be used to compare strings in C?ComputerScienceOne · Order of Precedence
- What is the order of precedence and associativity of common C operators?ComputerScienceOne · Comparing Strings and Characters