AI Hints
Home›Java Tutorial›The main Method, println and print, and Comments
Java · Lesson 9 of 120

Comments

Notes for humans.

⏱ 2 min read▶ Video at 11:11🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Comments are notes in your code, for people. Java ignores them completely. They explain why the code does what it does.

  • Notes for people
  • Java ignores them
  • Explain the why

Three kinds of comments

Two slashes start a comment, that runs to the end of the line. A comment can also sit after code, on the same line. Slash star starts a block comment, over several lines, and star slash ends it. Putting two slashes before code switches that line off. Run it. The closed today line doesn't print.

Main.javajava
/*
 * A small program about tea.
 * Written while learning Java.
 */
public class Main {
    public static void main(String[] args) {
        // Print a welcome message
        System.out.println("Welcome to the tea shop");
        System.out.println("Tea costs 3"); // price in pounds
        // System.out.println("Closed today");
    }
}
Output
Welcome to the tea shop
Tea costs 3

Good comments

Explain why, not what. The code already says what it does. Keep comments short, and up to date. And use comments to switch off code, only while testing.

keyvalue
Explainwhy, not what
Keepshort and true
// ...one line
/* ... */many lines

Quick check

Which of these lines does Java ignore? Pause, and think. It's the one starting with two slashes. Everything after them is a comment.

Quick check
Which line does Java ignore?

Summary

Two slashes start a one line comment, and slash star starts a block. Java ignores both. That's the end of module one. Next module, variables and types.

Key takeaways
  • // one line
  • /* block */
  • Explain why
Next up: Variables — named boxes for values