Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 201 ยท Strings

Comparing and Converting Strings

Compare Java strings with equals, equalsIgnoreCase, compareTo and Collator, and convert between strings, numbers, char arrays and byte arrays safely.

Two jobs come up constantly when you work with text: deciding whether two strings are "the same" (or which comes first), and converting between strings and other types such as numbers, character arrays and bytes. Both look simple, and both hide traps: == that works in tests and fails in production, sorting that puts "Zebra" before "apple", and null that turns into the text "null" or crashes your program, depending on which method you picked.

This lesson collects the tools and the rules. You met equals and compareTo briefly in Strings; here you'll go further.

Equality: equals, not ==

== on objects asks "are these the same object?" equals asks "do they contain the same characters?" For strings you almost always mean the second:

Java equals versus ==

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The text read from input is a new String object, so == is false even though the characters match. Two identical literals in the same program often are the same object, thanks to the string pool, which is exactly why == bugs hide in simple tests. Use equals every time.

Comparing safely when null is possible

Calling a method on null throws NullPointerException. Two common ways to avoid it:

Java
String status = null;

"active".equals(status);           // false, never throws: literal first
Objects.equals(status, "active");  // false, handles null on either side
status.equals("active");           // NullPointerException!

Objects.equals(a, b) returns true when both are null, false when only one is, and otherwise calls a.equals(b).

Other equality checks

  • equalsIgnoreCase compares character by character, ignoring case. It's fine for ASCII codes such as "yes" or "GET".
  • contentEquals(CharSequence) compares a String with a StringBuilder or any other CharSequence.
  • regionMatches(ignoreCase, offset, other, otherOffset, length) compares just a slice of two strings.
  • isEmpty() checks for length 0; isBlank() also treats whitespace-only strings as empty.

Case-insensitive comparison of human language is harder than it looks. Some letters change length when uppercased (the German sharp s becomes two letters), and the Turkish dotted and dotless i break naive rules. For words people will read, use a Collator (below). The Locales and Internationalization lesson covers the Turkish i in detail.

Ordering: compareTo

a.compareTo(b) returns an int:

  • negative if a comes before b,
  • zero if they are equal,
  • positive if a comes after b.

It compares the strings character by character using their UTF-16 numeric values. At the first difference it returns the difference between those two characters. If one string is a prefix of the other, it returns the difference in lengths. Only rely on the sign, never on the exact number.

Java compareTo and its surprises

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Two results deserve attention:

  • Uppercase sorts before lowercase. 'Z' is 90 and 'a' is 97, so "Zebra" comes before "apple". String.CASE_INSENSITIVE_ORDER and compareToIgnoreCase fix that.
  • Digits compare as characters, not numbers. "10" comes before "9" because '1' is less than '9'. If you sort file names like img10.png and img9.png, you need a "natural" comparator or to parse the numbers first.

compareTo is what makes String implement Comparable<String>, so Collections.sort, TreeMap and TreeSet use it by default. You'll write your own comparators in Sorting with Comparable and Comparator.

Language-aware sorting with Collator

compareTo knows numbers, not languages. Accented letters such as รฉ have large code values, so a plain sort puts "รฉclair" after "zebra", and different languages even disagree on where letters belong (Swedish sorts รค after z; German sorts it with a).

java.text.Collator compares strings by the rules of a Locale. It also has a strength setting that decides which differences count:

Strength Differences that count Example treated as equal
PRIMARY Base letters only resume, Resume, rรฉsumรฉ
SECONDARY Letters and accents resume, Resume
TERTIARY (default) Letters, accents and case none of them
Java Collator versus compareTo

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

compareTo puts "Zebra" first (uppercase letters have smaller codes) and "รฉclair" last (รฉ has a larger code than any plain letter). The collator gives the order a reader expects: "รฉclair" sits where an e-word belongs, and "zebra" comes just before "Zebra", because at the default strength case only breaks ties. The last three lines show strength at work: PRIMARY ignores both the accents and the capital R, while SECONDARY still sees the accents but not the case.

A Collator implements Comparator<Object>, so you can pass it straight to List.sort, TreeMap or a stream's sorted. Creating one is relatively expensive, so create it once and reuse it. It is not thread-safe while you change its settings; give each thread its own or don't modify a shared one.

