Teacher Guide: Variables & Data Types

Student page: Variables & Data Types Syllabus ref: B2.1.1 Estimated periods: 2 (90 min each) Prerequisites: None

Contents

  1. Lesson Plans
    1. Period 1: Types, Variables, Constants, Input/Output
      1. Period 1 Enrichment: Predict-the-Output
    2. Period 2: Operators, Type Casting, Expressions
      1. Period 2 Enrichment: Char/Int Casting
      2. Period 2 Enrichment: Overflow Prediction
      3. 6-Step Problem-Solving Process (IPO Model)
      4. Period 2 Homework
  2. Differentiation
    1. Supporting Weaker Students
    2. Extending Stronger Students
  3. Answer Keys
    1. Core 1: Name and Age
    2. Core 2: Average Calculator
    3. Core 3: Coin Converter
    4. Core 4: Rectangle Calculator
    5. Extension 5: Time Converter
    6. Extension 6: String Explorer
    7. Extension 7: Number Decomposer
    8. Challenge 8: BMI Calculator
    9. Challenge 9: Letter Grade with Rounding
  4. Integration Notes
    1. How Student Page Components Map to Class Time
    2. Additional Resources
  5. Common Errors Quick Reference

Lesson Plans

Period 1: Types, Variables, Constants, Input/Output

Phase Time Activity Notes
Warm-up 10 min “What kinds of info does a program remember?” brainstorm Write student answers on board, then reveal Java type names beside each
Teach 25 min Data types, declaration, constants, Scanner input Live code: name and greeting program
Practice 40 min Core #1–3 (Name and age, Average calculator, Coin converter) Circulate and check for integer division mistake in #2
Wrap-up 15 min Quick Code Check MCQs from student page Project on screen, students answer individually

Period 1 Enrichment: Predict-the-Output

Use these predict-the-output activities as a warm-up or early-finisher task. Have students write their prediction before running the code.

Expression Student expects Actual result Why
"A" + 1 + 2 "A3" "A12" Left-to-right evaluation: "A" + 1 produces "A1" (String concat), then "A1" + 2 produces "A12"
1 + 2 + "A" "12A" "3A" Left-to-right: 1 + 2 is integer addition (3), then 3 + "A" is String concat ("3A")
3 / 2 1.5 1 Integer division — both operands are int, so the decimal part is discarded
3.0 / 2 1 or 1.5 1.5 One operand is double, so Java promotes the other to double before dividing
(double)(total) / count varies decimal result Casting total to double before dividing gives a decimal quotient
(double)(total / count) same as above truncated result Integer division happens inside the parentheses first, then the already-truncated result is cast to double

Period 2: Operators, Type Casting, Expressions

Phase Time Activity Notes
Warm-up 10 min Integer division prediction: “What is 7 / 2 in Java?” Discovery activity — let students guess, then run the code
Teach 20 min Arithmetic operators, mod, type casting, char-to-int conversions Build on the warm-up surprise
Practice 45 min Core #4, Extension #5–7 (Rectangle, Time converter, String explorer, Number decomposer) Students work individually or in pairs
Wrap-up 15 min Challenge #8–9 intro or exit ticket Introduce BMI and letter-grade problems for early finishers or homework

Period 2 Enrichment: Char/Int Casting

These exercises bridge the Programming and Information layers. Students should predict each result before running the code.

Expression Result Discussion point
(int) 'A' 65 Unicode/ASCII value of uppercase A
(int) 'B' 66 Letters are sequential in the character table
(int) 'a' 97 Lowercase letters start at 97 — there is a gap of 32
(char) 66 'B' Casting an int to char gives the character at that code point
(char)('a' - 32) 'A' Capitalising a lowercase letter using arithmetic

Challenge prompt: “Write code that reads a lowercase letter and prints its uppercase equivalent using only arithmetic — no toUpperCase() allowed.”

Period 2 Enrichment: Overflow Prediction

For stronger students, demonstrate what happens when a value exceeds a type’s range:

byte b = 127;
b = (byte)(b + 1);
System.out.println(b);  // prints -128 (overflow wraps around)

