Java Expressions, Statements and Blocks
In this tutorial, you will learn about Java expressions, Java statements, difference between expression and statement, and Java blocks with the help of examples.
In previous chapters, we have used expressions, statements, and blocks without much explaining about them. Now that you know about variables, operators, and literals, it will be easier to understand these concepts.
1. Java Expressions
A Java expression consists of variables, operators, literals, and method calls. It evaluates to a single value.
int score;
score = 90;Here, score = 90 is an expression that returns an int.
Examples:
a + bnumber1 == number2"Hello " + "World"
What does an expression in Java always do?
2. Java Statements
In Java, each statement is a complete unit of execution. It's like a complete sentence in the English language.
int score = 9 * 5;Here, 9 * 5 is an expression, but int score = 9 * 5; is a statement.
Types of Statements
- Expression Statements: Expressions terminated by a semicolon.
number = 10; ++number; System.out.println("Hello"); - Declaration Statements: Used to declare variables.
double tax = 9.5; - Control Flow Statements: Used to control the flow of execution (if, while, for).
3. Java Blocks
A block is a group of statements (zero or more) that is enclosed in curly braces { }.
class Main {
public static void main(String[] args) {
String band = "Beatles";
if (band == "Beatles") { // start of block
System.out.print("Hey ");
System.out.print("Jude!");
} // end of block
}
}Key Points:
- Blocks can be nested inside other blocks.
- Variables declared inside a block are only visible within that block (Scope).
Example: Nested Blocks
public class Main {
public static void main(String[] args) {
// Outer block
int x = 10;
{
// Inner block
int y = 20;
System.out.println(x + y); // 30
}
// System.out.println(y); // Error! y is not visible here
}
}Key Takeaways
- Expression: Evaluates to a value (e.g.,
5 + 3). - Statement: A complete unit of execution, usually ending with
;. - Block: A group of statements enclosed in
{ }.
Challenge
Challenge
Task:
Create a block that contains a statement to print 'Inside Block'.Java Basic Input and Output
Complete guide to Java input/output with examples. Learn System.out.println, Scanner class, print vs println, and user input techniques.
Java Flow Control
Learn about Flow Control in Java. Understand how to control the execution flow of your program using decision-making, looping, and branching statements.
