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
- Explain what a variable is using the box example
- Declare a variable, assign it a value and use it
- Choose the right data type for each value
- Use operators to calculate and update values
- Name variables using Java rules and fix naming errors
In this lecture
- Every app remembers values that change while it runs
- A variable is a named box that holds one value
- Three steps to work with any variable
- Five data types cover most of our first programs
- Java has eight primitive types, each with a fixed size
- First program: store two numbers and add them
- The value changes, the name stays: track score line by line
- Variable names follow rules set by the compiler
- The compiler rejects a value of the wrong type
- Swap challenge: a third variable saves the value
- The + sign joins strings into one new string
- Five arithmetic operators
++and--change a value by one, before or after use+=and-=update a variable in one short step- Final exercise: a program that prints a student card
- Review questions
Every app remembers values that change while it runs
Your score goes up with every level you finish and stays at the top of the screen.
The M+ button saves a number so you can use it after several operations.
The cart total changes every time you add or remove a product.
A variable is a named box that holds one value
- 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.
| Part | Meaning |
|---|---|
int | Data type: a whole number |
firstNumber | Variable name |
2 | The value stored in it |
Three steps to work with any variable
Reserve a box and give it a type and a name. It has no value yet.
int age;Put a value in the box using =. Read it as "takes the value".
age = 19;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);
}
}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);
}
}unexpected typeShow the fix
public class Age {
public static void main(String[] args) {
int age;
age = 19;
System.out.println(age);
}
}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
| Type | Holds | Example | How to spot it |
|---|---|---|---|
int | A whole number | 19 | No decimal point |
double | A decimal number | 3.75 | Has a decimal point |
char | One character | 'A' | Inside ' ' |
String | Text | "Sara" | Inside " " |
boolean | True or false | true | Only 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);
}
}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?
double fits it.Which type fits "Has the student paid the fees?"
true or false.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.
| Type | Size | Range or examples |
|---|---|---|
boolean | Logical values | true, false |
byte | 8 bits | -128 … 127 |
char | 16 bits | One Unicode character: 'a' |
short | 16 bits | -32,768 … 32,767 |
int | 32 bits | About 2.1 billion, positive or negative |
long | 64 bits | 10L |
float | 32 bits | About 7 significant digits: 3.14f |
double | 64 bits | About 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);
}
}2147483647 -2147483648
First program: store two numbers and add them
- Write the lines inside
main - Predict the output before running
- Run itIn the lab press F6; here use the Run button or Ctrl+Enter.
- 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);
}
}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
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
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
| Name | Verdict | Why |
|---|---|---|
2ndNumber | Not allowed | Starts with a digit |
my age | Not allowed | Has a space |
int | Not allowed | A reserved word in Java |
total% | Not allowed | The symbol % is not allowed in names |
secondNumber | Allowed and clear | Starts with a letter |
myAge | Allowed and clear | Two words joined together |
totalPrice | Allowed and clear | Describes what it stores |
Age | Allowed, but avoid it | A 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);
}
}not a statementShow the fix
public class Naming {
public static void main(String[] args) {
int secondNumber = 7;
System.out.println(secondNumber);
}
}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);
}
}incompatible types: String cannot be converted to intShow the fix
public class Age {
public static void main(String[] args) {
int age = 19;
System.out.println(age);
}
}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;
}
}cannot find symbolShow the fix
public class Age {
public static void main(String[] args) {
int age = 19;
System.out.println(age);
}
}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);
}
}9 5
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
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
}
}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
| Operator | Name | A = 10, B = 20 | Note |
|---|---|---|---|
+ | Addition | 30 | Adds both sides |
- | Subtraction | -10 | Right from left |
* | Multiplication | 200 | Multiplies both sides |
/ | Division | 0 | Dividing whole numbers drops the decimal |
% | Modulo | 10 | Gives 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);
}
}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
}
}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
++xAdds one first, then uses the new value. Result: y = 35, x = 35.
int x = 34;
int y = ++x;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
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
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
}
}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?
int age; declares, age = 19; assigns, and they can be combined: int age = 19;.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
12
Why? The right side uses the old value: 4 × 3 = 12.