Computer Language
Lecture 3

Part 1 : Variables

Josue Obregon

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

April 14, 2025

Class contents

  1. Introduction to Computer Programming and Java
  2. Reading Input and Strings
  3. Variables and calculation with numbers
  4. Conditional statements
  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

Class contents

  1. Introduction to Computer Programming and Java
  2. Reading Input
  3. Variables and calculation with numbers
  4. Conditional statements
  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

  • Introduction to variables
  • Variable assignment
  • Tracing code with variables
  • Naming conventions
  • Reading different type of variables

Objectives

  • Understand the concept of a variable.
    • You know what variable types, names, and values are.
  • Know how to create and use string, integer, floating-point, and boolean variables.

Introduction to variables

  • We’ve already familiarized ourselves with strings to a degree while dealing with user inputs.

  • Let’s turn our attention to learning about other variable types commonly used in Java.

  • A variable can be thought of as a container in which information of a given type can be stored.

  • Examples of these different types include text (String), whole numbers (int), floating-point numbers (double), and whether something is true or false (boolean).

Variable assignment

A value is assigned to a variable using the equals sign (=).

int months = 12;

In the statement above, the value of 12 is assigned to an integer variable called months. The statement could be read as: “the variable months is assigned the value 12”.

Joining variables and strings

A variable’s value can be joined to a string using the + sign, as seen in the following example:

String text = "contains text";
int wholeNumber = 123;
double floatingPoint = 3.141592653;
boolean trueOrFalse = true;

System.out.println("Text variable: " + text);
System.out.println("Integer variable: " + wholeNumber);
System.out.println("Floating-point variable: " + floatingPoint);
System.out.println("Boolean: " + trueOrFalse);
Text variable: contains text
Integer variable: 123
Floating-point variable: 3.141592653
Boolean: true

Exercise 1 - Various variables

  • The Code template tab contains a program that prints the output shown in the Sample Output tab.

  • Modify the program in the right places so that it prints the output shown in the Modified output tab.

public class VariousVariables {

    public static void main(String[] args) {
        // MODIFY THESE:

        int numberOfChicken = 3;
        double baconWeight = 5.5;
        String tractor = "None!";

        // DON'T MODIFY THESE:
        System.out.println("Chicken:");
        System.out.println(numberOfChicken);
        System.out.println("Bacon (kg):");
        System.out.println(baconWeight);
        System.out.println("Tractor:");
        System.out.println(tractor);
        System.out.println("");
        System.out.println("And finally, a summary:");
        System.out.println(numberOfChicken);
        System.out.println(baconWeight);
        System.out.println(tractor);
    }
}
Chicken:
3
Bacon (kg):
5.5
Tractor:
None!

And finally, a summary:
3
5.5
None!
Chicken:
9000
Bacon (kg):
0.1
Tractor:
Zetor

And finally, a summary:
9000
0.1
Zetor

Variable names

  • Variable names are unique - no two variables can have the same name.
  • The program in the following example is faulty as it attempts to create the variable pi twice.
  • The variable is created the first time its declared.
public class Example {
    public static void main(String[] args) {
        double pi = 3.14;
        double pi = 3.141592653;

        System.out.println("The value of pi is: " + pi);
    }
}

Variable type

  • The variable type is stated when the variable is first declared (Line 1).
  • When a new value is assigned to the variable, the type is no longer declared (Line 3).
int value = 10;
System.out.println(value);
value = 4;
System.out.println(value);

Sample output

10
4

Changing a value assigned to a variable

  • A variable exists from the moment of its declaration, and its initial value is preserved until another value is assigned to it.
  • You can change a variable’s value using a statement that comprises the variable name, an equals sign, and the new value to be assigned.
int number = 123;
System.out.println("The value of the variable is " + number);

number = 42;
System.out.println("The value of the variable is " + number);

Output

The value of the variable is 123
The value of the variable is 42

Tracing the code with variables (I)

Let’s look at the preceding program’s execution step-by-step.

  • When a variable appears in the program for the first time, i.e., the computer is told both its type (in this case int) and its name (in this case number), the computer creates a ‘named container’ for the variable.
  • Then, the value on the right side of the equals sign is copied into this named container.

Tracing the code with variables (II)

  • Whenever a variable is referenced by its name in a program – here, we want to print the string “The value of the variable is” followed by the value of the number variable – its value is retrieved from a container that has the corresponding name.

Tracing the code with variables (III)

  • Whenever a value is assigned to a variable (here number = 42), a check is run to see whether a container with the given name already exists.
  • If one does, a new value is copied in the place of the old value, and the old value disappears.
  • If a container of the variable name is not found, the program execution ends in an error message, or it fails to run.

Tracing the code with variables (IV)

  • The variable is then referenced again by its name in the program – we again want to print the string “The value of the variable is” followed by the value of the number variable.
  • We proceed as normal, retrieving the value of number from a container having its name.

Tracing the code with variables (V)

  • At the end of the program, you’ll notice that the original value of the variable has vanished.
  • A variable can hold only one value at a time.

Variable’s type persists

  • Once a variable’s type has been declared, it cannot be changed.
  • For example, a boolean value cannot be assigned to a variable of the integer type, nor can an integer be assigned to a variable of the boolean type.
boolean integerAssignmentWillWork = false;
integerAssignmentWillWork = 42; // Does not work

int value = 10;
integerAssignmentWillWork = value; // Neither does this
  • However, an integer can be assigned to a variable of type double, since Java automatically converts the integer to a double.
double floatingPoint = 0.42;
floatingPoint = 1; // Works

int value = 10;
floatingPoint = value; // Also works

Naming Variables

  • Naming variables is a fundamental aspect of describing a program. Let’s look at two examples.
double a = 3.14;
double b = 22.0;
double c = a * b * b;

System.out.println(c);

Output

1519.76
double pi = 3.14;
double radius = 22.0;
double surfaceArea = pi * radius * radius;

System.out.println(surfaceArea);

Output

1519.76
  • Both of the preceding examples function the same way and output the same result.
  • One of them is, however, much more understandable.
  • The objective here is to compute the surface area of a circle.
  • The value of pi is defined in the first row, the circle’s radius in the second, and the surface area calculated in the third.

Note on variables names

Variables Express the Program and the Problem to Be Solved

  • Programming is a problem-solving tool.

  • The aim is to create solutions for any given problem, such as the automation of control in cars.

  • As a problem is approached, the developer decides on the terms used to describe the problem domain.

  • The terminology that is chosen, such as variable names, will serve to describe the problem for anyone who is to work with it in the future.

  • As you’re wording the problem that you’re solving, think about the concepts related to that problem and appropriate terms that could be used to describe them.

  • If you find it hard to come up with relevant names, think of the ones that definitely do not describe it.

  • After this, settle on some terminology that you’re going to use – the good thing is that you can usually improve on it later on.

Variable naming conventions (I)

Variable naming is limited by certain constraints.

  • Variable names cannot contain certain special symbols, such as exclamation marks (!).
  • Spaces are also not allowed, since they’re used to separate parts of commands. Instead of spaces, the convention in Java is to use a style known as camelCase.

Note!

The first letter of a variable name is always lower-cased:

int camelCaseVariable = 7;

Variable naming conventions (II)

  • Numbers can be used within a variable name as long as the name does not begin with a number. Also, a name cannot consists of numbers only.
int 7variable = 4; // Not allowed!
int variable7 = 4; // Allowed, but is not a descriptive variable name
  • A variable’s name cannot already be in use.
  • These names include, for instance, variables previously defined in the program and commands provided by Java, such as System.out.print and System.out.println.
int System.out.print = 4; // Not Allowed!
int System.out.println = 4; // Not Allowed!
int camelCase = 2;
int camelCase = 5; // Not allowed -- camelCase variable is already in use!

Variable naming conventions (III)

  • Letters containing diacritics (e.g. the letters ä and ö used in Finnish) should also not be used in variable names.
  • You can replace these letters with their non-diacritic equivalents. For example, you should convert ä -> a and ö -> o.

Permissible Variable Names

  • lastDayOfMonth = 20
  • firstYear = 1952
  • name = "Essi"

Impermissible Variable Names

  • last day of month = 20
  • 1day = 1952
  • beware! = 1910 *1920 = 1

The type of the variable informs of possible values

  • A variable’s type is specified when it’s initally declared.

    • For example, a variable containing the string “text” is declared with the statement String string = "text";, and an integer having the value 42 is declared with the statement int value = 42;.
  • A variable’s type determines the types of values that can be assigned to it. String types hold text, int types whole numbers, double floating-point numbers, and boolean types are either true or false.

  • As such, the possible values of a given variable type are limited. For example, a string cannot contain an integer, nor can a double contain a boolean value.

Variable’s types

Type Example Accepted values
Whole number, i.e., int int value = 4; An integer can contain whole numbers whose values lie between -2147483648 and 2147483647.
Floating-point number, i.e., double double value = 4.2; Floating-point numbers contain decimal numbers, with the greatest possible value being approximately 21023. When a decimal number is represented with a floating-point number, the value can be inaccurate as floating-points are incapable of representing all decimal numbers.
String String text = "Hi!"; A string can contain text. Strings are enclosed in quotation marks.
True or false value, i.e., boolean boolean right = true; A boolean contains either the value true or false.

Reading from user

  • In the text-based user interfaces that we’ve used in our programs, the user’s input is always read as a string, since the user writes their input as text.
  • Reading strings from the user has become familiar by this point - we do it using the nextLine-command of the Scanner helper method.
import java.util.Scanner;

public class Program {

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

        System.out.println("Write text and press enter ");
        String text = scanner.nextLine();
        System.out.println("You wrote " + text);
    }
}

Output

Write text and press enter
  (user input) text
You wrote text
  • Other input types, such as integers, doubles, and booleans are also read as text.
  • However, they need to be converted to the target variable’s type with the help of some tools provided by Java.

Convert String to integer

  • The Integer.valueOf command converts a string to an integer. It takes the string containing the value to be converted as a parameter.
String valueAsString = "42";
int value = Integer.valueOf(valueAsString);

System.out.println(value);

Output

42

Reading integers

  • When using a Scanner object, the reading of the value is usually inserted directly into the type conversion. This happens like so:
import java.util.Scanner;

public class Program {

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

        System.out.println("Write a value ");
        int value = Integer.valueOf(scanner.nextLine());
        System.out.println("You wrote " + value);
    }
}

Output

Write a value
  (user input) 42
You wrote 42

Exercise 2 - Integer Input

Write a program that asks the user for a value and then prints the value provided by the user.

Example print 1

Give a number:
  (user input) 3
You gave the number 3

Example print 2

Give a number:
  (user input) 42
You gave the number 42
  • Test the functionality of your program with non-numerical inputs.
  • The program should break as it doesn’t know how to convert these inputs into numbers.
  • We’ll learn how to deal with exceptional cases like these in the advanced programming course.

Convert String to double

  • The Double.valueOf command converts a string to a double. It takes the string containing the value to be converted as a parameter.
String valueAsString = "42.42";
double value = Double.valueOf(valueAsString);
System.out.println(value);

Output

42.42

Reading doubles

  • As with integers, the reading is nested within the conversion. This shown in the code below.
    • It’s possible to also read an integer variable into a double, in which case the value is converted automatically to type double.
    • Below there are two sample outputs, one for when the user inputs an floating-point number and one for when the user inputs an integer
import java.util.Scanner;

public class Program {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Write a value ");
        double value = Double.valueOf(scanner.nextLine());
        System.out.println("You wrote " + value);
    }
}

Output (with floating-point number input)

Write a value
  (user input) 1234.2
You wrote 1234.2

Output (with integer input)

Write a value
  (user input) 18
You wrote 18.0

Exercise 3 - Double Input

Write a program that asks the user for a floating-point number using the variable type Double. The program then prints the user’s input value.

Example print 1

Give a number:
  (user input) 3.14
You gave the number 3.14

Example print 2

Give a number:
  (user input) 2.718
You gave the number 2.718

Convert String to boolean

  • The Integer.valueOf command converts a string to an integer and the Double.valueOf converts it to a floating-point.
  • The valueOf command also appears when converting a string to a boolean – this is done with the command Boolean.valueOf.
  • Boolean variables can either have the value true or false.
  • When converting a string to a boolean, the string must be “true” if we want the boolean value to be true.
  • The case is insensitive here: both “true” and “TRue” turn into the boolean value of true.
  • All other strings turn into the boolean false.

Convert String to boolean example code

import java.util.Scanner;

public class program {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Write a boolean ");
        boolean value = Boolean.valueOf(scanner.nextLine());
        System.out.println("You wrote " + value);
    }
}

Output

Write a boolean
  (user input) I wont'!
You wrote false

Output

Write a boolean
  (user input) TRUE
You wrote true

Output

Write a boolean
  (user input) true
You wrote true

Exercise 4 - Boolean Input

Write a program that asks the user for a boolean value. The program should then print the value provided by the user.

Example print 1

Write something:
  (user input) santa does not exist
True or false? false

Example print 2

Write something:
  (user input) TRUE
True or false? true

Summary

Finally, a summary:

import java.util.Scanner;

public class Program {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String text = scanner.nextLine();
        int integer = Integer.valueOf(scanner.nextLine());
        double floatingPoint = Double.valueOf(scanner.nextLine());
        boolean trueOrFalse = Boolean.valueOf(scanner.nextLine());

        // and so on
    }
}

Exercise 5 - Different Types of Input

Write a program that asks the user for a string, an integer, a floating-point number, and a boolean. The program should then print the values given by the user.

Give a string:
  (user input) bye-bye
Give an integer:
  (user input) 11
Give a double:
  (user input) 4.2
Give a boolean:
  (user input) true
You gave the string bye-bye
You gave the integer 11
You gave the double 4.2
You gave the boolean true
Give a string:
  (user input) Oops!
Give an integer:
  (user input) -4
Give a double:
  (user input) 3200.1
Give a boolean:
  (user input) false
You gave the string Oops!
You gave the integer -4
You gave the double 3200.1
You gave the boolean false

Checking our learning objectives

  • Understand the concept of a variable.
    • You know what variable types, names, and values are.
  • Know how to create and use string, integer, floating-point, and boolean variables.

Next

  • Part 2: calculating with numbers

Acknowledgements


Back to title slide Back to lecture slides index