Java program to convert lowercase to uppercase without using string function

Published by user on

In this Java program, we are going to look at how to convert lowercase String to uppercase without using any String function. There are requirements where we cannot use any built-in functions.

For this conversion, we will make use of ASCII table.

Lower Case ASCII Upper Case ASCII
a – 97 A – 65
b – 98 B – 66

As we can see lower case ‘a’ has ASCII value 97 and upper case ‘A’ has ASCII value 65.

Logic to convert from lowercase to uppercase

From the concept, we know that the difference between lowercase ASCII and upper case ASCII is 32.

  • Find the length of String
  • Run the loop from 0 to (length – 1)
  • Visit each character of String and subtract 32 from it
  • As we subtract 32, the lowercase letter gets converted to uppercase letter
  • Print the uppercase string

Here we didn’t use any built-in function.

Now the logic is clear, so let’s look at the program.

Program

// Java Program to demonstrate
// Conversion of String from lowercase
// to uppercase without using
// built-in String functions
public class LowerUpperDemo {
	public static void main(String args[]) {
		String input = "java is best";
		System.out.println("Lower case string is : " + input);
		char strArr[] = input.toCharArray();
		for (int i = 0; i < strArr.length; i++) {
			// here is the actual logic
			if (strArr[i] >= 'a' && strArr[i] <= 'z') {
				strArr[i] = (char) ((int) strArr[i] - 32);
			}
		}
		System.out.print("Upper case string is : ");
		// print the string array
		for (int i = 0; i < strArr.length; i++) {
			System.out.print(strArr[i]);
		}
	}
}

Output:

Lower case string is : java is best
Upper case string is : JAVA IS BEST

Step By Step Run of the Program

  1. The input value is ‘java is best’. We want the output as ‘JAVA IS BEST’
  2. Loop from 0 till (length – 1), in this case, 12
  3. Read the character at position 0, and subtract 32 from it
  4. Step 3 did the conversion from lowercase to uppercase
  5. Store the result in the char array
  6. Increment the index to 1, and process the character at position 1
  7. Repeat the above steps with incremented index until all the characters are processed
Categories: Java