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!”);

tip.eps Most, but not all, Java statements must end with a semicolon. The basic rule is that declaration and expression statements must end with a semicolon, but most other statement types do not.

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.

tip.eps You don’t have to do anything special to continue a statement onto a second line. Thus, the statement

x = (y + 5) / z;

is identical to this statement:

x =

(y + 5) / z;

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset