Home › Learn › Java › First steps

Strings

Lesson 4 of 40. Join text, measure it, and pick characters out of it.

A String is text. + joins strings, and joins a string with any other value by converting the value to text: "Total: " + 3 is "Total: 3". text.length() counts characters, text.charAt(0) is the first character (a char), and text.toUpperCase() returns a new upper-case copy; strings never change, methods return new ones.

Compare strings with .equals, never ==: a.equals(b) compares the text, == asks whether they are the same object, which is usually not what you mean. "Ada".equals("ada") is false; equalsIgnoreCase ignores case.

String first = "Ada";
String full = first + " " + "Lovelace";
System.out.println(full.length());        // 12
System.out.println(full.charAt(0));       // A
System.out.println(full.toUpperCase());   // ADA LOVELACE

Your task

Using first and last from the starter, set full to the two names with a space between, shout to full in upper case, and initials to the first character of each name joined together (a String, so "AL"). Print full.

Hint 1

full = first + " " + last; shout = full.toUpperCase();

Hint 2

charAt gives a char; joining two chars with + adds their numbers. Start from a String instead: "" + first.charAt(0) + last.charAt(0).

Show the solution
public class Main {
    static String first = "Ada";
    static String last = "Lovelace";
    static String full = first + " " + last;
    static String shout = full.toUpperCase();
    static String initials = "" + first.charAt(0) + last.charAt(0);

    public static void main(String[] args) {
        System.out.println(full);
    }
}

    Compiles with OpenJDK javac and TeaVM, both compiled to WebAssembly (7 MB download the first time, then cached), and runs in this tab; nothing is sent anywhere.