Java program to convert String to UpperCase using StringBuilder.setCharAt() method

Write a Java program to convert String to Upper Case with or without toUpperCase() method.  This program may be asked in core java written exam. The following code accepts a line of input and converts it to UPPERCASE. In java String Class, there is a method toUpperCase() which converts lowercase string to UPPERCASE. For converting string to uppercase without using toUpperCase(), we can use StringBuilder Class and its setCharAt(int ,char) method. StringBuilder  is similar to StringBuffer but not thread safe  (no guarantee of synchronization). setCharAt(int ,char) which is used to replace a character to a new character at the specified index of a string)

package com.javaonline;

import javax.swing.JOptionPane;
class UpperCase
{
public static void main(String args[])
 {
		String inputStr = JOptionPane.showInputDialog("Enter any Line of text ");  // Getting Input
		if (inputStr!=null && !inputStr.isEmpty())
		{
			System.out.println("Original Input " + inputStr);
			System.out.println("Upper Case  without using toUpperCase() " +uCase(inputStr));
			System.out.println("Upper Case using method  toUpperCase() " + inputStr.toUpperCase());
		}
		else
			System.out.println("Input can not be empty");
    }

private static String uCase(String inputStr)
 {
	StringBuilder inputStrT = new StringBuilder(inputStr);

	for(int i = 0 ; i < inputStrT.length() ; i++)
	{
		if(inputStrT.charAt(i) >= 97 && inputStrT.charAt(i) <=122)    // check for small case letter ...   ascii code of "a" is 97 ... "z" is 122.
		{
		inputStrT.setCharAt(i, (char)(inputStrT.charAt(i)-32));     //   The character at the specified index is set to  to uppercase
		}
	}
		return inputStrT.toString();
	} 

}

Run the program.

Input: java is great.

Output: 

java upper case

 

Reference : StringBuilder Class

You may also like