What is Java Syntax?
Java syntax refers to the set of rules and structure that define how Java code is written.
Every Java application starts with a class, contains methods, statements, blocks, and expressions.
Basic Java Syntax
// This is a single line comment
/* This is a
multi-line comment */
/*
Every Java application starts with a class
with the main method.
*/
public class HelloWorld {
// main method — entry point for the application
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
Explanation
public class HelloWorld:
public = Access modifier
class = Declares a class
HelloWorld = Name of the class (should match file name)
public static void main(String[] args):
public = Accessible from anywhere
static = We can call main without instantiating the class
void = This method doesn’t return a value
String[] args = Command-like array of strings passed when we run the application
System.out.println("Hello, Java!");:
- Prints text to the console.
Java Statements
Variable Declaration:
int number = 10;
String message = "Hello, Java.";
double price = 99.99;
boolean isValid = true;
Control Structures
If-Else:
if (number > 5) {
System.out.println("number is greater than 5.");
} else {
System.out.println("number is not greater than 5.");
}
For Loop:
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
While Loop:
int count = 0;
while (count < 5) {
System.out.println("Count is: " + count);
count++;
}
Method Definition
public static int addNumbers(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int sum = addNumbers(5, 10);
System.out.println("Sum = " + sum);
}
Summary
- Java is case-sensitive.
- All code belongs to a class.
- The main method is the entry point for a Java application.
- Comments aid understanding code.
- Statements typically end with a semicolon (
;).