Statements
Unlike most programming languages, Java doesn’t use statements as its fundamental unit of code. Instead, it gives that honor to the class. However, every class must have a body, and the body of a class is made of one or more statements. In other words, you can’t have a meaningful Java program without at least one statement.
The simplest Java statements are declaration statements, which declare variables. For example:
int i;
String s = “This is a string”;
Customer c = new Customer();
Another common type of statement is an expression statement, which performs a calculation:
i = a + b;
salesTax = invoiceTotal * taxRate;
System.out.println(“Hello, World!”);
What makes this rule tricky is that most other types of statements include one or more declaration or expression statements that do use semicolons. For example, here’s a typical if
statement:
if (total > 100)
discountPercent = 10;
In this example, the assignment statement (discountPercent = 10
) must end with a semicolon. However, the if
statement does not require a semicolon.
x = (y + 5) / z;
is identical to this statement:
x =
(y + 5) / z;