FirstHack Learn
Log in Sign up free
Lessons in this course 0/6 All courses Java Fundamentals

CSE

Progress0 / 6 lessons
  1. 1. JVM, JDK and JRE explained properly
  2. 2. Classes, objects and the main method
  3. 3. Primitives, objects and autoboxing
  4. 4. String immutability and why == fails
  5. 5. Collections: ArrayList and HashMap
  6. 6. Exceptions and try-with-resources

Courses › Java Fundamentals

String immutability and why == fails

The string pool, why concatenation in a loop is slow, and the equals rule.

12 min read · Lesson 4 of 6 · Pro

A String cannot be changed

Once a String object exists, its characters never change. Every method that looks like it edits a string actually returns a new string.

Java
public class Immutable {
    public static void main(String[] args) {
        String s = "hello";
        s.toUpperCase();                 // result thrown away
        System.out.println(s);           // hello

        s = s.toUpperCase();             // now s points at the new object
        System.out.println(s);           // HELLO

        String t = "abc";
        t.concat("def");
        System.out.println(t);           // abc, not abcdef
    }
}
The rest of this lesson is Pro

The free lessons of Java Fundamentals finish what they start — read those first if you have not. This one goes further, and it is part of the paid half.

A pass opens the paid lessons of every course, the mock test papers and the company-wise series. It ends on its own date; nothing renews by itself.

Get a pass — from ₹29 for 7 days

Already bought one? Log in.