-3

toLowerCase() converts the string to lowercase but when i use it in a logic it gives bizarre results. I can do the logic in some other way without even using toLowerCase() but please tell me what's wrong here

char gender = 'M';
System.out.println((gender+"").toLowerCase());          //prints "m"
System.out.println((gender+"").toLowerCase()=="m");     //false

if ((gender+"").toLowerCase()=="m") {
    System.out.println("if it went through loop");
}

1 Answers1

3

Use if ((gender+"").toLowerCase().equals("m")). You should not use == operator to compare the value of String. Use equals() method instead. Learn how the comparison of strings with equals and assignment operator

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56