Overview of This Lesson

Expressions and statements are a fundamental part of any programming language. An expression is used to evaluate or compare values, and a statement contains one or more expressions, possibly with other code elements, to execute a specific task. Understanding how to write correct and efficient statements and expressions will ensure you have the necessary foundation to do more intermediate programming.

Pre-Requisites

Before doing this tutorial, it is expected that you understand Java's Data Types and that you know how to declare, initialize, and use Variables.

Basic Expressions and Statements

An expression is a part of a statement that evaluates to something: usually it would involve a calculation or comparison using literals, variables, and operators, but even a single value can be an expression. For example, each of the following are expressions:

Each expression evaluates to something, even "Hello, World!" and 77.77. The result of an expression is often called the return value of the expression. When referring to an expression, we often include the type of data it returns. For example:

Expressions are always part of statements. A statement is a single piece of executing code. In Java, a statement can take up multiple lines of code but it always ends in a semicolon (except for most programming constructs such as selections and loops, but we won't cover those for a while, yet). For example, these are statements:

An assignment statement is a special kind of statement that assigns a value or expression to a variable. For example, each of these are assignment statements:

Notice that the first two examples simply assign a value to a variable. The last 3 examples all assign the result of an expression to the variable.

When looking at an assignment statement, the equals sign (=) is the assignment operator, and it's job is to place the result of the expression on the right into the variable on the left. It's important to note that the direction of assignment goes from right to left, not left to right. If it helps, read the assignment operator as "gets" or "gets the value/result of". For example:

firstName = "Fred"; reads "the variable strFirstName gets the value Fred"
result = grade + bonus; reads "the variable result gets the result of the expression grade plus bonus"

Exercises

1. Which of the following are full statements, and which are only expressions (assume any variables being used have been declared and initialized)?

  1. System.out.println("Error: invalid input.");
  2. a * a + b * b
  3. int num = 5;
  4. double value = x / y;
  5. "Java 17"
  6. -999
  7. endValue = -999;
  1. System.out.println("Error: invalid input."); statement
  2. a * a + b * b expression
  3. int num = 5; statement
  4. double value = x / y; statement
  5. "Java 17" expression
  6. -999 expression
  7. endValue = -999; statement

2. Explain what's wrong with each of the following segments of code:

// example 1
double a = 5.0;
double b = 4.0;
double c = 0.0;
c * c = a * a + b * b;
System.out.println(a + ", " + b + ", " + c);
// example 2
double length;
double width = 15;
double area = length * width;
System.out.println("area" + area);
// example 3
int sum = score1 + score2 + score3;
int score1 = 78;
int score2 = 99;
int score3 = 84;
System.out.println(sum);
// example 4
double num = 1, den = 3, fraction = 0;
num / den = fraction;
System.out.println("decimal: " + fraction);

Example 1: You can't assign the result of the expression a * a + b * b to another expression (c * c). You can only assign an expression to a variable. If you wanted to fix this, you'd need to learn about Math methods, but here it is in case you're curious:

c = Math.sqrt(a * a + b * b);

(Math.sqrt() returns the square root of the expression a * a + b * b)

Example 2: the variable length has not been assigned a value. You can't use a variable unless it has been assigned a value. To fix it, assign any value to length e.g. double length = 10;

Example 3: this program is trying to use the score1, score2, and score3 variables in an expression before the variables are declared and initialized. Statements are always executed in order from top to bottom. To correct it, move the int sum = score1 + score2 + score3; statement right above the println() statement.

Example 4: The statement num / den = fraction; is backwards - you can't assign a variable to an expression. To fix it, just swap both sides of the assignment operator: fraction = num / den;

3. Write a program that calculates the amount of money to tip a wait person by coding the following tasks:

  1. Define a variable for the bill amount and initialize it to 35.10.
  2. Define a variable for the tip percentage and initialize it to 15.
  3. Define a variable for the tip amount.
  4. Calculate the tip as the bill amount multiplied by the tip percentage (remember that 15% = 0.15) and assign and store the result in the tip amount variable.
  5. Display the output on the screen as shown below:
Bill Amount: 35.1    Tip%: 15.0
Tip Amount: $5.265

public class TipCalculator {

  public static void main(String[] args) {

      // initialize the bill/tip variables
      double billAmount = 35.1;
      double tipPercent = 15.0;

      // calculate the tip amount
      double tipAmount = tipPercent / 100 * billAmount;

      // display the amount to tip for this bill
      System.out.println("Bill Amount: " + billAmount + "\tTip%: " + tipPercent
          + "\nTip Amount: $" + tipPercent);
  }
}