Skip to content

String Tools & Equality

The Course
•
20 min study

String methods let you inspect or transform text. trim() returns text without leading and trailing ordinary whitespace; isEmpty() tests whether its length is zero. toLowerCase() and toUpperCase() return case-converted text. A String's contents do not change in place: store the returned value if you want to use it later. We use simple English text in these examples.

A String variable refers to a text object. Two variables can refer to the same object, or to separate objects with equal text. Think of two labels attached to one notebook versus two notebooks containing the same words.

Use equals to compare String contents. == asks whether both variables refer to the very same object, which is a different question. Java may reuse literal strings, so == can appear to work in one example and then fail with text constructed at runtime. The mistake is the comparison rule, not a random behavior of the input reader.

Choose rules before cleanup

Removing outer spaces can be helpful, but do not silently remove internal spaces or change case unless the task calls for it. A person's topic title can preserve its spelling while an answer comparison deliberately ignores surrounding spaces. Keep the original and cleaned values separate when you need to explain the transformation. Check empty text as well as a normal word.

Store the cleaned result Java
public class Main {
    public static void main(String[] args) {
        String raw = " Java Basics ";
        String clean = raw.trim();

        System.out.println(raw.length());
        System.out.println(clean.length());
        System.out.println(clean);
        System.out.println("   ".trim().isEmpty());
    }
}
Check your prediction
Text
13
11
Java Basics
true

trim returns a result and leaves raw unchanged. Internal space between Java and Basics remains. Blank input consisting of spaces becomes empty after this particular cleanup rule.

In the next example, new String("Java") deliberately makes a separate text object. Ordinary text declarations do not need this extra step; we use it here only to make the difference between identity and contents visible.

Equal contents can be distinct objects Java
public class Main {
    public static void main(String[] args) {
        String literal = "Java";
        String separate = new String("Java");

        System.out.println(literal == separate);
        System.out.println(literal.equals(separate));
    }
}
Check your prediction
Text
false
true

new String deliberately creates a different object for this comparison. The contents are still Java. Do not memorize which strings happen to share identity; use equals when the question is about contents.

charAt(index) returns one char at a zero-based position. A char is a single character value in these English examples; a literal such as 'L' uses single quotes. A String uses double quotes and can hold several characters.

Inspect character positions Java
public class Main {
    public static void main(String[] args) {
        String topic = "Loops";

        System.out.println(topic.charAt(0));
        System.out.println(topic.charAt(topic.length() - 1));
        System.out.println(topic.toLowerCase());
    }
}
Check your prediction
Text
L
s
loops

charAt returns a char at a zero-based position. A char literal uses single quotes, such as 'L'; a String uses double quotes. Empty text has no valid character position, just as an empty array has no element.

A reference can also be null, meaning it refers to no object. This is different from "", which is an actual String with no characters. Calling a method through null fails. Non-null means an actual object is supplied. The following exercise assumes an actual array containing actual Strings, including the wanted value.

Normalize first, then apply the promised comparison

A String operation returns a result; it does not rewrite a variable automatically. Calling title.trim() and discarding the result leaves title referring to its original text. Store the returned value when later logic should use normalized text.

Keep normalization and matching separate. Trimming surrounding spaces says those spaces are irrelevant to your input policy. Ignoring letter case is another decision. The exact-match search exercise deliberately keeps case significant, so "Java" and "java" remain different even though " Java " can be normalized before searching.

A missing String reference is null, while an empty String is a real object with length zero. Check reference presence before calling a method if your contract accepts null. If the contract excludes null, state that restriction clearly instead of pretending an empty-list test demonstrates null safety.

Your turn

Exercise

Find a topic by content

Write containsTopic(String[] topics, String wanted) for non-null arrays containing non-null Strings and a non-null wanted value. Return true if any element equals wanted. Use exact case-sensitive comparison. Test Loops present, Missing absent and an empty array. The normal main prints true.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        System.out.println(containsTopic(new String[] {"Java", "Loops"}, "Loops"));
    }

    static boolean containsTopic(String[] topics, String wanted) {
        return false; // Replace the placeholder.
    }
}
Hint 1: the idea

A match can finish the search immediately; no match is known only after every element has been checked.

Hint 2: a first step

Use equals on each current topic. Put the final false return after the loop, not in the first nonmatching iteration.

Show one solution
Java
public class Main {
    public static void main(String[] args) {
        System.out.println(containsTopic(new String[] {"Java", "Loops"}, "Loops"));
    }

    static boolean containsTopic(String[] topics, String wanted) {
        for (String topic : topics) {
            if (topic.equals(wanted)) {
                return true;
            }
        }

        return false;
    }
}
Text
true

return true sits inside the if, so it fires on the first match. The return false comes after the loop because "not found" is only known once every element has been checked. equals is case-sensitive, so "java" does not match "Java".

Change it and explain

Show that the first element can fail to match while the second succeeds. This case catches an early false return inside the loop. Explain why a search that returns true for every nonempty list would still pass one poorly chosen test.

Day 6 will teach you to reject missing text before calling String methods. For now, the exercise supplies actual Strings so you can focus on content comparison.

Was this article helpful?

Your response is saved on this device.