Bifalgorithm post · Computer science one · Comparing Strings and Characters
Why can’t numeric comparison operators be used to compare strings in Java?
Why can’t numeric comparison operators be used to compare strings in Java? (Computer science one · Comparing Strings and Characters) — "Numeric comparison oper…
Ideas in this flowchart
- Java uses different rules for numeric and String comparisons.
- Numeric comparison operators are restricted to numeric types.
- An expression such as ("aardvark" < "zebra") is rejected by the Java compiler.
- The equality operator == can compile when used with String variables.
- A String is an object, and String variables are references to objects in memory.
- Using == asks whether two String references point to the same memory address.
- For s = "aardvark" and t = "zebra", the references are likely different, so the result is false.
- The code can create two String objects with new String("liger").
- The two constructed objects contain the same text but are separate object references.