Variables/data types and expressions
Why This Matters
# Variables, Data Types, and Expressions - Summary This foundational lesson covers Java's primitive data types (int, double, boolean), variable declaration and initialization, and the construction of arithmetic and logical expressions. Students learn proper naming conventions, type casting, operator precedence, and the distinction between integer and floating-point division—essential skills for AP exam multiple-choice questions and free-response problems involving algorithm implementation. Mastery of these concepts is critical as they underpin all subsequent programming tasks, including method writing, object manipulation, and array processing tested throughout the AP Computer Science A examination.
Key Words to Know
Core Concepts & Theory
Variables are named storage locations in computer memory that hold data values which can change during program execution. Think of them as labeled containers that store information temporarily while your program runs.
Data Types specify what kind of data a variable can hold and determine the operations that can be performed on it. The fundamental primitive data types in Java include:
• int (integer): Whole numbers without decimals, ranging from -2,147,483,648 to 2,147,483,647. Example: int age = 17;
• double: Floating-point numbers with decimal precision, storing approximately 15 decimal digits. Example: double price = 19.99;
• boolean: Logical values representing true or false only. Example: boolean isStudent = true;
• char: Single Unicode characters enclosed in single quotes. Example: char grade = 'A';
• String: Sequences of characters (reference type, not primitive). Example: String name = "Sarah";
Expressions are combinations of variables, literals, operators, and method calls that evaluate to a single value. They follow operator precedence rules (PEMDAS: Parentheses, Exponents, Multiplication/Division, Addition/Subtraction).
Type Casting converts values between data types:
• Implicit casting (widening): Automatic conversion from smaller to larger types: int → double
• Explicit casting (narrowing): Manual conversion requiring syntax: double → int using (int)
Variable Declaration syntax: dataType variableName = initialValue;
Cambridge Key Term: Identifier - the name given to a variable, following rules: must start with letter/underscore, cannot be Java keywords, case-sensitive.
Detailed Explanation with Real-World Examples
Understanding variables and data types becomes intuitive when connected to real-world scenarios.
Banking Application Analogy: Imagine a bank account system. Your account number is an int (whole number), your balance is a double (needs decimal precision for cents), your account status (active/inactive) is a boolean, and your name is a String. Each piece of information requires the appropriate data type to function correctly—you wouldn't store someone's name as a number!
Shopping Cart System: Consider an e-commerce platform:
int itemCount = 5; // Number of items in cart
double totalPrice = 127.50; // Total with decimals
boolean hasDiscount = true; // Promotional code applied
char sizeSelected = 'M'; // Clothing size
String customerName = "Alex"; // Customer details
int itemCount = 5; // Number of items in cart
double totalPrice = 127.50; // Total with decimals
boolean hasDiscount = true; // Promotional code applied
char sizeSelected = 'M'; // Clothing size
String customerName = "Alex"; // Customer details
Expression Evaluation in Real Context: When calculating a student's final grade:
double examScore = 85.5;
double courseworkScore = 78.0;
double finalGrade = (examScore * 0.6) + (courseworkScore * 0.4);
// Result: 82.5 (weighted average)
double examScore = 85.5;
double courseworkScore = 78.0;
double finalGrade = (examScore * 0.6) + (courseworkScore * 0.4);
// Result: 82.5 (weighted average)
Type Casting in Practice: Converting temperatures:
double celsius = 23.7;
int roundedTemp = (int) celsius; // Explicit cast: 23 (decimal truncated)
double fahrenheit = (celsius * 9/5) + 32; // Implicit cast during calculation
double celsius = 23.7;
int roundedTemp = (int) celsius; // Explicit cast: 23 (decimal truncated)
double fahrenheit = (celsius * 9/5) + 32; // Implicit cast during calculation
Memory Efficiency: Choosing correct data types matters for performance. A mobile game tracking player health (0-100) uses int, not double, saving memory across millions of users. A GPS app calculating coordinates requires double for precision—using int would place you kilometers away!
Real-World Insight: Professional developers choose data types based on range requirements, precision needs, and memory constraints.
Worked Examples & Step-by-Step Solutions
Example 1: Variable Declaration and Expression Evaluation
Question: Write Java code to calculate the area of a circle with radius 7.5cm. Declare appropriate variables and show the calculation. (π = 3.14159)
Solution:
double radius = 7.5; // [1 mark: correct data type]
double pi = 3.14159; // [1 mark: constant declaration]
double area = pi * radius * radius; // [2 marks: correct formula]
System.out.println("Area: " + area); // Output: 176.714625
double radius = 7.5; // [1 mark: correct data type]
double pi = 3.14159; // [1 mark: constant declaration]
double area = pi * radius * radius; // [2 marks: correct formula]
System.out.println("Area: " + area); // Output: 176.714625
Examiner Note: Must use double for decimal precision. Using int would truncate values and lose marks. Formula must be π * r², not 2πr (that's circumference).*
Example 2: Type Casting and Integer Division
Question: Explain the output of this code and correct any issues:
int total = 25;
int count = 4;
double average = total / count;
int total = 25;
int count = 4;
double average = total / count;
Solution:
Problem: Output is 6.0, not 6.25 because integer division occurs first.
Explanation:
total / countperforms integer division: 25 ÷ 4 = 6 (remainder discarded)- Result
6is then implicitly cast to6.0for storage indouble
Corrected Code [4 marks]:
int total = 25;
int count = 4;
double average = (double) total / count; // Explicit cast forces floating-point division
// OR: double average = total / (double) count;
// Result: 6.25
int total = 25;
int count = 4;
double average = (double) total / count; // Explicit cast forces floating-point division
// OR: double average = total / (double) count;
// Result: 6.25
Examiner Note: Cambridge mark schemes reward understanding why casting is needed. State: "Cast at least one operand to double before division to ensure floating-point arithmetic."
Example 3: Complex Expression
Question: Evaluate: int result = 10 + 3 * 2 - 8 / 4;*
Solution:
Step 1: 3 * 2 = 6 (multiplication first)
Step 2: 8 / 4 = 2 (division same precedence)
Step 3: 10 + 6 = 16 (addition left-to-right)
Step 4: 16 - 2 = 14 (subtraction)
Final: result = 14
Step 1: 3 * 2 = 6 (multiplication first)
Step 2: 8 / 4 = 2 (division same precedence)
Step 3: 10 + 6 = 16 (addition left-to-right)
Step 4: 16 - 2 = 14 (subtraction)
Final: result = 14
Examiner Note: Show working using operator precedence. Cambridge awards method marks even if arithmetic error occurs.
Common Exam Mistakes & How to Avoid Them
Mistake 1: Integer Division Truncation
What students do: int result = 7 / 2; expecting 3.5, getting 3.
Why it...
Cambridge Exam Technique & Mark Scheme Tips
Command Word Mastery for This Topic:
• "State" (1-2 marks): Give the data type only. Example: "State the data t...
2 more sections locked
Upgrade to Starter to unlock all study notes, audio listening, and more.
Exam Tips
- 1.Always declare a variable's data type before using it (e.g., `int x;` not just `x;`).
- 2.Initialize variables with a starting value to avoid errors, especially if you use them in calculations right away (e.g., `int count = 0;`).
- 3.Pay close attention to data type compatibility; a `double` can hold an `int`'s value, but an `int` cannot directly hold a `double`'s value without potential data loss (and a specific 'cast').
- 4.Understand the difference between the assignment operator (`=`) and the equality operator (`==`); this is a very common source of errors on the exam.
- 5.Practice evaluating complex expressions step-by-step, following the order of operations (PEMDAS/BODMAS), just like in math class.