Java Syntax
Understanding Java syntax is essential for writing effective Java programs. Java syntax is the set of rules defining how a Java program is written and interpreted.
Key Topics
1. Basic Structure of a Java Program
A typical Java program consists of the following components:
- Package declaration (optional)
- Import statements (optional)
- Class definition
- Main method
public class MyClass {
public static void main(String[] args) {
// Code to execute
}
}
Explanation: A Java program starts with a class definition. The public class MyClass
defines a class named MyClass
. The public static void main(String[] args)
method is the entry point of any Java program. Code written inside the main
method will be executed when the program runs.
2. Statements and Blocks
Statements are executed sequentially and terminated with a semicolon ;
. Blocks of code are enclosed within curly braces {}
.
Example
public class MyClass {
public static void main(String[] args) {
int a = 5;
int b = 10;
int sum = a + b;
System.out.println("Sum: " + sum);
}
}
Explanation: Each line ending with a semicolon is a statement. Statements are executed in order. The block of code inside the main
method is enclosed within curly braces. This block contains statements that declare variables a
, b
, and sum
, and then prints the sum.
3. Identifiers
Identifiers are names given to classes, variables, and methods. They must begin with a letter, underscore _
, or dollar sign $
, and can be followed by any combination of letters, digits, underscores, or dollar signs.
Example
public class MyClass {
public static void main(String[] args) {
int _value = 100;
int $amount = 200;
int totalAmount = _value + $amount;
System.out.println("Total Amount: " + totalAmount);
}
}
Explanation: The identifiers _value
, $amount
, and totalAmount
are used to name variables. They follow the rules of starting with a letter, underscore, or dollar sign and can include letters and digits.
4. Keywords
Keywords are reserved words in Java that have special meanings and cannot be used as identifiers. Examples include class
, public
, static
, void
, etc.
Example
public class MyClass {
public static void main(String[] args) {
// The following are keywords and cannot be used as identifiers:
// class, public, static, void, int, etc.
// Incorrect usage (will cause compilation error):
// int class = 10;
// void public() {}
// Correct usage:
int number = 10;
System.out.println("Number: " + number);
}
}
Explanation: Keywords like class
and public
have predefined meanings in Java and cannot be used as variable names or identifiers. The example shows incorrect usage which will cause compilation errors and correct usage of identifiers.
Key Takeaways
- Java syntax rules must be followed to write valid programs.
- Statements end with a semicolon, and code blocks are enclosed in curly braces.
- Identifiers should be meaningful and follow naming conventions.
- Keywords are reserved and cannot be used as identifiers.