Java Program to Convert lowercase character to uppercase character, the following program has written in different ways to convert small alphabets to capital alphabets. Sample output is also added after the Java program, Java String toLowercase() and toUpperCase().
Our problem statement here is, to convert all the lowercase character of the given input into uppercase. To do this, we require an input string and our expected output is the string where there are no lowercase and everything is converted to uppercase.
To read the input string, we make use of a well known class in Java named, the Scanner class.
This helps us to read inputs from console screen of any primitive datatype at runtime. For this, we first create an object of this class and using the object we invoke the nextLine() method. We invoke the nextLine() method because, our required output is of string type.
This can be done as shown below:
1 2 3 4 5 |
Scanner sc=new Scanner(System.in); System.out.println("Enter the string"); String s1=sc.nextLine(); |
To convert lowercase to uppercase, we need to check individual characters of the string. To do this, we first convert the string into character array by making use of the String.charAt() method. This is stored in the character array (ch).
1 |
char[] ch = s1.toCharArray(); |
Every character has ASCII values by which it is stored. The ASCII value of lowercase i.e., from ‘a’-‘z’ is 97-122 whereas, the ASCII value of upper case i.e., from ‘A’-‘Z’ is 65-90.
Therefore, to convert every lowercase alphabet to its corresponding uppercase alphabet, we need to subtract 32 from the lowercase alphabet.
So, we traverse through the character array until the end and check whether the character at that index is between 97-122 both inclusive.
If it is in that range then, 32 is subtracted from it. Now, when we reach the end of the character array and exit the loop, all the alphabets become uppercase only.
This can then be displayed in the console screen using the System.out.println() method. After this, our code execution comes to an end.
for(i=0;i<s1.length();i++) {
if(ch[i]>=97 && ch[i]<=122 ) {
ch[i]-=32;
}
}
System.out.println(ch);
Java Code – Lowercase to Uppercase Character
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.util.Scanner; class lowToUpperCase { public static void main(String arg[]) { int i; char c[]; Scanner sc=new Scanner(System.in); System.out.println("Enter the string"); String s1=sc.nextLine(); char[] ch = s1.toCharArray(); System.out.print("Uppercase("+s1+")--------->"); for(i=0;i<s1.length();i++) { if(ch[i]>=97 && ch[i]<=122 ) { ch[i]-=32; } } System.out.println(ch); } } |
Output:
1 2 3 |
Enter the string hello WORLD Uppercase(hello WORLD)--------->HELLO WORLD |