+12

Why is the method ignored in this case?

Hi all, I was doing some challenges and got this in quiz: String s = “ABC”; s.toLowerCase(); s += “def”; System.out.print(s) Result is ABCdef - so I wonder if someone could, please, explain why the toLowerCase() method is ignored in this case?

4/8/2019 9:41:54 PM

Romy

7 Answers

New Answer

+12

It’s because ”s.toLowerCase();” doesn’t change the original string, it returns a new string. To achieve what you wanted, you can write: s = s.toLowerCase(); Which would assign your variable to the returned value. Hope it helped. EDIT: No Problem :)

+10

Because toLoweCase() doesn't change original string. It only returns modified string in lower case. If the code were: s = s.toLowerCase() The string would change because it would be overriden by toLowerCase return value. In java strings are inmutable. Mutable strings in java are StringBuilder and StringBuffer

+8

Of course! Got it now. Thank you a lot.

+8

Thank you everyone for your answers! :)

+5

its because s.toLowerCase() returns a lower cased version of s, it does not set the string. so a simple fix would be s = s.toLowerCase()

+2

Answer is the method toLowerCase only returns a string in lower case and it doesn't change the value of the actual string.. so to access that lower case string you must assign it to another string.. It works perfect if you try like this... String s="ABC"; String s1=s.toLowerCase(); String add=s1+"def"; System.out.println(add);

+1

Some methods mutate (change) an object or a value while other methods only access the contents of an object or a valur without changing the object or value. Setter methods are methods that change values. void setTemp( float temp ) { float temperature = temp; // mutator method changes //the temperature value } float getTemp( ) { return temperature; //Accessor method returns //a value but does not change //any values } Like others have noted, the toLowerCase() method is an accessor method because it behaves like a “getter” method and leaves the original string untouched. Before using methods, its good to know what the methods will do to the original data—access only (getter) or change (setter).