11package com .thealgorithms .strings ;
22
33public final class Upper {
4+
45 private Upper () {
56 }
67
@@ -15,25 +16,42 @@ public static void main(String[] args) {
1516 }
1617
1718 /**
18- * Converts all the characters in this {@code String} to upper case
19+ * Converts all the characters in this {@code String} to upper case.
1920 *
2021 * @param s the string to convert
2122 * @return the {@code String}, converted to uppercase.
23+ * @throws IllegalArgumentException if {@code s} is null
2224 */
2325 public static String toUpperCase (String s ) {
2426 if (s == null ) {
25- throw new IllegalArgumentException ("Input string connot be null" );
27+ throw new IllegalArgumentException ("Input string cannot be null" );
2628 }
2729 if (s .isEmpty ()) {
2830 return s ;
2931 }
30- StringBuilder result = new StringBuilder (s );
31- for (int i = 0 ; i < result .length (); ++i ) {
32- char currentChar = result .charAt (i );
33- if (Character .isLetter (currentChar ) && Character .isLowerCase (currentChar )) {
34- result .setCharAt (i , Character .toUpperCase (currentChar ));
32+
33+ // Check if any lowercase letter exists before creating a new String
34+ boolean hasLower = false ;
35+ for (int i = 0 ; i < s .length (); i ++) {
36+ if (Character .isLowerCase (s .charAt (i ))) {
37+ hasLower = true ;
38+ break ;
3539 }
3640 }
37- return result .toString ();
41+
42+ // If no lowercase characters, return the same string
43+ if (!hasLower ) {
44+ return s ;
45+ }
46+
47+ // Convert lowercase letters to uppercase
48+ char [] chars = s .toCharArray ();
49+ for (int i = 0 ; i < chars .length ; i ++) {
50+ if (Character .isLowerCase (chars [i ])) {
51+ chars [i ] = Character .toUpperCase (chars [i ]);
52+ }
53+ }
54+
55+ return new String (chars );
3856 }
3957}
0 commit comments