Understanding the basic building blocks of the language is essential. These include expressions, statements, and blocks, which help structure code and control the flow of execution.
Expressions
An expression in Java is any valid combination of variables, constants, operators, and function calls that results in a value. Expressions are used to compute values and are often part of larger statements.
Examples of expressions
5 + 3
(Arithmetic expression)x * y
(Arithmetic expression with variables)a > b
(Relational expression)str.length()
(Method call expression)
Expressions can appear on the right-hand side of an assignment, in control flow conditions, or as arguments to methods.
Statements
A statement in Java is an instruction that the Java Virtual Machine (JVM) executes. Statements can be classified into different types:
- Expression Statement: A statement that contains an expression, like
a = b + 5;
. - Declaration Statement: A statement that declares a variable, such as
int x = 10;
. - Control Flow Statement: Statements that control the flow of execution, such as
if
,for
,while
, andswitch
statements. - Return Statement: It exits from the current method and can optionally return a value.
Examples of statements
1 2 3 4 5 |
int x = 10; // Declaration statement x = x + 5; // Expression statement if (x > 10) { // Control flow statement System.out.println("Greater than 10"); } |
Blocks
A block is a group of statements enclosed within curly braces {}
. Blocks are used to define the scope of a method, class, or control structure (e.g., if
, for
, while
).
Example of a block
1 2 3 4 5 6 7 8 |
public void exampleMethod() { // Block of code inside the method int a = 5; int b = 10; if (a < b) { System.out.println("a is less than b"); } } |
In this example, the code inside the method is a block, and the if
statement also has its own block to group the code that should be executed if the condition is true.