loading

Java Syntax

Java Syntax

We built a Java file named Main.java in the last chapter, and we printed “Hello World” to the screen using the following code:

Main.java

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

Example explained

In Java, each line of code must be contained within a class. We gave the class in our example the name Main. Every class should begin with an uppercase initial letter.

Note: that “MyClass” and “myclass” have different meanings in Java due to case sensitivity.

The class name and the Java file name must match. Put “.java” at the end of the filename and save the file using the class name. Make sure Java is installed correctly on your computer in order to use the preceding example: To learn how to install Java, refer to the Get Started Chapter. The result ought to be:

				
					Hello World
				
			

The main Method

You will find the main() function in any Java program; it is needed.

				
					public static void main(String[] args)
				
			

The code included within the main() method will be run. The keywords before and after the main text are unimportant. While reading through this guide, you will gradually come to know them.

For now, just keep in mind that every Java program needs to have the main() function and that the class name must match the filename.

System.out.println()

To print a line of text to the screen inside the main() method, use the println() method:

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

Note: A block of code begins and ends with the curly braces {}.

An example of a useful member in the built-in Java class System is out, which is short for “output”. To print a value to the screen (or a file), use the println() function, which stands for “print line”.

Proceed with caution while dealing with System, out, and println(). Just be aware that in order to print things to the screen, you need both of them.

Additionally, keep in mind that every code statement needs to terminate with a semicolon (;).

Share this Doc

Java Syntax

Or copy link

Explore Topic