+ 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?

8th Apr 2019, 9:41 PM
Romy
7 Answers
+ 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 :)
8th Apr 2019, 9:53 PM
Victor Andersson
Victor Andersson - avatar
+ 11
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
8th Apr 2019, 9:57 PM
Javier Felipe Toribio
Javier Felipe Toribio - avatar
+ 8
Of course! Got it now. Thank you a lot.
8th Apr 2019, 9:57 PM
Romy
+ 8
Thank you everyone for your answers! :)
8th Apr 2019, 9:59 PM
Romy
+ 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);
9th Apr 2019, 2:02 PM
Syntax_error_chaitu
Syntax_error_chaitu - avatar
+ 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).
4th May 2019, 2:39 AM
ic01010101 ◼️LM
ic01010101 ◼️LM - avatar