short s = 32767;
s = (short)(s + 1);
System.out.println(s);  // prints -32768

This connects to the Information layer (binary representation) and helps students understand why type ranges matter.

6-Step Problem-Solving Process (IPO Model)

Teach students to plan before coding:

  1. Read the problem carefully
  2. Identify Inputs — what data does the program need from the user?
  3. Identify Outputs — what should the program display?
  4. Plan the Process — what calculations or operations connect input to output?
  5. Write the Code — translate the plan into Java
  6. Test — run with sample data and verify the output
Input Process Output
(what the user types) (calculations/operations) (what the program prints)

Use this IPO table as a worksheet for weaker students who struggle to start exercises.

Period 2 Homework

Assign 3 exercises for homework:

  1. Greeting — Read the user’s first name and last name (separately), then print "Hello, [first] [last]!"
  2. Age in Days — Read the user’s age in years and print the approximate number of days they have lived (age * 365)
  3. Total Cost of Apples — Read the number of apples and the price per apple, then print the total cost

Differentiation

Supporting Weaker Students

Strategy When to use Example
Provide variable declaration starters Student cannot start Core #1 Give String name; and int age; as a starting scaffold
IPO worksheet Student cannot identify what the program needs Blank table: Input / Process / Output — fill it in together before coding
Pair programming During Core #1–3 Stronger student navigates, weaker student drives
Type reference card Student confuses int/double/boolean/char/String One-page printout with the type table, examples, and common mistakes

Extending Stronger Students

Strategy When to use Example
Predict-the-output Finishes Core early Give the "A" + 1 + 2 vs 1 + 2 + "A" exercises from the enrichment table
Real-world application After Core #4 “Calculate compound interest” or “Convert between currencies with an exchange rate”
Challenge exercises Extended learners #8 BMI calculator, #9 Letter grade with rounding
Char arithmetic After type casting section “Write code to capitalise a lowercase letter using only arithmetic — no toUpperCase()

Answer Keys

Core 1: Name and Age

Show solution
import java.util.Scanner;

public class NameAndAge {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();
        System.out.print("Enter your age: ");
        int age = scanner.nextInt();
        System.out.println("Hello, " + name + "! You are " + age + " years old.");
        scanner.close();
    }
}

Expected output:

Enter your name: Alice
Enter your age: 16
Hello, Alice! You are 16 years old.

Common mistakes:

  • Using next() instead of nextLine() for names with spaces — next() only reads up to the first space
  • Forgetting the import java.util.Scanner; statement
  • Using println instead of print for the prompts (puts the cursor on the next line)

Marking notes: Full marks for a working solution that reads name and age and prints the greeting in the correct format. Accept minor formatting variations (e.g., different prompt text).


Core 2: Average Calculator

Show solution
import java.util.Scanner;

public class AverageCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter score 1: ");
        int s1 = scanner.nextInt();
        System.out.print("Enter score 2: ");
        int s2 = scanner.nextInt();
        System.out.print("Enter score 3: ");
        int s3 = scanner.nextInt();
        double average = (s1 + s2 + s3) / 3.0;
        System.out.println("Average: " + average);
        scanner.close();
    }
}

Expected output:

Enter score 1: 80
Enter score 2: 90
Enter score 3: 70
Average: 80.0

Common mistakes:

  • Using / 3 instead of / 3.0 — integer division gives the wrong result (e.g., (80 + 90 + 70) / 3 gives 80, not 80.0)
  • Forgetting parentheses: s1 + s2 + s3 / 3.0 divides only s3 by 3 due to operator precedence

Marking notes: Must produce a decimal output. Accept either / 3.0 or casting to (double) as valid approaches. Deduct marks if the output is an integer (indicates integer division).


Core 3: Coin Converter

Show solution
import java.util.Scanner;

public class CoinConverter {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter cents: ");
        int cents = scanner.nextInt();
        int dollars = cents / 100;
        int remaining = cents % 100;
        System.out.println(dollars + " dollars and " + remaining + " cents");
        scanner.close();
    }
}

Expected output:

Enter cents: 365
3 dollars and 65 cents

Common mistakes:

  • Using double division instead of integer division with % — getting 3.65 instead of separating dollars and cents
  • Confusing / and % — using modulo for dollars and division for cents (reversed)

Marking notes: Must use integer division (/) and modulo (%). This is the key concept being tested. Accept reasonable output format variations.


Core 4: Rectangle Calculator

Show solution
import java.util.Scanner;

public class RectangleCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter width: ");
        double width = scanner.nextDouble();
        System.out.print("Enter height: ");
        double height = scanner.nextDouble();
        double area = width * height;
        double perimeter = 2 * (width + height);
        System.out.println("Area: " + area);
        System.out.println("Perimeter: " + perimeter);
        scanner.close();
    }
}

Expected output:

Enter width: 5
Enter height: 3
Area: 15.0
Perimeter: 16.0

Common mistakes:

  • Forgetting parentheses in 2 * (width + height) — writing 2 * width + height only doubles the width
  • Using int instead of double — dimensions should support decimal values

Marking notes: Both area and perimeter must be correct. Check for correct use of parentheses in the perimeter formula.


Extension 5: Time Converter

Show solution
import java.util.Scanner;

public class TimeConverter {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter total seconds: ");
        int totalSeconds = scanner.nextInt();
        int hours = totalSeconds / 3600;
        int minutes = (totalSeconds % 3600) / 60;
        int seconds = totalSeconds % 60;
        System.out.println(hours + " hour(s), " + minutes + " minute(s), " + seconds + " second(s)");
        scanner.close();
    }
}

Expected output:

Enter total seconds: 3661
1 hour(s), 1 minute(s), 1 second(s)

Common mistakes:

  • Wrong order of operations — must extract hours first, then calculate minutes from the remainder
  • Using totalSeconds / 60 for minutes without first removing the hours portion
  • Forgetting to use % 3600 before dividing by 60 for minutes

Marking notes: The key insight is the two-step extraction: hours first via / 3600, then minutes from the remainder via % 3600 / 60, then leftover seconds via % 60. Accept any output format that shows all three components correctly.


Extension 6: String Explorer

Show solution
import java.util.Scanner;

public class StringExplorer {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a word: ");
        String word = scanner.nextLine();
        System.out.println("Length: " + word.length());
        System.out.println("First character: " + word.charAt(0));
        System.out.println("Last character: " + word.charAt(word.length() - 1));
        System.out.println("Uppercase: " + word.toUpperCase());
        scanner.close();
    }
}

Expected output:

Enter a word: Hello
Length: 5
First character: H
Last character: o
Uppercase: HELLO

Common mistakes:

  • Using word.length() instead of word.length() - 1 for the last character index — causes StringIndexOutOfBoundsException
  • Confusing length() (method with parentheses for Strings) with length (field without parentheses for arrays)

Marking notes: Must correctly use charAt(0) for first and charAt(word.length() - 1) for last. Accept additional String method explorations beyond the minimum requirements.


Extension 7: Number Decomposer

Show solution
import java.util.Scanner;

public class NumberDecomposer {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a 3-digit number: ");
        int number = scanner.nextInt();
        int hundreds = number / 100;
        int tens = (number / 10) % 10;
        int units = number % 10;
        System.out.println("Hundreds: " + hundreds);
        System.out.println("Tens: " + tens);
        System.out.println("Units: " + units);
        scanner.close();
    }
}

Expected output:

Enter a 3-digit number: 472
Hundreds: 4
Tens: 7
Units: 2

Common mistakes:

  • Using number % 100 / 10 instead of (number / 10) % 10 for tens — both work correctly, but students often get confused about which approach to use
  • Forgetting % 10 for the units digit

Marking notes: Accept either (number / 10) % 10 or (number % 100) / 10 for the tens digit — both are correct. The important thing is that all three digits are extracted correctly.


Challenge 8: BMI Calculator

Show solution
import java.util.Scanner;

