1
public class StringTest{
public static void main(String[] args){
    String s1 = "A", s2="a", s3="b";
    s1.toLowerCase();
    s3.replace('b','a');
    System.out.println((s1.equals(s2))+","+(s2.equals(s3)));
    System.out.println(s1+" "+s2+" "+s3);
}
}

Expected output:

true, true
a a a

but toLowerCase() and replace() fuction is not working and i am getting the output as:

false,false
A a b

i am new to java programming.

James Z
  • 12,209
  • 10
  • 24
  • 44
sikkin.p
  • 13
  • 2
  • 1
    Does this answer your question? [String replace method is not replacing characters](https://stackoverflow.com/questions/12734721/string-replace-method-is-not-replacing-characters) – Federico klez Culloca Jun 17 '21 at 08:18
  • Strings are immutable. Meaning the vslue can't be modified which us why toLowerCase returns a new string rather than modify the input. Same goes for replace method. – Yoshikage Kira Jun 17 '21 at 08:18
  • Strings are immutable objects created on heap, and if you are using replace function please assign it back – Ashish Mishra Jun 17 '21 at 08:52

3 Answers3

2

You did not assign value to the variable after conversion. Please replace those 2 functions with

s1=s1.toLowerCase();
s3=s3.replace('b','a');
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
2

The Answers above are Right.

But as a beginner, what I want to you you understand is that Strings and Primitives in Java are immutable meaning the Values they are assigned to can't change

In your situation above you could do

String s1 = "A", s2="a", s3="b";
 
System.out.println( s1.toLowerCase());

To verify that the toLowerCase() methods works or you reassign the variable

s1 = s1.toLowerCase()
Mab
  • 412
  • 3
  • 12
0
s1.toLowerCase();

this works exactly as you would expect, but it doesn't change the assigned version.

You want:

s1 = s1.toLowerCase();

For the replace method, its the same issue: the correct value is returned, but you don't assign it to your variable.

Stultuske
  • 9,296
  • 1
  • 25
  • 37