Advertisement
Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

How Statements Are Used in Java

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

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.

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;
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win an iPad Mini. Enter to win now!