Variables & Data Types
IB Syllabus: B2.1.1 - Identify and describe variables, constants, and the common data types: int, double, boolean, char, String.
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
# Python has no separate declaration step - a variable exists
# once you assign it, and its type comes from the value.
age = 16 # an int, because 16 is a whole number
lives = 3
Constants
Use final for values that should never change after assignment:
final double PI = 3.14159;
final int MAX_ATTEMPTS = 3;
# Python has no final keyword - ALL_CAPS names signal "treat as a constant"
PI = 3.14159
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'; |
(Python note: the type comes from the value - x = 5 makes an int, x = 9.99 a float, True/False booleans; there is no char, so a one-character string like "A" is used instead.)
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
name = "Alice" # no type keyword - the quotes make it a string
greeting = "Hello, " + name # "Hello, Alice"
empty = "" # empty string, not None
Compare Strings with
.equals(), never==:if (name.equals("Alice")) { ... } // correct if (name == "Alice") { ... } // WRONG - compares memory addresses(Python:
==IS the correct choice - it compares the text content, and there is no.equals().)
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. (Python:/always gives the decimal answer -7 / 2is3.5; use//when you want whole-number division:7 // 2is3.)
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
name = "Alice"
age = 16
# Python will not join a number onto text with + - convert it with str() first
print("Name: " + name + ", Age: " + str(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). (Python simply refuses:"A" + 1is a TypeError - convert withstr()first.)
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
total = 365
average = float(total) # Python has no automatic widening - convert explicitly with float()
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'
price = 9.99
truncated = int(price) # 9 - decimal part dropped, NOT rounded
letter = "A" # Python has no char type - a one-character string
code = ord(letter) # 65 (Unicode value)
code2 = 66
letter2 = chr(code2) # "B"
(int) 3.9gives3, not4. Casting tointtruncates - it does not round. (Python’sint()truncates the same way:int(3.9)is3.)
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.");
}
}
# Python needs no import or Scanner - input() reads a whole line as text
name = input("Enter your name: ")
age = int(input("Enter your age: ")) # wrap input() in int() to get a number
print("Hello, " + name + "! You are " + str(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 |
(Python: one function covers all of these - input() reads a line as text; wrap it in int(...) or float(...) to get a number.)
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);
}
}
PI = 3.14159 # no final keyword - ALL_CAPS marks it as a constant
radius = float(input("Enter the radius: "))
area = PI * radius * radius
print("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");
}
}
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = celsius * 9.0 / 5.0 + 32
print(str(celsius) + "°C = " + str(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. (Python:9 / 5is already1.8- this trap only exists in Java.)
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
a = 10
b = 20
temp = a # save a's value
a = b # overwrite a with b
b = temp # put original a into b
print("a =", a) # a = 20
print("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);
total = 17
group_size = 5
full_groups = total // group_size # 3 - // is whole-number division (Java's int /)
remaining = total % group_size # 2
print("Full groups:", full_groups)
print("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 = 4;
int c = a / b;
int d = a % b;
double e = (double) a / b;
a = a + d;
a = 10
b = 4
c = a // b # Java's whole-number division - Python needs //
d = a % b
e = a / b # / always gives the decimal answer - no cast needed
a = a + d
| Line | a | b | c | d | e |
|---|---|---|---|---|---|
int a = 10 | - | - | - | - | |
int b = 4 | 10 | - | - | - | |
int c = a / b | 10 | 4 | - | - | |
int d = a % b | 10 | 4 | 2 | - | |
double e = (double) a / b | 10 | 4 | 2 | 2 | |
a = a + d | 4 | 2 | 2 | 2.5 |
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);
x = 5
y = 2
print(x // y) # // matches Java's whole-number division
print(x % y)
print(x / y) # / gives the decimal answer - Java needed the (double) cast
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);
s = "Hello"
# Python never mixes text and numbers with + ("Hello" + 3 is a TypeError),
# so Java's left-to-right rule has no Python twin - convert with str() instead.
print(s + " " + str(3) + str(4))
print(str(3 + 4) + " " + s)
Hello 34
7 HelloPractice Exercises
Core
-
Name and number - Write a program that reads the user’s name and favourite number, then prints a sentence:
"Hi Alice, your favourite number is 7." -
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
Codespace Setup Instructions (click to expand)
First Time Setup
- Click “Open in GitHub” above, then click the green “Accept this assignment” button
- Check the email registered with your GitHub account: click the link there to open your repository. This avoids access issues and means your teacher does not need to share links manually
- Wait for your repository to be created, then click “Open in Codespace”
- Wait for the Codespace to finish loading (you’ll see VS Code in your browser)
Important: Switch to Standard Mode
- Look at the bottom status bar. If it says
Java: Lightweight Mode, click on it and select Standard - Wait for Java to finish loading (status bar will say
Java: Ready) - Without Standard Mode, the Run button won’t work and you’ll get “Main method not found” errors
Dismiss Popups
You’ll see two notification popups. Dismiss them both:
- “Would you like VS Code to periodically run git fetch?” → Click No
- “There’s a pull request associated with main” → Click Don’t Show Again
These are housekeeping popups, not part of the assignment.
How to Code
- Open
src/VariablesAndTypes.java. This is the only file you need to edit - Complete each
// TODOsection - Click the Run button (▶ above
main) to test your output - Compare your output with the expected output written in the comments above each task
How to Check Your Code
You can check your work in two ways:
Option A: Run your code directly
- Click the Run button (▶) above
maininVariablesAndTypes.java - Compare your printed output with the expected output shown in the comments above each task
Option B: Run the autograder tests
- Open the Terminal (Menu → Terminal → New Terminal)
- Type
bash run-tests.shand press Enter - Green ✓ = test passed, Red ✗ = test failed
- Each test tells you what it expected. Read the error message to fix your code
How to Submit
- Click the Source Control icon (branch icon) in the left sidebar
- Type a message like
completed tasksin the message box - Click the green Commit button
- If asked “stage all changes?” → click Always
- Click Sync Changes → if asked about push/pull → click OK, Don’t Show Again
- Done! Autograding runs automatically. Your teacher can see your results in the GitHub Classroom dashboard
How to Review Feedback
- Go to your repository on GitHub
- Click the “Pull requests” tab at the top
- Open the pull request called “Feedback”
- Click the “Files changed” tab. You’ll see your teacher’s comments on specific lines of your code
- Read through each comment carefully, then fix your code in Codespaces
- Run
bash run-tests.shin your Codespaces Terminal to check your fixes - Commit and push again (repeat steps 12-17). The autograder will re-run automatically
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.