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.
Feed/

Why can’t numeric comparison operators be used to compare strings in Java?

No cover

Channel

Computer science one

1 page

"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);"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.