University College of Applied SciencesProgramming 1
العربية
Lecture 3 · 100 min

Variables and Data Types

How does a program remember, change and use values?

Prepared by: Eng. Badereddin Mohammed Elhalimi · Eng. Mohammed Zuhair Kouhail

By the end of this lecture you will be able to

  1. Explain what a variable is using the box example
  2. Declare a variable, assign it a value and use it
  3. Choose the right data type for each value
  4. Use operators to calculate and update values
  5. Name variables using Java rules and fix naming errors
In this lecture
  1. Every app remembers values that change while it runs
  2. A variable is a named box that holds one value
  3. Three steps to work with any variable
  4. Five data types cover most of our first programs
  5. Java has eight primitive types, each with a fixed size
  6. First program: store two numbers and add them
  7. The value changes, the name stays: track score line by line
  8. Variable names follow rules set by the compiler
  9. The compiler rejects a value of the wrong type
  10. Swap challenge: a third variable saves the value
  11. The + sign joins strings into one new string
  12. Five arithmetic operators
  13. ++ and -- change a value by one, before or after use
  14. += and -= update a variable in one short step
  15. Final exercise: a program that prints a student card
  16. Review questions
Part one: variables and their types

Every app remembers values that change while it runs

Mobile game

Your score goes up with every level you finish and stays at the top of the screen.

Calculator

The M+ button saves a number so you can use it after several operations.

Online store

The cart total changes every time you add or remove a product.

A variable is a named box that holds one value

firstNumber2int
secondNumber3int
  • A program needs to keep values while it runs.
  • A number alone is not a variable; a variable is a name that holds it.
  • A box holds only one value at a time.
  • Variables are not only for numbers.
PartMeaning
intData type: a whole number
firstNumberVariable name
2The value stored in it

Three steps to work with any variable

Declare

Reserve a box and give it a type and a name. It has no value yet.

int age;
Assign

Put a value in the box using =. Read it as "takes the value".

age = 19;
Use

Write the variable name, and the program reads the value stored in it.

println(age);

Try the three steps

Run the program, then press "Debug line by line" and watch the box appear and fill. Change the age and run it again.

public class Age {
    public static void main(String[] args) {
        int age;
        age = 19;
        System.out.println(age);
    }
}
Output
19

The name goes on the left

Fix the line so the program works and prints 19.

public class Age {
    public static void main(String[] args) {
        int age;
        19 = age;
        System.out.println(age);
    }
}
Compiler messageunexpected type
Show the fix
public class Age {
    public static void main(String[] args) {
        int age;
        age = 19;
        System.out.println(age);
    }
}
Output
19

Why? The left side of = must be a box that receives a value, and the number 19 is not a box.

Five data types cover most of our first programs

TypeHoldsExampleHow to spot it
intA whole number19No decimal point
doubleA decimal number3.75Has a decimal point
charOne character'A'Inside ' '
StringText"Sara"Inside " "
booleanTrue or falsetrueOnly two values

All five types in one program

public class Types {
    public static void main(String[] args) {
        int age = 19;
        double gpa = 3.75;
        char grade = 'A';
        String name = "Sara";
        boolean passed = true;

        System.out.println(name);
        System.out.println(age);
        System.out.println(gpa);
        System.out.println(grade);
        System.out.println(passed);
    }
}
Output
Sara
19
3.75
A
true

Which type fits the number of students in a class, such as 32?

Which type fits the price of a book, such as 12.5?

Which type fits "Has the student paid the fees?"

Java has eight primitive types, each with a fixed size

This course uses int, double, char and boolean; the others store the same kinds of values in more or less memory.

TypeSizeRange or examples
booleanLogical valuestrue, false
byte8 bits-128 … 127
char16 bitsOne Unicode character: 'a'
short16 bits-32,768 … 32,767
int32 bitsAbout 2.1 billion, positive or negative
long64 bits10L
float32 bitsAbout 7 significant digits: 3.14f
double64 bitsAbout 16 significant digits: 3.14

What happens when the box is full?

Every type has a limit. Add 1 to the largest int, then change the type to long and add L to the number.

public class Limits {
    public static void main(String[] args) {
        int biggest = 2147483647;
        System.out.println(biggest);
        System.out.println(biggest + 1);
    }
}
Output
2147483647
-2147483648
Part two: let's code

