To Print uppercase & lowercase letters separately from given String in Java, there are following step :-
- first we create the object of StringBuilder class,we are using this because it is not thread safe and mutable also.
- now make one for loop and pass this string and iterate from index 0 to s.length().
- if s.charAt(i) method give the character value at specific index and it is validate to uppercase from Character.isUpperCase method. if s.charAt(i) value is in the range of A-Z, it appends to a StringBuilder named “uper”.
- In next if condition s.charAt(i) give value and it is validate to lowercase from Character.isLowerCase method. if s.charAt(i) value is in the range of a-z, it appends to a StringBuilder named “lower”.
- in last if condition s.charAt(i) method give value and it is validate to number from Character.isDigit method. if s.charAt(i) value is in the range of 0-9, it appends to a StringBuilder named “digits”.
public class CharNumberCheck {
public static void main(String[] args) {
// print XYZ, mn and 456 as separate lines
String s = "XYZmn456";
StringBuilder uper = new StringBuilder();
StringBuilder digits = new StringBuilder();
StringBuilder lower = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (Character.isUpperCase(s.charAt(i))) {
uper.append(s.charAt(i));
} else if (Character.isLowerCase(s.charAt(i))) {
lower.append(s.charAt(i));
}
if (Character.isDigit(s.charAt(i))) {
digits.append(s.charAt(i));
}
}
System.out.println("Upper case character value:- " + uper);
System.out.println("lower case character value:- " + lower);
System.out.println("number value:- " + digits);
}
}
Output :-
Upper case character value:- XYZ
lower case character value:- mn
number value:- 456