Skip to main content

1. Writing Simple Expressions in Java

Prerequisites

This module only assumes that the learner knows how to write a "Hello World" program in Java.

Overview

Expressions are used frequently in Java programs. When you write an expression, you are asking Java to calculate value. This is similar to entering an arithmetic expression into a calculator, where the calculator computes the answer.

Expressions in statements

A statement may contain zero or more input expressions. Java computes the value(s) of these expressions in the statement, and then does something with the values.

For example, System.out.println(1 + 2) is a statement. Java first evaluates the expression 1 + 2 to get 3. It then passes this result to System.out.println, which does something with the value (prints the value to the screen).

Sequencing

Evaluation of expressions is fundamental and it's important to introduce evaluation here, as its a prerequisite for the rest of this module.

Expressions are always part of statements. Because a program consists of many statements, expressions appear in many places in a Java program.

Parts of an expression

In the expression 1 + 2, + is called the operator and 1 and 2 are the operands. Operators perform operations on the operands, which are inputs to the operators.

note

In this tutorial, operands are referred to as inputs.

There are different types of operators and operands. First, we will only consider integer operands (such as 1) and string operands (such as "apple"), and explore the types of operators that can be used with these operands.

Expressions can be of any length. This module only looks at basic expressions:

  • That contain one operator and two operands (such as 1 + 2 and "apple" + "banana")
  • That contain no operator and one operand (such as 10). In this case, the expression evaluates to the operand itself.

Types of operators used in expressions

In this section will cover four types of operators used in expressions:

  • Arithmetic operators such as +, -, *, and /
  • Comparison operators such as == (equal) and <> (not equal)
  • Logical operators such as && (and)

An additional type of operator (calling a class method) will be covered in the next section. You were introduced to classes and methods in the previous section.

Sequencing

The sections on arithmetic, comparison, and logical operators are presented below, in no particular order.

Arithmetic operators

The following program demonstrates some of the arithmetic operators that can be used in Java.

Example 1

Create a new file ComparisonOperatorsDemo.java and copy in the following code.

public class ArithmeticOpertorsDemo {
public static void main(String[] args) {
System.out.println(10 + 20); // Addition
System.out.println(10 - 20); // Subtraction
System.out.println(10 * 2); // Multiplication
System.out.println(10 / 2); // Division without the remaindr
System.out.println(10 % 3); // The remainder of division
System.out.println("apple" + "banana"); // When used with strings, + appends one string to another
}
}

Output:

30
-10
20
5
1
applebanana

Comparison operators

Example 2

The following program demonstrates some of the comparison operators that can be used in Java. Create a new file ComparisonOperatorsDemo.java and copy in the following code.

public class ComparisonOperatorsDemo {
public static void main(String[] args) {
System.out.println(1 == 2); // Does 1 equal 2?
System.out.println("apple" == "banana") // Is apple equal to banana?
System.out.println(1 != 2); // Does 1 not equal 2?

System.out.println(1 > 1);
System.out.println(2 > 1); // Is 2 greater than 1?
System.out.println("strawberry" > "apple");

System.out.println(1 < 1); // Is 1 less than 1?
System.out.println(2 < 1); //Is 2 less than 1?
System.out.println("banana" < "carrot")
}
}

Output:

true
false
false
true
false
true
true
false
false
true

Relational operators

Example 3

The following program demonstrates some of the relational operators that can be used in Java. Create the file RelationalOperatorsDemo.java containing the following code:

public class RelationalOperatorsDemo {
public static void main(String[] args) {
System.out.println(true && true);
System.out.println(true && false);
System.out.println(true || true);
System.out.println(true || false);
System.out.println(!true);
System.out.println(!false);
}
}

Assignment operators in expressions

The assignment operator sets a variable to a value. The assignment operator is discussed in a future module.

Operands

Operands are inputs to operators. The types of operands are:

  • Literals
  • Return values from calling class methods.
  • Variable values

Literals

Literals are used without needing further computation. For example, 1 (an integer) and apple (a string) are both literals.

Return values from calling class methods

Sequencing

This discussion of calling class methods digresses from the subject of expressions. Yet, return values from class methods are important types of operands that can be read in expressions.

A class is a fundamental unit for organizing a Java programs.

A class contains related functions (methods) and may also contain data that the functions operate on. In this section, we will only call class methods and not be concerned with classes that store data.

An example of a class is Math. It contains methods such as Max (maximum), Min (minimum) and Abs (absolute value) methods. Some class methods, such as the three just mentioned, return a value. When a method returns a value, the value can be used in an expression.

System.out.println(Math.Max(20,50));
System.out.println(Math.Min(20,50));
System.out.println(Math.Abs(-100));

Output:

50
20
200

Using variables in expressions

Sequencing

This discussion of variables digresses from the subject of expressions. Yet, variable values are important types of operands that can be read in expressions.

A variable is a storage location for data. A variable value is the data stored at the location of the variable.

Expressions can read the values of variables.

One use for a variable is to store user input.

The following program prompts the user for integer input, stores the input in a variable, and prints the variable value to the screen. Read through the program and focus on the following lines. The other lines are not important now.

  • int number; creates a variable. Creating a variable is also known as declaring a variable. This example declares a variable number of type int.

  • number = s.nextInt(); prompts the user for integer input, and stores the entered value in the variable number.

  • System.out.println(number); prints out the number.

  • System.out.println(number * number); prints out the square of the number. This line demonstrates that number * number is an expression, where the variable is used twice.

class Main {
public static void main(String[] args) {
Scanner s = new java.util.Scanner(System.in);
System.out.println("Enter a number");
int number;

numbnr = s.nextInt();
s.close();
System.out.println(number);
System.out.println(number * number);
}
}

This program has the following output. Assume the user has entered 5 when prompted.

Output:

Enter a number
5
The number is 5
The number squared is 25

Example 2

Write a program that prompts the user for three numbers and stores them in variables number_1, number_1, and number_3. The program prints True if number_2 is in between number_3, and prints False otherwise.

Use the following program code, as a starting point. This code asks the user to input three numbers that are stored in the variable number_1, number_2, and number_3. How this code works is not important right now.

class Main {
public static void main(String[] args) {
Scanner s = new java.util.Scanner(System.in);
int number_1;
int number_2;
int number_3;

System.out.println("Enter number 1");
number_1 = s.nextInt();
System.out.println("Enter number 2");
number_2 = s.nextInt();
System.out.println("Enter number 3");
number_3 = s.nextInt();
s.close();

System.out.println(number_2 >= number_1 && number_1 <= number_3)

}
}

Problem 1

Write a program that prompts the user to enter a string and display the first two characters of the string. When displaying the characters, use only one statement and call the method <string>.charAt(<position>) twice. Use the code below to prompt the user to enter a string.

class Main {
public static void main(String[] args) {
Scanner s = new java.util.Scanner(System.in);
System.out.println("Enter a string");
String st;

st = s.nextLine();
s.close();

<Display first two characters of the string>
}
}

:::Sequencing info This is an application. :::

Next Steps

In the next module, you will learn how to use expressions to perform complex calculations.