Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Java Syntax

Java Syntax

In the preceding section, we generated a Java file named Main.java, employing the subsequent code to display “Hello World” on the screen:

Main.java:

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

Example explained

In Java, every line of executable code must reside within a class. In our illustration, we designated the class as Main. It’s conventionally recommended that class names begin with an uppercase letter.

Please note that Java is case-sensitive, meaning “MyClass” and “myclass” are distinct.

Furthermore, the Java file’s name should correspond to the class name. When saving the file, use the class name followed by “.java”. To execute the example provided on your machine, ensure that Java is correctly installed. Refer to the “Get Started” chapter for Java installation instructions. The expected output is:

 

Hello World

 

The main Method

The presence of the main() method is mandatory and it is a staple in every Java program.

public static void main(String[] args)
Any code inside the main() method will be executed.
Don't worry about the keywords before and after main;
you'll learn about them gradually as you progress through this tutorial.

For now, just keep in mind that each Java program has a class name that must align with the filename, and every program must include the main() method.

System.out.println()

Within the main() method, we utilize the println() method to output a line of text to the screen.

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

Keep in mind that curly braces { } mark the beginning and end of a code block.

System is an intrinsic Java class that contains useful members like out, which stands for “output”.

The println() method, short for “print line”, is used to display a value on the screen or in a file.

Although System, out, and println() might appear complex, just remember that they are essential for outputting content to the screen.

Additionally, every code statement must end with a semicolon (;).