Java Tutorial Java Advanced Java References

Java - Syntax



First Java Program

Although the "Hello World!" program looks simple, it has all the fundamental concepts of Java which is necessary to learn to proceed further. Lets break down "Hello World!" program to learn all these concepts.

//   Hello World! Example 
public class MyClass {
  public static void main(String[] args) {
    System.out.println("Hello World!");
  }
}

The output of the above code will be:

Hello World!

First line is a single line comment which starts with //. Generally, comments are added in programming code with the purpose of making the code easier to understand. It is ignored by compiler while running the code. Please visit comment page for more information.

Every line of code in Java must be within a class. In this example, the name of class is MyClass. It is a public class too. Every java program file can have maximum one public class. Public class name and java program file name must be same. For example, in this example name of java program file is MyClass.java. To learn about class, please visit class page.

Please note that Java is case-sensitive language. Along with this, body of the class must be within curly brackets.

The Main Method()

In Java, every public class must contain main method which is executed when public class is called. Please note that public class name and java program file name must be same.

System.out.println() and System.out.print()

There are two methods in Java, which can be used to print the output.

  • System.out.println(): Output is printed in a new line.
  • System.out.print(): Output is printed in the same line.

Inside println() or print(), multiple variables can be used, each separated by +.

public class MyClass {
  public static void main(String[] args) {
    System.out.println("Hello " + "World!.");
    System.out.println("Print in a new line.");

    System.out.println();
    System.out.print("Hello " + "World!.");
    System.out.print("Print in the same line.");   
  }
}

The output of the above code will be:

Hello World!.
Print in a new line.

Hello World!.Print in the same line.

Semicolons

In a Java program, the semicolon is a statement terminator. Each individual statement in Java must be ended with a semicolon. It indicates that the current statement has been terminated and other statements following are new statements. For example - Given below are two different statements:

System.out.println("Hello " + "World!.");
System.out.println("Print in a new line.");

line change, "\n"

To facilitates a line change inside ystem.out.println() statement or ystem.out.print() statement, "\n" can be used. "\n" tells to start a new line to the program.


public class MyClass {
  public static void main(String[] args) {
    System.out.println("Hello \nWorld!.");
    System.out.print("Learning Java is fun.\nAnd easy too.");
  }
}

The output of the above code will be:

Hello 
World!.
Learning Java is fun.
And easy too.