Skip to content

Strings & Messages

The Course
•
20 min study

A String is text, including spaces and punctuation. Double quotes mark its boundaries in source code; they are not printed as part of its value. You can store text in a variable and reuse it in several messages. An empty string, written as two adjacent double quotes, is valid text of length zero.

The + operator adds numbers when both operands are numeric. If a String is involved, it builds text instead. Java evaluates a chain from left to right, so adding a label before two numbers can turn those later operations into text concatenation. Use parentheses or a named numeric result to make your intention clear. A readable report is the last step of a calculation, not a replacement for the calculation.

Let names carry meaning

Build messages from values rather than repeatedly editing the same number in several strings. If minutes changes from 25 to 30, every message using that variable sees its current value. You still decide where the spaces go. Java does not automatically insert spaces between concatenated pieces.

Calculate before building a message Java
public class Main {
    public static void main(String[] args) {
        String topic = "Java";
        int minutes = 25;
        int sessions = 2;
        int total = minutes * sessions;

        System.out.println(topic + ": " + total + " min");
        System.out.println("Next: " + topic);
    }
}
Check your prediction
Text
Java: 50 min
Next: Java

The total is a number until the print statement combines it with a label. The colon and spaces belong to quoted text. Change minutes to 30 and confirm that the report follows the value.

Same symbols, different grouping Java
public class Main {
    public static void main(String[] args) {
        System.out.println("Total: " + 2 + 3);
        System.out.println("Total: " + (2 + 3));
        System.out.println(2 + 3 + " minutes");
    }
}
Check your prediction
Text
Total: 23
Total: 5
5 minutes

The first line builds Total: 2, then appends 3. The parentheses in the second line require numeric addition first. The last line starts with two numbers, so it adds them before encountering text.

Count characters, including spaces Java
public class Main {
    public static void main(String[] args) {
        String title = "Java";
        String spaced = " Java ";

        System.out.println(title.length());
        System.out.println(spaced.length());
        System.out.println("".length());
    }
}
Check your prediction
Text
4
6
0

length() is a built-in String method: a named operation that gives back a value. Include its parentheses. The two outer spaces are real characters. Later you will learn more String operations and write methods of your own.

Read an expression one step at a time

When an output line surprises you, evaluate its expression before blaming the printer. In "Total: " + 2 + 3, the first operation creates the string "Total: 2". The next operation therefore appends text. In 2 + 3 + " minutes", the first operation is numeric addition, so the string starts with 5.

Java works left to right. Each row is one +:

Expression so farValueKind
"Total: " + 2"Total: 2"text
"Total: 2" + 3"Total: 23"text
2 + 35number
5 + " minutes""5 minutes"text

Once the left side is text, every later + joins text. To add first, store the sum in a variable such as total and attach the label afterward.

Debug a plausible mistake

This connects today's text rules to yesterday's arithmetic. Java can print a perfectly valid string that reports the wrong calculation. Follow the intermediate value of the leftmost addition, not just the final printed line.

Exercise

Repair the numeric report

The report must print Total: 35 from planned 25 and extra 10. Keep both input values numeric and derive the answer; do not hard-code 35. Then set extra to 0 and expect Total: 25. Predict what the current program actually prints before changing it. Make the smallest repair, then try extra = 0. The supplied version compiles; its behavior is the problem.

Debugging workspace Java
public class Main {
    public static void main(String[] args) {
        int planned = 25;
        int extra = 10;
        System.out.println("Total: " + planned + extra);
    }
}
Hint 1: the idea

The label starts concatenation before both numbers have been added.

Hint 2: a first step

Calculate a numeric result before attaching its label, or group the arithmetic explicitly.

Show one solution
Java
public class Main {
    public static void main(String[] args) {
        int planned = 25;
        int extra = 10;
        int total = planned + extra;
        System.out.println("Total: " + total);
    }
}

Expected output after repair:

Text
Total: 35

The bug was "Total: " + planned + extra: the label made the first + join text, so 25 and 10 were glued into Total: 2510. Adding into total first makes + do arithmetic. With extra = 0 the old code printed Total: 250, the fixed code prints Total: 25.

Your turn

Exercise

Print a useful report

Store topic="Loops", days=3 and minutesPerDay=20. Calculate the total and print Loops: 60 minutes in 3 days. Then print the length of the topic (5). Change a starting value afterward to check that the message follows your data.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        String topic = "Loops";
        int days = 3;
        int minutesPerDay = 20;
        // Calculate the total and build the report.
    }
}
Hint 1: the idea

Calculate with the numbers first. Then build the label from topic, the result and days.

Hint 2: a first step

Create a total variable before the print statement so numeric addition or multiplication cannot accidentally become text concatenation.

Show one solution
Java
public class Main {
    public static void main(String[] args) {
        String topic = "Loops";
        int days = 3;
        int minutesPerDay = 20;
        int total = days * minutesPerDay;

        System.out.println(topic + ": " + total + " minutes in " + days + " days");
        System.out.println(topic.length());
    }
}
Text
Loops: 60 minutes in 3 days
5

int total = days * minutesPerDay; does the arithmetic before any text is involved, so the report only joins finished values.

Change it and explain

Use a topic with an internal space and predict its length. Try days=1; the message still says days because grammar is not automatic. You will learn how to choose singular or plural wording using conditions tomorrow.

To put a double quote inside text, escape it as \"; a backslash introduces an escape sequence in a Java string. \n represents a newline in text, while a newline between statements only changes source layout. Prefer separate println calls while practicing output order. Do not use String equality with == to compare user-facing text; the dedicated equality lesson will explain why.

Going further

These examples use simple English text. Java's length() counts UTF-16 code units, so a visible symbol such as an emoji can count as two rather than one. charAt uses the same positions. You do not need Unicode processing for this course's core tasks; avoid assuming that a displayed symbol always occupies one position.

Was this article helpful?

Your response is saved on this device.