Computer Science Researcher • Educator • Programming Instructor
Java syntax refers to the rules that define how Java programs are written and understood. Java is strict about punctuation and structure, but once you get used to it, writing programs becomes easy.
All Java code MUST be inside a class:
public class Main {
}
The main() method is the starting point of every Java program.
Without it, the program will not run.
public static void main(String[] args) {
System.out.println("Hello Java");
}
You use System.out.println() to print text:
System.out.println("Welcome");
System.out.println(5 + 10);
System.out.println("Result: " + 20);
System.out.print("Hello ");
System.out.print("World!");
Output: Hello World!
Every statement in Java must end with a semicolon ;
int x = 10;
System.out.println(x);
int age = 20;
int Age = 30;
System.out.println(age); // 20
System.out.println(Age); // 30
age and Age are different variables.
// This is a comment
System.out.println("Hello");
/*
This is a
multi-line comment
*/
if (5 > 2) {
System.out.println("Yes");
}
for (int i = 1; i <= 3; i++) {
System.out.println("Loop: " + i);
}
Java does not require indentation to run the code, but indentation makes programs readable.
// Good indentation
if (x == 10) {
System.out.println("Correct");
}
// Bad indentation (still works, but messy)
if (x == 10){System.out.println("Correct");}
public class Main {
public static void main(String[] args) {
// Print a welcome message
System.out.println("Java Syntax Example");
int a = 5;
int b = 10;
System.out.println("Sum = " + (a + b));
}
}
// Example 1: Print your name
System.out.println("Khalid");
// Example 2: Print a number
System.out.println(123);
// Example 3: Print text + number
System.out.println("Age: " + 38);
// Example 4: Declare two numbers and print them
int x = 7;
int y = 9;
System.out.println(x + y);
// Example 5: Simple message
System.out.println("Java is fun!");
Back to Top