user3089390
user3089390

Reputation: 25

Printing properties with .toLowerCase

The following code is given.

String myString = "Hello World";
myString.toLowerCase();
System.out.println(myString);

What my question regards the reason that the result that is printed isn't "hello world"

Is it because the second line doesn't REALLY do anything? Would the proper syntax be (given the first line):

System.out.println(myString.toLowerCase);

Upvotes: 1

Views: 231

Answers (7)

hatellla
hatellla

Reputation: 5142

In Java, java.lang.String is an immutable object (it cannot be changed once it's created)

Try this way instead

String myString = "Hello World";
myString = myString.toLowerCase(); 
System.out.println(myString);

Upvotes: 0

1218985
1218985

Reputation: 8022

Since String is immutable in Java, the myString.toLowerCase() won't change anything in myString but just return a new String with all characters of myString converted to lower case using the rules of the default locale. If you explicitly assign it to the reference variable as shown below, it will refer to "hello world" object.

myString = myString.toLowerCase();

Upvotes: 0

Kamlesh Meghwal
Kamlesh Meghwal

Reputation: 4972

String variables are immutable i.e. you cannot change the object itself, but you can change the reference ofcourse.

Try this way,it will print newely assigned value

String myString = "Hello World";
myString = myString.toLowerCase(); 
System.out.println(myString); 

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 122006

Strings are immutable in java

myString =myString.toLowerCase();

You have to get back the result by assigning.

String myString = "Hello World";  // your String
myString.toLowerCase();       // returning new String
System.out.println(myString); // Still your old String

So,

myString =myString.toLowerCase();// myString is now returned value.

Upvotes: 2

Rahul
Rahul

Reputation: 45070

String is immutable in Java. That is why you need to re-assign the changed value returned by the toLowerCase() method back to myString variable.

String myString = "Hello World";
myString = myString.toLowerCase(); // re-assigning the changed value to myString
System.out.println(myString); // printing the new value

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136062

try this

System.out.println(myString.toLowerCase());

String.toLowerCase() returns lower case String, it does not change the argument

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35577

Change your code to following to get expected out put

    String myString = "Hello World";
    myString=myString.toLowerCase();
    System.out.println(myString);

toLowerCase() s return type is String and that contains the lower case String. you should take return result from that method. Because String is immutable and myString.toLowerCase() will return a new String witch in lower case.

Upvotes: 0

Related Questions