Variables & Data Types
IB Syllabus: B2.1.1 — Identify and describe variables, constants, and the common data types: int, double, boolean, char, String.
Table of Contents
- Key Concepts
- Data Types
- Naming Conventions
- Operators
- Type Casting
- User Input with Scanner
- Worked Examples
- Quick Code Check
- Trace Exercise
- Code Completion
- Spot the Bug
- Output Prediction
- Practice Exercises
- GitHub Classroom
- Connections
Key Concepts
A variable is a named container for storing data. In Java, you must declare the type before using a variable.
Declaration and Initialisation
int age; // declared — memory reserved, no value yet
age = 16; // initialised — value assigned
int lives = 3; // declared and initialised in one line
Constants
Use final for values that should never change after assignment:
final double PI = 3.14159;
final int MAX_ATTEMPTS = 3;
By convention, constants use
UPPER_SNAKE_CASE. The compiler will give an error if you try to reassign afinalvariable.
Data Types
A data type tells Java what kind of value a variable holds and how much memory to reserve.
Primitive Types (IB-assessed)
| Type | Size | What it stores | Example |
|---|---|---|---|
int | 32 bits | Whole numbers | int score = 42; |
double | 64 bits | Decimal numbers | double price = 9.99; |
boolean | — | true or false only | boolean passed = true; |
char | 16 bits | A single Unicode character | char grade = 'A'; |
charuses single quotes ('A'),Stringuses double quotes ("Alice"). Mixing them is a compile error.
String
String is not a primitive — it is an object. This matters later in OOP, but for now:
String name = "Alice"; // double quotes, capital S
String greeting = "Hello, " + name; // "Hello, Alice"
String empty = ""; // empty string, not null
Compare Strings with
.equals(), never==:if (name.equals("Alice")) { ... } // correct if (name == "Alice") { ... } // WRONG — compares memory addresses
Naming Conventions
| What | Rule | Example |
|---|---|---|
| Variables & methods | Start lowercase, camelCase | totalScore, playerName |
| Classes | Start uppercase, PascalCase | GradeCalculator |
| Constants | All caps, underscores | MAX_ATTEMPTS, TAX_RATE |
Operators
Arithmetic Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 5 - 3 | 2 |
* | Multiplication | 5 * 3 | 15 |
/ | Division | 7 / 2 | 3 (integer!) |
% | Modulo (remainder) | 7 % 2 | 1 |
Integer division trap: When both operands are
int, Java discards the decimal part.7 / 2gives3, not3.5. Cast one operand to get a decimal result:(double) 7 / 2gives3.5.
String Concatenation
The + operator joins Strings together, and automatically converts numbers to text:
String name = "Alice";
int age = 16;
System.out.println("Name: " + name + ", Age: " + age);
// Output: Name: Alice, Age: 16
Watch evaluation order:
"A" + 1 + 2gives"A12"(concatenation left-to-right), but1 + 2 + "A"gives"3A"(addition first, then concatenation).
Type Casting
Sometimes you need to convert a value from one type to another.
Implicit (Widening) — Automatic
Java automatically promotes smaller types to larger types:
int total = 365;
double average = total; // int automatically widened to double
Explicit (Narrowing) — Manual
Converting to a smaller type requires a cast — information may be lost:
double price = 9.99;
int truncated = (int) price; // 9 — decimal part dropped, NOT rounded
char letter = 'A';
int code = (int) letter; // 65 (Unicode value)
int code2 = 66;
char letter2 = (char) code2; // 'B'
(int) 3.9gives3, not4. Casting tointtruncates — it does not round.
User Input with Scanner
The Scanner class reads input typed by the user. It requires an import statement.
import java.util.Scanner;
public class Greeting {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = input.nextLine();
System.out.print("Enter your age: ");
int age = input.nextInt();
System.out.println("Hello, " + name + "! You are " + age + " years old.");
}
}
Common Scanner Methods
| Method | What it reads |
|---|---|
nextInt() | Next integer |
nextDouble() | Next decimal number |
next() | Next word (stops at whitespace) |
nextLine() | Entire line including spaces |
nextLine() trap: After calling
nextInt()ornextDouble(), the newline character\nremains in the buffer. A followingnextLine()will read that leftover newline as an empty string. Fix: add a throwawayinput.nextLine()call between them.
Worked Examples
Example 1: Area of a Circle
import java.util.Scanner;
public class AreaOfCircle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final double PI = 3.14159;
System.out.print("Enter the radius: ");
double radius = input.nextDouble();
double area = PI * radius * radius;
System.out.println("Area = " + area);
}
}
Input: 5.0 → Output: Area = 78.53975
Example 2: Temperature Converter
import java.util.Scanner;
public class TempConverter {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter temperature in Celsius: ");
double celsius = input.nextDouble();
double fahrenheit = celsius * 9.0 / 5.0 + 32;
System.out.println(celsius + "°C = " + fahrenheit + "°F");
}
}
Input: 100 → Output: 100.0°C = 212.0°F
Notice
9.0 / 5.0instead of9 / 5. Using9 / 5would give1(integer division), producing an incorrect result.
Example 3: Swap Two Variables
int a = 10;
int b = 20;
int temp = a; // save a's value
a = b; // overwrite a with b
b = temp; // put original a into b
System.out.println("a = " + a); // a = 20
System.out.println("b = " + b); // b = 10
Key insight: You need a temporary variable to swap — you cannot swap two values directly without losing one.
Example 4: Integer Division and Modulo
int total = 17;
int groupSize = 5;
int fullGroups = total / groupSize; // 3
int remaining = total % groupSize; // 2
System.out.println("Full groups: " + fullGroups);
System.out.println("Remaining: " + remaining);
Use cases for %:
- Check if even:
n % 2 == 0 - Extract last digit:
n % 10 - Wrap around (clock, array index):
index % length
Quick Code Check
Q1. What is the result of 7 / 2 in Java?
Q2. Which data type stores a single character such as 'A'?
Q3. What does (int) 3.9 evaluate to?
Q4. What does "Score: " + 42 produce?
Q5. What is the result of 17 % 5?
Q6. What does the final keyword do to a variable?
Trace Exercise
Trace this code — fill in the value of each variable after each line executes.
int a = 10;
int b = 3;
int c = a / b;
int d = a % b;
double e = (double) a / b;
a = a + d;
| Line | a | b | c | d | e |
|---|---|---|---|---|---|
int a = 10 | — | — | — | — | |
int b = 3 | 10 | — | — | — | |
int c = a / b | 10 | 3 | — | — | |
int d = a % b | 10 | 3 | 3 | — | |
double e = (double) a / b | 10 | 3 | 3 | 1 | |
a = a + d | 3 | 3 | 1 | 3.333... |
Code Completion
Complete the missing parts of this program that calculates the area of a rectangle. The program reads two dimensions from the user using Scanner and computes the area using the correct data type and method call.
import java.util.Scanner;
Scanner input = new Scanner(System.in);
System.out.print("Enter width: ");
width = input.nextDouble();
System.out.print("Enter height: ");
double height = input.;
double area = ;
System.out.println("Area = " + area); Complete the code to swap two variables using a temporary variable. Swapping requires a third variable to hold one value so it is not lost during reassignment.
int x = 5;
int y = 10;
int temp = ;
x = ;
y = ;
System.out.println("x = " + x); // should print 10
System.out.println("y = " + y); // should print 5 Spot the Bug
This code should calculate the average of three test scores, but operator precedence and integer division cause it to produce the wrong answer. Find the bug.
int score1 = 80;
int score2 = 90;
int score3 = 85;
double average = score1 + score2 + score3 / 3;
System.out.println("Average: " + average);What is wrong and how do you fix it?
This code applies the formula F = C * 9/5 + 32 to convert Celsius to Fahrenheit, but integer division causes it to produce incorrect results. Find the bug.
int celsius = 100;
double fahrenheit = celsius * 9 / 5 + 32;
System.out.println(celsius + "C = " + fahrenheit + "F");What is wrong and how do you fix it?
Output Prediction
What does this code print? This code demonstrates the difference between integer division (/), the modulo operator (%), and explicit type casting to double for decimal results. Type the exact output.
int x = 5;
int y = 2;
System.out.println(x / y);
System.out.println(x % y);
System.out.println((double) x / y);
2
1
2.5What does this code print? This code demonstrates how Java evaluates + left-to-right: when a String appears first, subsequent numbers are concatenated as text, but when numbers appear first, they are added arithmetically until a String is encountered.
String s = "Hello";
System.out.println(s + " " + 3 + 4);
System.out.println(3 + 4 + " " + s);
Hello 34
7 HelloPractice Exercises
Core
-
Name and age — Write a program that reads the user’s name and age, then prints a greeting:
"Hello, Alice! You are 16 years old." -
Average calculator — Read three test scores from the user and print the average as a decimal number.
-
Coin converter — Read a number of cents from the user and output how many dollars and cents that is. Use integer division and modulo.
-
Rectangle calculator — Read the width and height of a rectangle. Print its area and perimeter.
Extension
-
Time converter — Read a total number of seconds and convert it to hours, minutes, and seconds. Example: 3661 seconds = 1 hour, 1 minute, 1 second.
-
String explorer — Read a word from the user. Print its length, first character, last character, and the word in uppercase.
-
Number decomposer — Read a 3-digit number (e.g., 472) and extract the hundreds, tens, and units digits using
/ 10and% 10.
Challenge
-
BMI calculator — Read weight (kg) and height (m) from the user. Calculate and display the BMI (
weight / height²) with appropriate formatting. -
Letter grade with rounding — Read a decimal score and round it to the nearest integer using type casting (hint: add 0.5 before casting). Then assign a letter grade.
GitHub Classroom
Connections
Prerequisites:
- None — this is the starting point for Java programming
Related Topics:
- String Methods — built-in methods for manipulating text
- Exception Handling — handling runtime errors
- Debugging — finding and fixing errors
What’s Next:
- Selection (if/else) — making decisions in code
- Iteration (Loops) — repeating code
Once you understand variables and types, selection (if/else) is the natural next step — you already know how to write conditions like
score >= 50.