Chapter 2_2:Java Syntax and Java Comments

Java Syntax

Following code to print “Hello Java World” to the screen:

DemoClass.java

public class DemoClass {
  public static void main(String[] args) {
    System.out.println("Hello Java World");
  }

Here,

Every line of code that runs in Java essential inside a class. In our example, we named the class DemoClass. A class should always start with an uppercase first letter.

Note: Java is case-sensitive: “DemoClass” and “democlass” has different meaning.

The name of the java file must match the class name. When saving the file, save it using the class name and add “.java” to the end of the filename. To run the example above on your computer, make sure that Java is properly installed.

 The output should be:

Hello Java World

Main Method

You will see the main() method in every Java program and is required :

public static void main(String[] args)

Any code inside the main() method will be executed. You don’t have to understand the keywords before and after main. You will get to see them in the next chapter next cahpter.

Now, just remember that every Java program has a class name which must match the filename, and that every program must contain the main() method.

System.out.println()

Inside the main() method, println() we can use in the method to print a line of text to the screen:

public static void main(String[] args) {
  System.out.println("Hello Java World");
}

Note: In Java, each code statement must end with a semicolon.

Java Comments

Comments can be used to express Java code, and to make it more clear. It can also be used to prevent execution when testing alternate code.

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by Java (will not be executed).

This example uses a single-line comment before a line of code:

Example
public class DemoClass {

  public static void main(String[] args) {

    // This is a comment

    System.out.println(“Hello Java World”);

  }

}

Output:

Hello Java World

This example uses a single-line comment at the end of a line of code:

Example
System.out.println("Hello Java World"); // This is a comment

Java Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Java.

This example uses a multi-line comment to explain the code:

Example
/*below code will print the words Hello Java World
to the screen, and it is very easy*/
System.out.println("Hello Java World");