Curriculum
In Java, expressions, statements, and blocks are the fundamental building blocks of programs.
Expressions are the smallest unit of computation in Java. An expression is a combination of variables, operators, and method invocations that produces a value. For example, 2 + 3
is an expression that produces the value 5
. Expressions can be used to perform arithmetic calculations, compare values, and invoke methods, among other things.
A statement is a complete command that performs some action in a program. Statements can be used to execute expressions, declare variables, control the flow of program execution, and perform other tasks. For example, the following are all examples of statements in Java:
int x = 5; System.out.println("Hello, world!"); if (x > 0) { System.out.println("x is positive"); }
In this example, the first statement declares and initializes a variable x
. The second statement prints a message to the console. The third statement uses a conditional (if
) statement to control the flow of program execution.
A block is a group of zero or more statements enclosed in braces ({}
) that are executed together as a single unit. Blocks are used to group statements together, to control the scope of variables, and to define the bodies of classes, methods, and control structures. For example, the following is an example of a block in Java:
{ int x = 5; int y = 7;In this example, the block contains three statements that declare and initialize variables and perform an arithmetic calculation. The block is executed as a single unit, and the variables declared in the block are only visible within the block itself. int z = x + y; System.out.println("The sum of x and y is: " + z); }
In this example, the block contains three statements that declare and initialize variables and perform an arithmetic calculation. The block is executed as a single unit, and the variables declared in the block are only visible within the block itself.