public class BMICalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter weight (kg): ");
        double weight = scanner.nextDouble();
        System.out.print("Enter height (m): ");
        double height = scanner.nextDouble();
        double bmi = weight / (height * height);
        System.out.println("BMI: " + bmi);
        scanner.close();
    }
}

Expected output:

Enter weight (kg): 70
Enter height (m): 1.75
BMI: 22.857142857142858

Common mistakes:

  • Forgetting parentheses around height * height — writing weight / height * height divides by height first, then multiplies by height, giving back the original weight
  • Using integer types instead of double — BMI requires decimal precision

Marking notes: The formula weight / (height * height) must have correct parentheses. Accept Math.pow(height, 2) as an alternative if students discover it on their own, but it is not required at this stage.


Challenge 9: Letter Grade with Rounding

Show solution
import java.util.Scanner;

public class LetterGrade {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter decimal score: ");
        double score = scanner.nextDouble();
        int rounded = (int)(score + 0.5);
        System.out.println("Rounded score: " + rounded);
        String grade;
        if (rounded >= 90) {
            grade = "A";
        } else if (rounded >= 80) {
            grade = "B";
        } else if (rounded >= 70) {
            grade = "C";
        } else if (rounded >= 60) {
            grade = "D";
        } else {
            grade = "F";
        }
        System.out.println("Grade: " + grade);
        scanner.close();
    }
}

Expected output:

Enter decimal score: 89.5
Rounded score: 90
Grade: A
Enter decimal score: 79.4
Rounded score: 79
Grade: C

Common mistakes:

  • Adding 0.5 after casting instead of before — (int) score + 0.5 casts first (truncates), then adds 0.5, giving a double result instead of a rounded int
  • Not understanding that (int) truncates — students expect it to round automatically
  • Using == instead of >= in the grade boundaries, which misses all scores that are not exact multiples of 10

Marking notes: The rounding technique (int)(score + 0.5) is the key concept here. Accept Math.round() if students discover it, but the point of this exercise is to understand how truncation plus 0.5 achieves rounding. The if/else chain must use >= with descending thresholds. Note: this exercise previews selection — if students have not yet covered if/else, provide the grade logic as starter code and ask them to fill in the rounding part only.


Integration Notes

How Student Page Components Map to Class Time

Item In Class Homework Student Page Link
Worked Examples 1–2 Walk through together in Period 1 Key Concepts
Quick Code Check MCQs Period 1 wrap-up Pre-class review before Period 2 Quick Code Check
Core #1–3 Individual practice in Period 1 Practice Exercises
Core #4, Extension #5–7 Start in Period 2 Complete for homework Practice Exercises
Challenge #8–9 Optional extension Practice Exercises
Trace Exercise Period 2 warm-up or homework check Trace Exercise
GitHub Classroom Due end of week GitHub Classroom

Additional Resources

Predict-the-output warmup sheet: Print the enrichment table from Period 1 as a handout. Students fill in the “Student expects” and “Actual result” columns, then run the code to verify. Works well as a 5-minute warm-up at the start of Period 2.

IPO problem-solving worksheet: Provide a blank IPO table for each Core exercise. Weaker students fill in the Input / Process / Output columns before writing any code. This forces planning and prevents the “stare at a blank screen” problem.

Common trap — uninitialised variables: Forgetting to initialise variables (counter, total) is a common source of logic errors. Java gives compile errors for uninitialised local variables, but instance variables get default values (covered later in OOP).


Common Errors Quick Reference

Error What students write Fix
Integer division double avg = (a + b) / 2; Use / 2.0 or cast: (double)(a + b) / 2
String comparison with == if (name == "Alice") Use name.equals("Alice")== compares memory addresses
Missing parentheses 2 * width + height Use 2 * (width + height) for perimeter
Truncation surprise Expects (int) 3.9 to give 4 (int) truncates, does not round — result is 3
Concat vs addition Expects "A" + 1 + 2 to give "A3" Left-to-right evaluation: "A1" then "A12"
Scanner mismatch Uses next() for full name Use nextLine() to read text with spaces

Back to top

© EduCS.me — A resource hub for IB Computer Science

This site uses Just the Docs, a documentation theme for Jekyll.