First program: store two numbers and add them

  1. Write the lines inside main
  2. Predict the output before running
  3. Run itIn the lab press F6; here use the Run button or Ctrl+Enter.
  4. Change the two values and run again
package firstprogram;

public class FirstProgram {
    public static void main(String[] args) {
        int firstNumber = 2;
        int secondNumber = 3;
        int sum = firstNumber + secondNumber;
        System.out.println(sum);
    }
}
Output
5

Quotation marks separate a variable name from text. What does this print?

public class Names {
    public static void main(String[] args) {
        int sum = 5;
        System.out.println(sum);
        System.out.println("sum");
        System.out.println("Sum = " + sum);
    }
}
Show the output
Output
5
sum
Sum = 5

Why? Without quotation marks the program prints the value; inside them it prints the word as written. The + joins text and a variable.

The value changes, the name stays: track score line by line

What is the final value of score?

public class Score {
    public static void main(String[] args) {
        int score = 10;
        score = score + 5;
        score = score * 2;
        System.out.println(score);
    }
}
Show the output
Output
30

Why? Line 2 is not a math equation: we calculate the right side first (10 + 5), then put the result in the box and the old value is erased. Then 15 × 2 = 30.

Variable names follow rules set by the compiler

NameVerdictWhy
2ndNumberNot allowedStarts with a digit
my ageNot allowedHas a space
intNot allowedA reserved word in Java
total%Not allowedThe symbol % is not allowed in names
secondNumberAllowed and clearStarts with a letter
myAgeAllowed and clearTwo words joined together
totalPriceAllowed and clearDescribes what it stores
AgeAllowed, but avoid itA different name from age, but it breaks the camelCase convention
total$Allowed, but avoid it$ and _ are allowed, but programmers rarely use them in names

Fix the variable name

public class Naming {
    public static void main(String[] args) {
        int 2ndNumber = 7;
        System.out.println(2ndNumber);
    }
}
Compiler messagenot a statement
Show the fix
public class Naming {
    public static void main(String[] args) {
        int secondNumber = 7;
        System.out.println(secondNumber);
    }
}
Output
7

Why? A name cannot start with a digit. The compiler reads 2 as a number and cannot make sense of the rest, which is why the message looks unrelated to the real cause.

The compiler rejects a value of the wrong type

Planned test

We put the age inside quotation marks. Notice the red underline in the editor, then fix the line.

public class Age {
    public static void main(String[] args) {
        int age = "19";
        System.out.println(age);
    }
}
Compiler messageincompatible types: String cannot be converted to int
Show the fix
public class Age {
    public static void main(String[] args) {
        int age = 19;
        System.out.println(age);
    }
}
Output
19

Why? The type decides what the box accepts: a box made for numbers does not accept text.

Another common error

We used a variable before declaring it.

public class Age {
    public static void main(String[] args) {
        System.out.println(age);
        int age = 19;
    }
}
Compiler messagecannot find symbol
Show the fix
public class Age {
    public static void main(String[] args) {
        int age = 19;
        System.out.println(age);
    }
}
Output
19

Why? The compiler reads top to bottom, so it does not know the name age before the line that declares it.

Swap challenge: a third variable saves the value

Trace the swap

Press "Debug line by line" and watch the three boxes. Then remove the int temp = a; line and see what happens.

public class Swap {
    public static void main(String[] args) {
        int a = 5;
        int b = 9;

        int temp = a;
        a = b;
        b = temp;

        System.out.println(a);
        System.out.println(b);
    }
}
Output
9
5
Part three: operators in action

The + sign joins strings into one new string

Joining text with + is called concatenation. Java reads + from left to right, and that is where the trap lies.

Predict: text and numbers

public class Concat {
    public static void main(String[] args) {
        System.out.println("Total: " + 2 + 3);
        System.out.println(2 + 3 + " total");
        System.out.println("Total: " + (2 + 3));
    }
}
Show the output
Output
Total: 23
5 total
Total: 5

Why? In line 1, "Total: " + 2 becomes text, so 3 is stuck onto it. In line 2, 2 + 3 is added first because both are numbers. The parentheses in line 3 force the addition before the join.

