Java Syntax Basics

Java Program Structure

Every Java program must contain at least one class, and the starting point of execution is the main method. This method must be inside a class — most commonly named Main or another class name of your choice.

The public static void main(String[] args) method is required for the JVM (Java Virtual Machine) to run your code.

  • public: means the method can be accessed from anywhere
  • static: allows the method to run without creating an object
  • void: indicates the method doesn't return a value
  • String[] args: allows command-line arguments to be passed into the program
public class Main {
    public static void main(String[] args) {
        // Your code here
    }
}

Print Statements

Use System.out.println() to print messages in Java. This is one of the most commonly used statements to display output.

Loading...
Output:

Statements and Semicolons

Every executable line in Java ends with a ;. Omitting this causes a compilation error.

Loading...
Output:

Curly Braces Define Blocks

Java uses {} to define code blocks for conditionals, loops, classes, and methods.

Loading...
Output:

Case Sensitivity

Java is case-sensitive, meaning MyVar and myvar are considered different variables.

int myVar = 5;
int MyVar = 10;
System.out.println(myVar);  // 5

Comments in Java

Java supports both single-line and multi-line comments:

// This is a single-line comment
/*
 This is a multi-line comment 
*/

Whitespace and Formatting

Whitespace is ignored by the compiler, but developers use indentation and spacing to make code more readable.

Practice Question

Which of the following is invalid Java syntax? Option A or Option B?

Loading...
Output:
Loading...
Output:

Hint: The method declaration is missing void.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic