Computer Language
Lecture 3

Part 2 : Calculating with numbers

Josue Obregon

Seoul National University of Science and Technology
Information Technology Management
Lecture slides index

March 19, 2025

Class contents

  1. Introduction to Computer Programming and Java
  2. Reading Input
  3. Variables and calculation with numbers
  4. Conditional statements and recurrent patterns when programming
  5. Repeating functionality
  6. Methods & Debugging
  7. Lists, Arrays and Strings
  8. Midterm
  1. Introduction to Object Oriented Programming
  2. Deeper look into Object Oriented Programming
  3. Inheritance and Interfaces I
  4. Inheritance and Interfaces II
  5. Class diagrams, packages and exceptions
  6. Project Live Code Review and Evaluation
  7. Final examination

Agenda

  • Mathematical operations and precedence
  • Expression and statement
  • Expression evaluation
  • Division
  • Type casting
  • Memory tables

Objectives

  • Learn to perform calculations with the help of variables.
  • Know how to form printable statements including both calculations (expressions) and strings.

Introduction to mathematical operations

  • The basic mathematical operations are both familiar and straightforward: addition +, subtraction -, multiplication *, and division /.
  • The precedence is also familiar: operations are performed from left to right with the parentheses taken into account.
  • Expressions involving * and / are calculated before those involving + and -, as is customary in elementary school mathematics.
int first = 2;
System.out.println(first); // prints 2
int second = 4;
System.out.println(second); // prints 4

// The sum of the values of the variables first and second is assigned to the variable sum
int sum = first + second; 
System.out.println(sum); // prints 6

Precedence and parentheses

  • You can affect the order of operations by using parentheses.
  • Operations within parentheses are performed before those outside them.
int calculationWithParentheses = (1 + 1) + 3 * (2 + 5);
System.out.println(calculationWithParentheses); // prints 23

int calculationWithoutParentheses = 1 + 1 + 3 * 2 + 5;
System.out.println(calculationWithoutParentheses); // prints 13
  • The example above can also be divided into steps.
int calculationWithParentheses = (1 + 1);
System.out.println(calculationWithParentheses); // prints 2
calculationWithParentheses = calculationWithParentheses + 3 * (2 + 5);
System.out.println(calculationWithParentheses); // prints 23

int calculationWithoutParentheses = 1 + 1;
calculationWithoutParentheses = calculationWithoutParentheses + 3 * 2;
calculationWithoutParentheses = calculationWithoutParentheses + 5;
System.out.println(calculationWithoutParentheses); // prints 13

Exercise 1 - Seconds in a day

  • In the exercise template, implement a program that asks the user for the number of days. After that, the program prints the number of seconds in the given number of days.
  • Earlier we learned to read an integer in the following manner:
Scanner scanner = new Scanner(System.in);

System.out.println("Give a number:");
int number = Integer.valueOf(scanner.nextLine());
System.out.println("You gave " + number);
import java.util.Scanner;

public class SecondsInADay {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Write your program here

    }
}

Sample 1

How many days would you like to convert to seconds?
  (user input) 1
86400

Sample 2

How many days would you like to convert to seconds?
  (user input) 3
259200
How many days would you like to convert to seconds?
  (user input) 7
604800

What does this program print?

int first = 10;
int second = first + 5;
first = 20;

System.out.println(second);
  • 10
  • 15
  • 20
  • 25

Expression and Statement

  • An expression is a combination of values that is turned into another value through a calculation or evaluation.
  • The statement below includes the expression 1 + 1 + 3 * 2 + 5, which is evaluated prior to its assignment to the variable.
int calculationWithoutParentheses = 1 + 1 + 3 * 2 + 5;
  • The evaluation of an expression is always performed before its value is assigned to a variable. As such, the calculation “1 + 1 + 3 * 2 + 5” in the example above is performed before the result is assigned to the variable.

Expression evaluation

  • An expression is evaluated where it occurs in the program’s source code.
  • As such, the evaluation can occur within a print statement, if the expression is used in calculating the value of the print statement’s parameter.
int first = 2;
int second = 4;

System.out.println(first + second); // prints 6
System.out.println(2 + second - first - second); // prints 0
  • An expression does not change the value stored in a variable unless the expression’s result is assigned to a variable or used as a parameter, for instance, in printing.
int first = 2;
int second = 4;

// the expression below does not even work, since
// the result is not assigned to any variable
// or given as a parameter to a print statement
first + second;

Expressions and variable value

What does the following program print?

int age = 32;
int height = 178;
height = age + 10;

System.out.println(age);
  • 42
  • 32
  • 188
  • 178

Calculating and Printing

  • The command System.out.println prints the value of a variable.
  • The string literal to be printed, which is marked by quotation marks, can be appended with other content by using the operation +.

Example 1

int length = 42;
System.out.println("Length " + length);
Length 42

Example 2

System.out.println("here is an integer --> " + 2);
System.out.println(2 + " <-- here is an integer");
here is an integer --> 2
2 <-- here is an integer

Calculating and Printing (II)

  • If one of the operands of the operation + is a string, the other operand will be changed into a string too during program execution.
  • In the example below, the integer 2 is turned into the string “2”, and a string has been appended to it.
  • The precedence introduced earlier also apply here:
System.out.println("Four: " + (2 + 2));
System.out.println("But! Twenty-two: " + 2 + 2);

Exercise 2 - Sum of two numbers

  • Write a program that asks the user for two numbers. After this, the program prints the sum of the numbers given by the user.
  • When you ask for multiple numbers, create a separate variable for each:
Scanner scanner = new Scanner(System.in);

System.out.println("Give the first number:");
int first = Integer.valueOf(scanner.nextLine());
System.out.println("Give the second number:");
int second = Integer.valueOf(scanner.nextLine());

// do something with the numbers

Sample 1

Give the first number:
(user input) 8
Give the second number:
(user input) 3
The sum of the numbers is 11

Sample 2

Give the first number:
(user input) 3
Give the second number:
(user input) -1
The sum of the numbers is 2

Exercise 3 - Sum of three numbers

  • Write a program that asks the user for three numbers. After this, the program prints the sum of the numbers given by the user.

Sample output 1

Give the first number:
(user input) 8
Give the second number:
(user input) 3
Give the third number:
(user input) 3
The sum of the numbers is 14

Sample output 2

Give the first number:
(user input) 3
Give the second number:
(user input) -1
Give the third number:
(user input) 2
The sum of the numbers is 4

More on expressions

  • Applying this knowledge, we can create an expression consisting of some text and a variable, which is evaluated in connection with the printing:
int x = 10;

System.out.println("The value of the variable x is: " + x);

int y = 5;
int z = 6;

System.out.println("y is " + y + " and z is " + z);

Output

The value of the variable x is: 10
y is 5 and z is 6

Exercise 4 - Addition formula

  • Create a program that can be used to add two integers together.
  • In the beginning, the user is asked to give two integers that are to be summed.
  • The program then prints the formula that describes the addition of the numbers.

Example output 1

Give the first number:
(user input) 5
Give the second number:
(user input) 4
5 + 4 = 9

Example output 2

Give the first number:
(user input) 73457
Give the second number:
(user input) 12888
73457 + 12888 = 86345

Exercise 5 - Multiplication formula

  • Similar to the previous exercise, create a program that multiplies the values stored in two integer variables.
  • For instance, if the entered numbers are 2 and 8, the program should print the output of the left side.
  • Likewise, if the entered numbers are 277 and 111, the program should print the output of the right side.

Example output 1

Give the first number:
(user input) 2
Give the second number:
(user input) 8
2 * 8 = 16

Example output 2

Give the first number:
(user input) 277
Give the second number:
(user input) 111
277 * 111 = 30747

Greatest possible integer

  • Once you have completed the previous exercises, try finding out the greatest possible multiplication that you can calculate.
  • The reason behind the phenomenon you’ll observe is that the value of an integer value is capped at the maximum of 231-1 (i.e. 2147483647).
  • This is because integer variables are represented with 32 bits in the computer’s memory.

Integer Min and Max

Code for printing the maximum and minimum integer values

public class Test
{
   public static void main(String[] args)
   {
     System.out.println(Integer.MIN_VALUE);
     System.out.println(Integer.MAX_VALUE);
   }
}

Division of integers

  • Division of integers is a slightly trickier operation.
  • The types of the variables that are part of the division determine the type of result achieved by executing the command.
  • If all of the variables in the division expression are integers, the resulting value is an integer as well.
int result = 3 / 2;
System.out.println(result);
1
  • The previous example prints 1 as output, this is because both 3 and 2 are integers, and the division of two integers always produces an integer.
int first = 3;
int second = 2;
double result = first / second;
System.out.println(result);
1
  • The output is 1 again, since first and second are (still) integers.

Division of floating point numbers

  • If the dividend or divisor (or both!) of the division is a floating point number, the result is a floating point number as well.
double whenDividendIsFloat = 3.0 / 2;
System.out.println(whenDividendIsFloat); // prints 1.5

double whenDivisorIsFloat = 3 / 2.0;
System.out.println(whenDivisorIsFloat); // prints 1.5

Output

1.5
1.5

Type casting

  • An integer can be converted into a floating point number by placing a type-casting operation (double) before it:
int first = 3;
int second = 2;

double result1 = (double) first / second;
System.out.println(result1); // prints 1.5

double result2 = first / (double) second;
System.out.println(result2); // prints 1.5

double result3 = (double) (first / second);
System.out.println(result3); // prints 1.0

Output

1.5
1.5
1.0

Rounding when type casting

  • The last example produced an incorrectly rounded result, because the integer division is executed before the type casting.
  • If the result of a division is assigned to an integer-type variable, the result is automatically an integer.
int integer = (int) 3.0 / 2;
System.out.println(integer);
1
  • The next example prints “1.5”; the dividend is converted into a floating-point number by multiplying it with a floating-point number prior to executing the division.
int dividend = 3;
int divisor = 2;

double result = 1.0 * dividend / divisor;
System.out.println(result);
1.5

Calculating the average

  • The next exercises task you with calculating the average of the entered numbers. Let’s briefly review the concept of average.

  • An average refers to the sum of numbers divided by their count. For instance, the average of the numbers 5 and 3 can be calculated with the formula (5+3)/2. Similarly, the average of the numbers 1, 2, and 4 is produced by the formula (1+2+4)/3.

  • In the context of programming, there are a few things to keep in mind.

    1. Dividing by zero is typically not permitted. This implies that calculating the average of zero numbers is impossible.
    2. If the program handles both the sum of the numbers and their total count as integers, one (or both) of the variables should be casted to a floating-point number by multiplying it by 1.0 before the division.

Exercise 6 - Average of two numbers

  • Write a program that asks the user for two integers and prints their average.

Example output

Give the first number:
(user input) 8
Give the second number:
(user input) 2
The average is 5.0

Exercise 7 - Average of three numbers

  • Write a program that asks the user for three integers and prints their average.

Example output 1

Give the first number:
(user input) 8
Give the second number:
(user input) 2
Give the third number:
(user input) 3
The average is 4.333333333333333

Example output 2

Give the first number:
(user input) 9
Give the second number:
(user input) 5
Give the third number:
(user input) -1
The average is 4.333333333333333

Division

What does the following program print?

int dividend = 3;
int divisor = 2;

double result = dividend / divisor * 1.0;
System.out.println(result);
  • 3.0
  • 1.0
  • 1.5
  • 2.0

Exercise 8 - Simple calculator

  • Write a program that asks the user for two numbers and prints their sum, difference, product, and quotient. Two examples of the execution of the program are given below.

Example output 1

Give the first number:
(user input) 8
Give the second number:
(user input) 2
8 + 2 = 10
8 - 2 = 6
8 * 2 = 16
8 / 2 = 4.0

Example output 2

Give the first number:
(user input) 9
Give the second number:
(user input) 2
9 + 2 = 11
9 - 2 = 7
9 * 2 = 18
9 / 2 = 4.5

Misunderstanding 1

  • Viewing value assignment as a transfer instead of a copy operation: once first = second has been executed, it’s often assumed that the value of the variable second has been moved to the value of the variable first, and that the variable second no longer holds a value, or that its value is 0, for instance. This is incorrect, as executing first = second means that the value in the position specified by second is merely copied to the place specified by the variable first. Hence, the variable second is not modified.
int first = 1;
int second = 2;
first = second;

Misunderstanding 2

  • Viewing value assignment as creating a dependency instead of being a copy operation: once first = second has been executed, it’s often assumed that any change in the value of the variable second is automatically also reflected in the value of the variable first. This is incorrect; assignment – i.e., copying – is a one-off event. It only occurs when the program code first = second is executed.
int first = 1;
int second = 2;
first = second;

Misunderstanding 3

  • The third misunderstanding concerns the direction of copying: it’s often thought that in executing first = second the value of the variable second is set as the value of the variable first. The confusion also manifests itself in situations where the programmer accidentally writes e.g. 42 = value – fortunately, IDEs provide support on this issue too (we will start using IDEs soon).
int first = 1;
int second = 2;
first = second;
42 = first // This does not work

Memory tables

  • Perhaps the best way to understand a program’s execution flow is through the use of pen and paper and memory tables (basic version).
  • As you’re reading the program (and sometimes explaining it to your rubber duck), do the following:
    1. Create a new Memory Table every time you run a program.
    2. Write the program name in the box at the top of table.
    3. When a variable is created, add it as a row in the table (variable name in the “name” column; value in “value” column.
    4. When a variable is updated, find the variable by name, cross out the previous value and write in the new one.

Don’t forget!

  • The value on the right-hand side of the equality sign is copied and assigned to the variable on the left-hand side.
  • If the value on the right-hand is an expression, it should be evaluated first, and then assigned to the varuable on the left-hand side.

Memory tables example

Analyze the execution of this code fragment using memory tables.

int first = (1 + 1);
int second = first + 3 * (2 + 5);

first = 5;

int third = first + second;
System.out.println(first);
System.out.println(second);
System.out.println(third);

Don’t forget!

  • The value on the right-hand side of the equality sign is copied and assigned to the variable on the left-hand side.
  • If the value on the right-hand is an expression, it should be evaluated first, and then assigned to the varuable on the left-hand side.

Checking our learning objectives

  • Learn to perform calculations with the help of variables.
  • Know how to form printable statements including both calculations (expressions) and strings.

Next week

  • Conditional statements

Acknowledgements


Back to title slide Back to lecture slides index