Java Strings Introduction

  • + 0 comments

    Strings in Java are immutable, so every invocation of .substring(), .replace() , .toUpperCase() or concatenation with + creates a new String object. Thus, I prefer converting a String to character array or use StringBuilder class that encapsulates a mutable buffer and provides a set of methods to operate on it in a meaningful name. In the end, it creates a new String, of course, but it scales well with the number of applied operations.

    My solution looks as follows:

    import java.util.Scanner;
    
    public class Solution {
        private static String capitalizeFirst(String str) {
            StringBuilder sb = new StringBuilder(str);
            sb.setCharAt(0, Character.toUpperCase(str.charAt(0)));
            return sb.toString();
        }
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            String a = sc.nextLine();
            String b = sc.nextLine();
            sc.close();
            System.out.println(a.length() + b.length());
            System.out.println((a.compareTo(b) > 0) ? "Yes" : "No");
            System.out.println(capitalizeFirst(a) + " " + capitalizeFirst(b));
        }
    }