Skip to main content

Java Fundamentals

Comments and Statements

Introduction to Comments

In programming, we can instruct computers to ignore some parts of the code by using comments.

Why use comments if the computer ignores them?

We use comments as little notes in our program to help us understand the code better. They're mainly for humans to read and grasp the code. 

We'll also use comments in the course to explain how the code works. 🙂

Single-line comments

In Java, we use two forward slashes (//) at the beginning to add a single-line comment.

Any text between // and the end of the line won’t be executed by Java. 

For Example:

class Main {
    public static void main(String[] args) {
        
        // this is a comment. will not be executed.
        System.out.println("Welcome to Java World");
    }
}

We can also add comments in the same line as the code.

class Main {
    public static void main(String[] args) {
        System.out.println("Welcome to Java World");   // this is a comment. 
    }
}

Multi-line comments

Multi-line comments begin with /* and end with */.  Java will ignore any text between /* and */.

This example utilises a multi-line comment (a comment block) to explain the code:

class Main {
  public static void main(String[] args) {
    /* The code below will display the phrase Welcome 
     to Java World on the screen */
    System.out.println("Welcome to Java World");
  }
}

Statements

Statements are roughly equivalent to sentences in natural languages.

In Java, a statement is a command that the compiler can execute. It comprises a complete instruction for the computer to perform and may involve one or more expressions.

Types of Statements

We can broadly categorise Java statements into the following types:

  • Expression statements - Statements that combine variables, operators, and methods in a way that calculates a single value. It's a fundamental part of Java programs and is often used to create or assign values to variables. An expression is made up of values, variables, operators, and method calls.

      Here are some examples of expression statements:

// assignment statement
num = 8933.234;
// increment statement
num++;
// method invocation statement
System.out.println("Hello World!");
// object creation statement
MyClass newObject = new MyClass();
  • Declaration Statements -  A declaration statement declares a variable or constants by specifying their name and data type. 
// declaration statement
double num= 8933.234;
  • Control Statements - Control statements in Java determine the order of execution of statements in a program. Java reads statements from top to bottom. This means that using control flow statements can stop or change a section of a program depending on a specific condition. You'll learn about control flow statements in this section.