Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the method toLowerCase(); working in my code?

Tags:

java

import java.util.Scanner;

public class Test
{

    public static void main(String[] args)
    {
        char[] sArray;

        Scanner scan = new Scanner(System.in);

        System.out.print("Enter a Palindrome : ");

        String s = scan.nextLine();


        sArray = new char[s.length()];

        for(int i = 0; i < s.length(); i++)
        {
            s.toLowerCase();
            sArray[i] = s.charAt(i);
            System.out.print(sArray[i]);
        }

    }
}
like image 768
wam090 Avatar asked Dec 12 '10 15:12

wam090


People also ask

Why is toLowerCase not working in Java?

It doesn't work because strings are immutable. You need to reassign: s = s. toLowerCase();

How do you declare toLowerCase in Java?

Java String toLowerCase() method is used and operated over string where we want to convert all letters to lowercase in a string. There are two types of toLowerCase() method as follows: toLowerCase() toLowerCase(Locale loc): Converts all the characters into lowercase using the rules of the given Locale.

What is the return type of the toLowerCase () method?

Java - toLowerCase() Method The method returns the lowercase form of the specified char value.


2 Answers

It doesn't work because strings are immutable. You need to reassign:

s = s.toLowerCase();

The toLowerCase() returns the modified value, it doesn't modify the value of the instance you are calling this method on.

like image 76
Darin Dimitrov Avatar answered Nov 07 '22 10:11

Darin Dimitrov


You need to do:

String newStr = s.toLowerCase();
like image 22
Brian Avatar answered Nov 07 '22 08:11

Brian