Pair activity: print your full name

Declare two String variables, firstName and lastName, holding Sara and Ali, then print the full name with a space between them, using concatenation.

public class FullName {
    public static void main(String[] args) {
        // Declare firstName and lastName here

    }
}
Expected output
Sara Ali
Hint 1

You need a piece of text between them holding one space: " ".

Solution
public class FullName {
    public static void main(String[] args) {
        String firstName = "Sara";
        String lastName = "Ali";
        System.out.println(firstName + " " + lastName);
    }
}

Five arithmetic operators

OperatorNameA = 10, B = 20Note
+Addition30Adds both sides
-Subtraction-10Right from left
*Multiplication200Multiplies both sides
/Division0Dividing whole numbers drops the decimal
%Modulo10Gives the remainder

Change the values and predict

Change A to 17 and B to 5, and predict all five results before running.

public class Arithmetic {
    public static void main(String[] args) {
        int A = 10;
        int B = 20;
        System.out.println(A + B);
        System.out.println(A - B);
        System.out.println(A * B);
        System.out.println(A / B);
        System.out.println(A % B);
    }
}
Output
30
-10
200
0
10

Turn seconds into minutes and seconds

The variable total holds 125 seconds. Work out the minutes and the remaining seconds using / and %, then print them as in the expected output.

public class Duration {
    public static void main(String[] args) {
        int total = 125;
        // Work out the minutes and the seconds here

    }
}
Expected output
Minutes: 2
Seconds: 5
Hint 1

A minute has 60 seconds, and dividing whole numbers drops the decimal: total / 60.

Hint 2

The remaining seconds are the remainder: total % 60.

Solution
public class Duration {
    public static void main(String[] args) {
        int total = 125;
        int minutes = total / 60;
        int seconds = total % 60;
        System.out.println("Minutes: " + minutes);
        System.out.println("Seconds: " + seconds);
    }
}

++ and -- change a value by one, before or after use

Prefix: ++x

Adds one first, then uses the new value. Result: y = 35, x = 35.

int x = 34;
int y = ++x;
Postfix: x++

Uses the old value first, then adds one. Result: y = 34, x = 35.

int x = 34;
int y = x++;

Vote: what does each line print?

public class Vote {
    public static void main(String[] args) {
        int x = 14;
        System.out.println(x++);
        System.out.println(x);
    }
}
Show the output
Output
14
15

Why? x++ gives the old value 14 to print, then x becomes 15.

+= and -= update a variable in one short step

The rule: Java applies the operator to the old value, and the result replaces it. *= and /= work the same way.

Start with num1 = 4 and num2 = 8, and write num2 on paper after each line.

public class Compound {
    public static void main(String[] args) {
        int num1 = 4;
        int num2 = 8;
        num2 += num1;
        System.out.println(num2);
        num2 -= num1;
        System.out.println(num2);
        num2 *= 3;
        System.out.println(num2);
    }
}
Show the output
Output
12
8
24

Why? num2 += num1 means num2 = num2 + num1, which is 12. Subtracting 4 gives 8, and multiplying by 3 gives 24.

Final exercise: a program that prints a student card

Student card

Declare three variables: String name holding Ahmed, double gpa holding 3.75 and int courses holding 5. Then print each on its own line, as in the expected output.

public class StudentCard {
    public static void main(String[] args) {
        // Declare the three variables, then print them

    }
}
Expected output
Name: Ahmed
GPA: 3.75
Courses: 5
Hint 1

Join text and a variable with +, like: "Name: " + name.

Hint 2

You need three println statements.

Solution
public class StudentCard {
    public static void main(String[] args) {
        String name = "Ahmed";
        double gpa = 3.75;
        int courses = 5;
        System.out.println("Name: " + name);
        System.out.println("GPA: " + gpa);
        System.out.println("Courses: " + courses);
    }
}

Review questions

What is the difference between declaring and assigning?

Which type fits a temperature like 36.6?

Why does the compiler reject the name 2ndNumber?

What is x after these two lines?

public class Review {
    public static void main(String[] args) {
        int x = 4;
        x = x * 3;
        System.out.println(x);
    }
}
Show the output
Output
12

Why? The right side uses the old value: 4 × 3 = 12.