Converting strings to numbers

The wrapper classes parse text into numbers. Each parseXxx method returns a primitive; each valueOf returns the wrapper object (see Wrapper Classes and Autoboxing):

Java Parsing numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Rules to remember:

  • Integer.parseInt doesn't trim spaces and doesn't accept decimals or thousands separators: "8 ", "3.0" and "1,000" all throw NumberFormatException. Double.parseDouble, by contrast, does ignore surrounding whitespace.
  • Values outside the type's range also throw: Integer.parseInt("3000000000") fails, so use Long.parseLong.
  • Boolean.parseBoolean never throws: anything other than "true" (in any case) is false.
  • For money and exact decimals, parse with new BigDecimal(text) instead of double (see BigInteger and BigDecimal).
  • For user-facing numbers written with a locale's separators, such as 1.234,5, use NumberFormat from Formatting Strings.

Converting values to strings

There are four common ways to turn a value into text, and they treat null differently:

Java valueOf, toString, concatenation and Objects.toString

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Expression With null Notes
String.valueOf(x) "null" Overloaded for every primitive; never throws for an Object
x.toString() Throws NullPointerException Only on objects
"" + x "null" Works, but reads like a trick; fine inside larger concatenations
Objects.toString(x, "default") "default" Best when you want a fallback

String.valueOf(null) with a literal null does not return "null". The compiler picks the most specific overload, valueOf(char[]), which throws NullPointerException. A variable typed as Object (like missing above) uses valueOf(Object) and is safe.

Strings, char arrays and byte arrays

A String can turn into a char[] (one element per UTF-16 code unit) and back. That's useful when you want to modify characters in place or sort them:

Java char[] and byte[] conversions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Bytes are where character sets matter. The same text becomes different bytes in UTF-8 and ISO-8859-1, and decoding bytes with the wrong charset gives garbled text (here, cafรƒยฉ: 5 characters instead of 4). Always name the charset explicitly with StandardCharsets, both when encoding (getBytes) and decoding (new String(bytes, charset)). The full story is in Character Sets and Encoding.

Two more conversions you'll use often:

  • A single char to a String: String.valueOf(ch) or Character.toString(ch).
  • A digit character to its number: ch - '0' for '0' to '9', or Character.digit(ch, 10), which returns -1 for non-digits.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? String a = IO.readln(); IO.println(a == "hi"); when the user types hi

    The input is a new String object, so == compares two different references and gives false. Use a.equals("hi") to compare content.
  2. 2. In what order does Collections.sort put the list ["b", "C", "a"]?

    The natural order uses UTF-16 values, and uppercase letters (65 to 90) come before lowercase ones (97 to 122). Use String.CASE_INSENSITIVE_ORDER or a Collator for the friendly order.
  3. 3. What does Integer.parseInt(" 12") do?

    parseInt does not ignore whitespace, so the leading space makes it fail. Call strip() first.
  4. 4. Given Object o = null;, which expression throws an exception?

    Calling a method on a null reference throws NullPointerException. The other three handle null and return "null", "xnull" and "?".
  5. 5. Which tool should sort a list of people's names for display in a French app?

    A Collator applies the language's sorting rules, placing accented letters next to their base letters. compareTo and CASE_INSENSITIVE_ORDER only compare UTF-16 values.

Summary

  • Compare content with equals, never ==; put the literal first or use Objects.equals when null is possible.
  • compareTo returns a negative, zero or positive number based on UTF-16 values: uppercase sorts before lowercase and "10" before "9".
  • String.CASE_INSENSITIVE_ORDER and compareToIgnoreCase ignore case; Collator sorts by a language's rules with a chosen strength.
  • Integer.parseInt, Double.parseDouble and friends parse text and throw NumberFormatException on bad input; parseInt doesn't trim.
  • String.valueOf and concatenation turn null into "null", toString() on null throws, and Objects.toString(x, default) gives a fallback.
  • toCharArray/new String(char[]) convert to and from characters; always pass a StandardCharsets value when converting to and from bytes.

Next: if, else if and else, where you'll start making decisions in your programs.