Statements in Java
What is a Statement?
A statement in Java is a complete command that instructs the Java Virtual Machine (JVM) to perform an action. Every statement ends with a semicolon (;) and may include expressions, declarations, assignments, method calls, loops, and more.
Types of Statements
| Type | Description | Example |
|---|---|---|
| Declaration Statement | Declares a variable | int a; |
| Initialization / Assignment Statement | Assigns value to a variable | a = 10; |
| Expression Statement | Evaluates an expression | a = a + 5; |
| Method Call Statement | Calls a method | System.out.println("Hello"); |
| Control Flow Statement | Controls program execution flow | if (a > 10) { ... } |
| Loop Statement | Repeats block of code | for (int i = 0; i < 5; i++) { ... } |
| Jump Statement | Transfers control | break;, continue;, return; |
Rules for Writing Statements
- Every statement must end with a semicolon (;)
- A block of code (like inside if, for, method, class) can contain multiple statements
- You can combine declaration + assignment in one line:
int x = 10;
Examples
public class StatementExample {
public static void main(String[] args) {
int math = 90; // Declaration + Assignment
int science = 95; // Declaration + Assignment
int total = math + science; // Expression Statement
System.out.println(total); // Method Call Statement
if (total > 180) { // Control Flow Statement (if)
System.out.println("Excellent");
}
for (int i = 0; i < 3; i++) { // Loop Statement (for)
System.out.println(i);
}
}
}
Output:
185
Excellent
0
1
2
Explanation:
| Code | Explanation |
|---|---|
| int math = 90; | Declares a variable and assigns 90 |
| int science = 95; | Declares and assigns 95 |
| int total = math + science; | Adds values and stores in total (expression statement) |
| System.out.println(total); | Prints the total value (method call statement) |
| if (total > 180) { ... } | Checks a condition and prints "Excellent" if true |
| for (int i = 0; i < 3; i++) | Loops 3 times and prints index values 0, 1, 2 |
Statement vs Expression
| Statement | Expression |
|---|---|
| A complete instruction that does something | A combination of variables, operators, and values that results in a value |
| Ends with a semicolon (;) | Can be part of a larger statement |
| Example: x = x + 5; | Expression inside: x + 5 |
Note: Every expression can be part of a statement, but not all statements are just expressions.
Summary
| Feature | Description |
|---|---|
| End Symbol | ; (semicolon) |
| Includes | Declaration, Assignment, Method Call, Control Flow, Loops, etc. |
| Not Included | Comments, White space, Class/Method definitions |
| Execution | Java executes one statement at a time in sequence |