Skip to content

Beginner · Arrays and strings · topic 13 of 60 · 30 min

Strings in depth

Explanation

A String is an immutable object: methods like toUpperCase return a new String. String literals are kept in a shared string pool, which is why == sometimes seems to work, but == compares references, so always compare text with equals or equalsIgnoreCase. Key methods: length, charAt, substring (end exclusive), indexOf, contains, split, strip, replace and isBlank.

Strings are objects, and immutable

String is a class in java.lang. A String object never changes after it is created; it is immutable. Every "change" (toUpperCase, replace, concat, trim) creates a new String and leaves the old one as it was. Immutability makes Strings safe to share between threads and to use as map keys.

java
String name = "asha";
name.toUpperCase();              // result thrown away
System.out.println(name);        // asha
name = name.toUpperCase();       // keep the new String
System.out.println(name);        // ASHA

== versus equals: the most famous Java trap

== on objects checks whether two references point to the SAME object. equals checks whether the TEXT is the same. Java keeps string literals in a string pool: identical literals in your code share one object, so "a" == "a" is true. But strings created at run time (new String, user input, concatenation of variables, substring) are new objects.

java
String a = "Pune";
String b = "Pune";                 // same pooled literal
String c = new String("Pune");     // a new object
String d = "Pu" + "ne";            // compile-time constant: pooled
String part = "Pu";
String e = part + "ne";            // built at run time: new object

System.out.println(a == b);        // true  (same pool object)
System.out.println(a == c);        // false (different objects)
System.out.println(a.equals(c));   // true  (same text)
System.out.println(a == d);        // true
System.out.println(a == e);        // false
System.out.println(a.equals(e));   // true
Careful: Always compare String contents with equals (or equalsIgnoreCase). Code like if (input == "yes") may pass a quick test with literals and then fail with real user input. To avoid a NullPointerException when the variable may be null, put the literal first: "yes".equals(input).

Everyday methods

MethodExampleResult
length()"Kolkata".length()7
charAt(i)"Kolkata".charAt(0)'K'
substring(a, b)"Kolkata".substring(0, 4)"Kolk" (b not included)
indexOf(s)"banana".indexOf("na")2 (or -1)
contains(s)"order-55".contains("55")true
startsWith / endsWith"bill.pdf".endsWith(".pdf")true
toUpperCase / toLowerCase"upi".toUpperCase()"UPI"
strip() / trim()" hi ".strip()"hi"
replace(a, b)"9-8-7".replace("-", "")"987" (all occurrences)
split(regex)"a,b,c".split(",")["a", "b", "c"]
isEmpty / isBlank" ".isBlank()true (Java 11+)
String.joinString.join("-", "a", "b")"a-b"
compareTo"apple".compareTo("banana")negative (comes first)

Note: replace replaces ALL occurrences of the text (it is not regex-based); replaceAll and split take regular expressions, so a literal dot is written "\\." in Java source (the regex \. inside a Java string).

Walking through characters

java
String pan = "ABCDE1234F";
int digits = 0;
for (int i = 0; i < pan.length(); i++) {
    if (Character.isDigit(pan.charAt(i))) digits++;
}
System.out.println(digits);   // 4
Think of it like this: An immutable String is like a printed ticket. You cannot edit the printed text; if the name is wrong, the counter prints a NEW ticket and you throw the old one away. == asks "is this the same piece of paper?", while equals asks "does it say the same thing?".
Tip: split with a single space breaks on extra spaces ("a b".split(" ") gives an empty string in the middle). Use split("\\s+") after strip() to split on any run of spaces.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Strings in depth · 1/6

Strings

In this lesson you will work with Java Strings and avoid their famous traps.

Prefer a video by a teacher? Find free videos on “java string methods equals vs == string pool immutable” on YouTube ↗

In real life: Validating a PAN number

A tax-filing website checks that a PAN has the right shape before calling the government verification API: 10 characters, five letters, four digits, one letter. This uses length, charAt and Character methods (a regex can do the same in one line).

java
static boolean looksLikePan(String pan) {
    if (pan == null || pan.length() != 10) return false;
    for (int i = 0; i < 10; i++) {
        char ch = pan.charAt(i);
        boolean ok = (i < 5 || i == 9) ? Character.isUpperCase(ch) : Character.isDigit(ch);
        if (!ok) return false;
    }
    return true;
}
// looksLikePan("ABCDE1234F") → true, looksLikePan("ABCD12345F") → false

Practice (0/3 done)

Task 1 · Question

What does this print? String s = "hello"; s.toUpperCase(); s.concat(" world"); System.out.println(s);

Task 2 · Question

What does this print? String x = "ab"; String y = "a"; String z = y + "b"; System.out.println((x == z) + " " + x.equals(z));

Task 3 · Practice

Write static String initials(String fullName) that returns the upper-case initials of every word, ignoring extra spaces: initials(" ravi kumar singh ") returns "RKS". Also write static boolean isPalindrome(String s) that ignores case and spaces ("Nitin" → true).

Quick quiz

Question 1

1.How should you compare two Strings for equal text?

Question 2

2."Bengaluru".substring(3, 6) is…

Question 3

3.Why write "yes".equals(input) instead of input.equals("yes")?

Question 4

4."a.b.c".split(".") returns an array of length…

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

How should you compare two Strings for equal text?

Answer: a.equals(b)

equals compares content.

"Bengaluru".substring(3, 6) is…

Answer: "gal"

Indexes 3, 4, 5: g, a, l.

Why write "yes".equals(input) instead of input.equals("yes")?

Answer: It avoids a NullPointerException when input is null

Calling equals on a null reference throws; the literal is never null.

"a.b.c".split(".") returns an array of length…

Answer: 0

split takes a regex; "." matches every character, and trailing empty strings are removed, leaving an empty array. Use split("\\.").

let s = 'hi'; s.toUpperCase(); console.log(s); What is printed?Related

Answer: 'hi'

Strings are immutable; the result of toUpperCase was thrown away.

From Strings and template literals

Which gives the last character of the string text?Related

Answer: text.at(-1)

at(-1) counts from the end. text[-1] is undefined, there is no last() method, and slice(0, 1) gives the first character.

From Strings in depth

What does immutable mean for strings?Related

Answer: Once made, a string's characters cannot change; methods return new strings

Every "change" creates a new string.

From Strings: methods, interpolation, verbatim and raw strings

How many bytes does "UPI" occupy as a string literal?Related

Answer: 4

3 letters + the terminator.

From Strings are char arrays

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 2 more topics in “Arrays and strings” before its exam: StringBuilder and formatting, Wrapper classes and autoboxing.
  2. Module 3 exam: Arrays and strings · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Classes and objects. 60 topics left in the course before the final exam.

← Previous: Two-dimensional arrays and array algorithms