3

Why does the string s print "Hello, World" after converting to lower case?

public class Practice {
    public static void main(String[] args){
        String s = "Hello, World";
        s.toLowerCase();
        System.out.println(s);
    }
}
0

2 Answers 2

8

Strings are immutable. You need to re assign the result of String#toLowerCase to the variable:

s = s.toLowerCase();
Sign up to request clarification or add additional context in comments.

Comments

2

Strings are special kind of objects in Java. Java developers deliberately created them to be immutable (for various security and performance reasons).

That means that when you think you change the state of a String object, actually a new String object is created (and the previous is not really changed).

Therefore, to make your code work, you have to assign the result of the method to some string:

s = s.toLowerCase();

2 Comments

when you change the state of a String object this wording is wrong. Since it's immutable, you cannot change its state. Any operation that involves changing the state of the object will create a new object with the new state, and the state of the older object will remain intact.
@LuiggiMendoza I was thinking about it while I wrote it (whether it would be confusing). And it sure was, it seems. Fixed it, thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.