Java Syntax -

Java Syntax

For a Java program, the filename should always match the class name. This means the name of the class will be the same as the file name, and the file will be saved with the extension .java.

Java Program Structure

Like in programming languages such as C and C++, the entry point of a Java program is the main() method. As shown in the example below:

// File: Test.java
public class A {
   public static void main(String[] args) {
      System.out.println("Class A running");
   }
}

Explanation:

  • As mentioned above, the entry point of a Java program is the main() method. We write all the implementation code within the main() method.
  • The first letter of the class name should always be uppercase. If the class name consists of multiple words, it should be written in camel case, like UserAddress.
  • Remember that Java is a case-sensitive language, so Test and test are considered different.
  • The class name and the file name should be the same.

Java main Method

You will see the main() method in every Java program. Any code inside the main() method will execute when the program runs.

public static void main(String[] args)

The keywords used in the method will be explained in detail later.

Java System.out.println()

System is a predefined class that has many useful members and properties, such as out. out is short for output. The println() method is used to print any text. It stands for print line.

Important

Normally, we keep the file name and class name the same, but it’s not mandatory to name the file exactly the same as the class name. In fact, the file name is used to compile the Java program, while the main class name present in the file is used to execute the compiled code. See the example below:

// File: Test.java
class A {
   public static void main(String[] args) {
      System.out.println("Class A running");
   }
}

Output:

javac Test.java
java A
Class A running

In this example, you can see that the filename is used for compilation, and the class name is used to execute the compiled code.

Important Note

Remember, if the file name is different from the class name, the class should not be public; otherwise, the compiler will throw an error.

// File: Test.java
public class A {
   public static void main(String[] args) {
      System.out.println("Class A running");
   }
}
javac Test.java

class A is public, should be declared in a file named A.java
public class A {
       ^
1 error

This error occurs because the class A is public and must be declared in a file named A.java.

Leave a Comment