Variables & Data Types

B2.1.1 - Construct and trace programs using a range of global and local variables of various data types.


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 a final variable.


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.)

char uses single quotes ('A'), String uses 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 / 2 gives 3, not 3.5. Cast one operand to get a decimal result: (double) 7 / 2 gives 3.5. (Python: / always gives the decimal answer - 7 / 2 is 3.5; use // when you want whole-number division: 7 // 2 is 3. For negative numbers the two differ: Python’s // rounds down, so -7 // 2 is -4, while Java’s -7 / 2 drops the decimal part and gives -3.)

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 + 2 gives "A12" (concatenation left-to-right), but 1 + 2 + "A" gives "3A" (addition first, then concatenation). (Python simply refuses: "A" + 1 is a TypeError - convert with str() 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)   # average = total would stay an int; float() gives 365.0 like Java

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.9 gives 3, not 4. Casting to int truncates - it does not round. (Python’s int() truncates the same way: int(3.9) is 3.)


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() or nextDouble(), the newline character \n remains in the buffer. A following nextLine() will read that leftover newline as an empty string. Fix: add a throwaway input.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.0 instead of 9 / 5. Writing celsius * (9 / 5) would give celsius * 1, because 9 / 5 on its own is integer division. Using 9.0 / 5.0 keeps the result right whichever order the expression is written in. (Python: 9 / 5 is already 1.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: With plain assignments you need a temporary variable to swap: assigning one variable to the other first loses its value. (Python can also write a, b = b, a.)


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 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
Lineabcde
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 Error

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 = 9/5 * C + 32 to convert Celsius to Fahrenheit, but integer division causes it to produce incorrect results. Find the bug.

int celsius = 100;
double fahrenheit = 9 / 5 * celsius + 32;
System.out.println(celsius + "C = " + fahrenheit + "F");

What is wrong and how do you fix it?


Predict the Output

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
Expected: 2
1
2.5

What 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)
Expected: Hello 34
7 Hello

Practice Exercises

Core

  1. 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."

  2. Average calculator - Read three test scores from the user and print the average as a decimal number.

  3. Coin converter - Read a number of cents from the user and output how many dollars and cents that is. Use integer division and modulo.

  4. Rectangle calculator - Read the width and height of a rectangle. Print its area and perimeter.

Extension

  1. 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.

  2. String explorer - Read a word from the user. Print its length, first character, last character, and the word in uppercase.

  3. Number decomposer - Read a 3-digit number (e.g., 472) and extract the hundreds, tens, and units digits using / 10 and % 10.

Challenge

  1. BMI calculator - Read weight (kg) and height (m) from the user. Calculate and display the BMI (weight / height²) with appropriate formatting.

  2. 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

Variables and Data Types
Practice declaring variables, using operators, reading input, and type casting.

A class assignment on GitHub Classroom: use it when your teacher has set it. It needs a free GitHub account.

Working in the Codespace

  1. Accept and open. Accept the assignment above, open the link in the email from GitHub, then press Open in Codespace. In Java, change the status bar from Lightweight to Standard mode.
  2. Write and check. Open src/VariablesAndTypes.java and complete each TODO. Press Run and compare the output with the comments, or run bash run-tests.sh in the Terminal.
  3. Submit. In Source Control, write a message, press Commit, then Sync Changes. Your teacher’s feedback arrives as a pull request called Feedback.

The full Codespace guide, with pictures


Connections

Prerequisites:

  • None - this is the starting point for Java programming

Related Topics:

Where this leads:

Once you understand variables and types, selection (if/else) is the natural next step - you already know how to write conditions like score >= 50.