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.
Get Java For Dummies Quick Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.