Printing and Comments

println vs print

  • System.out.println(...) prints, then moves to a new line (the ln means “line”).
  • System.out.print(...) prints and stays on the same line.
public class Main {
    public static void main(String[] args) {
        System.out.print("Good ");
        System.out.print("morning");
        System.out.println("!");
        System.out.println("Next line");
    }
}

Output

Good morning!
Next line

Printing numbers and maths

Text goes inside double quotes. Numbers don't need quotes, and Java can work out sums for you:

public class Main {
    public static void main(String[] args) {
        System.out.println(42);
        System.out.println(10 + 5);
        System.out.println("10 + 5");
    }
}

Output

42
15
10 + 5

With quotes, "10 + 5" is just text, so Java prints it exactly as written.

Special characters

Some characters are written with a backslash \. These are called escape sequences:

WriteYou get
\na new line
\ta tab (a wide space)
\"a double quote inside text
\\a backslash
public class Main {
    public static void main(String[] args) {
        System.out.println("Line one\nLine two");
        System.out.println("Name:\tAsha");
        System.out.println("She said \"hi\"");
    }
}

Output

Line one
Line two
Name:	Asha
She said "hi"

Comments: notes for humans

A comment is a note in your code that Java ignores. Use comments to explain what your code does.

public class Main {
    public static void main(String[] args) {
        // This is a one-line comment
        System.out.println("Comments are ignored"); // a comment at the end of a line

        /* This is a comment
           that spans many lines */
        System.out.println("Done");
    }
}

Output

Comments are ignored
Done

Remember: // starts a one-line comment. /* ... */ wraps a comment over many lines.

HOME LABS COMMUNITY DASHBOARD