Java code to convert String to Lower Case with / without toLowerCase() method Example

The following code accepts a line of string and converts it to LowerCase. In Java String Class , there is a method toLowerCase() which converts UpperCase string to LowerCase. In our example we have converted the string to LowerCase in two ways. One way is to use the existing method string.toLowerCase(). Another way is  using user defined function called lCase(). Here characters are converted to lower case by adding 32 with the ASCII value of Uppercase Letter. For example, ASCII value of Capital ‘A’ is 65, adding 32 with 65 becomes 97 which is the ASCII value of Small ‘a’.  StringBuilder Class is used in this example. StringBuilder Class can be modified. Moreover it has various methods like setCharAt(int ,char), replace, etc which simplifies the task.

package com.javaonline;

import java.io.*;
class ToLowerCase
{
public static void main(String args[]) throws IOException
 {

	System.out.println("Enter any line ");

	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	String inputLine=br.readLine();
	System.out.println("Lower Case using method  toLowerCase()  : " + inputLine.toLowerCase());
	String lcase=lCase(inputLine);  // userdefined function lCase() is called
	System.out.println("Lower Case  without using toLowerCase() :  " + lcase);

    }

private static String lCase(String inputLine)
 {
	StringBuilder inputLineT = new StringBuilder(inputLine);

	for(int i = 0 ; i < inputLineT.length() ; i++)
		{
		if(inputLineT.charAt(i) >= 65 && inputLineT.charAt(i) <=91)    // check for Capital  letter ...   ascii code of "A" is 65 ... "Z" is 91.
			{
				inputLineT.setCharAt(i, (char)(inputLineT.charAt(i)+32));     //   The character at the specified index is set to  to uppercase
			}
	}
	return inputLineT.toString();
}
} 

Running the above program :

tolowercase

tolowercase1

You may also like