Module 3: Variables, Console Output, and Arithmetic Operations
Module Overview
In this module, you'll learn about variable declaration, initialization, console output, and performing arithmetic operations in Java. You'll understand data types, expressions, and basic operations in Java programming.
Learning Objectives
- Declare variables of the correct types to store primitive data
- Implement code to write output to the console
- Calculate the result of a basic and compound arithmetic expression
- Cast to floating point type to preserve precision when dividing integers
Content
Variables, Console Output, and Arithmetic Operations
Java Variables
Variables are containers for storing data values. In Java, each variable must have a specific data type that determines what kind of value it can hold.
Variable Declaration and Initialization
// Declaration
dataType variableName;
// Initialization
variableName = value;
// Declaration and initialization in one step
dataType variableName = value;
Java Primitive Data Types
Java has eight primitive data types:
int
- Integers, 32 bits. Example:int age = 25;
double
- Double precision floating point numbers, 64 bits. Example:double price = 19.99;
boolean
- true or false values. Example:boolean isActive = true;
char
- Single characters, 16 bits. Example:char grade = 'A';
float
- Single precision floating point numbers, 32 bits. Example:float temperature = 98.6f;
long
- Long integers, 64 bits. Example:long population = 8000000000L;
short
- Short integers, 16 bits. Example:short productCode = 32767;
byte
- Very small integers, 8 bits. Example:byte level = 127;
Variable Naming Rules
- Names can contain letters, digits, underscores, and dollar signs
- Names must begin with a letter, underscore, or dollar sign
- Names are case-sensitive (
myVar
andmyvar
are different variables) - Cannot use reserved words like
int
orclass
as variable names - Use camelCase for variable names (e.g.,
firstName
,totalAmount
)
Example: Using Variables
// Declaring and initializing variables
int age = 25;
double height = 5.9;
char initial = 'J';
boolean isStudent = true;
// Using variables in expressions
int birthYear = 2023 - age;
double heightInCm = height * 30.48;
// Updating variable values
age = age + 1; // Now age is 26
Console Output
Java provides several ways to display output to the console. The most common method is to use the System.out.println()
method.
Print Methods
System.out.println(x)
- Prints the value of x and then moves to a new lineSystem.out.print(x)
- Prints the value of x without moving to a new lineSystem.out.printf(format, args...)
- Prints formatted text using format specifiers
Printing Different Data Types
// Printing strings
System.out.println("Hello, Java!");
// Printing variables
int score = 95;
System.out.println("Your score is: " + score);
// Printing multiple values
String name = "Alice";
int age = 30;
System.out.println(name + " is " + age + " years old.");
// Formatted printing
double price = 19.99;
System.out.printf("The price is $%.2f\n", price); // Outputs: The price is $19.99
Formatting Output
Format specifiers for printf
and String.format()
:
%d
- for integers%f
- for floating-point numbers%s
- for strings%c
- for characters%b
- for boolean values%n
- for a new line (platform-independent)
// Formatting examples
System.out.printf("Name: %s, Age: %d, GPA: %.1f%n", "John", 20, 3.85);
String formatted = String.format("Balance: $%.2f", 1250.575);
System.out.println(formatted); // Outputs: Balance: $1250.58
Arithmetic Operations
Java supports various arithmetic operators to perform calculations.
Basic Arithmetic Operators
+
(Addition) - Adds values on either side of the operator-
(Subtraction) - Subtracts right-hand operand from left-hand operand*
(Multiplication) - Multiplies values on either side of the operator/
(Division) - Divides left-hand operand by right-hand operand%
(Modulus) - Returns the remainder after division
Compound Assignment Operators
+=
- Adds right operand to the left operand and assigns the result to left operand-=
- Subtracts right operand from the left operand and assigns the result to left operand*=
- Multiplies right operand with the left operand and assigns the result to left operand/=
- Divides left operand with the right operand and assigns the result to left operand%=
- Takes modulus using two operands and assigns the result to left operand
Integer Division and Type Casting
When dividing two integers, Java performs integer division, which truncates any decimal portion:
int a = 5;
int b = 2;
int result = a / b; // result is 2, not 2.5
To preserve decimal precision when dividing integers, cast at least one operand to a floating-point type:
int a = 5;
int b = 2;
double result = (double) a / b; // result is 2.5
// Alternative approach
double result2 = a / (double) b; // result is 2.5
double result3 = (double) (a / b); // result is 2.0 (wrong way to do it)
Operator Precedence
Java follows the standard mathematical order of operations:
- Parentheses
()
- Unary operators (
++
,--
,+
,-
) - Multiplication, Division, Modulus (
*
,/
,%
) - Addition, Subtraction (
+
,-
) - Assignment operators (
=
,+=
, etc.)
Example: Complex Expressions
// Order of operations example
int result1 = 10 + 5 * 2; // result is 20, not 30
int result2 = (10 + 5) * 2; // result is 30
// Compound calculations
int a = 10;
int b = 4;
int c = 3;
double result3 = (double) (a + b) / c; // result is 4.67
// Compound assignment
int count = 10;
count += 5; // same as count = count + 5
System.out.println(count); // outputs 15
Putting It All Together
This complete example demonstrates variables, console output, and arithmetic operations:
public class StudentGradeCalculator {
public static void main(String[] args) {
// Variable declarations
String studentName = "John Smith";
int mathScore = 85;
int scienceScore = 92;
int englishScore = 78;
// Calculate total and average
int totalScore = mathScore + scienceScore + englishScore;
double averageScore = (double) totalScore / 3;
// Calculate percentage (assuming max score is 100 per subject)
double maxPossibleScore = 3 * 100;
double percentage = (totalScore / maxPossibleScore) * 100;
// Output results
System.out.println("Student Grade Report");
System.out.println("-------------------");
System.out.println("Name: " + studentName);
System.out.println("Math: " + mathScore);
System.out.println("Science: " + scienceScore);
System.out.println("English: " + englishScore);
System.out.println("-------------------");
System.out.println("Total Score: " + totalScore);
System.out.printf("Average Score: %.2f\n", averageScore);
System.out.printf("Percentage: %.2f%%\n", percentage);
// Determine pass/fail status (pass if average >= 60)
boolean isPassed = averageScore >= 60;
System.out.println("Status: " + (isPassed ? "PASSED" : "FAILED"));
}
}
This program calculates a student's grades, demonstrating:
- Variable declaration and initialization
- Arithmetic operations
- Type casting for precise division
- Both simple and formatted console output
- Boolean expressions and ternary operators
Curated Content
What is a variable?
Resources
Java Compound Operators
Guided Project
Project Overview
In this guided project, you'll apply your knowledge of variables, console output, and arithmetic operations to solve real-world problems:
School Data Tracker
This project involves creating a program that:
- Stores student information using appropriate variable types
- Performs calculations on student grades and attendance
- Displays formatted reports using console output
- Demonstrates type casting to ensure accurate calculations
Bouncing Rainbow Squares
This visual project demonstrates:
- Using variables to track position and movement
- Applying arithmetic operations to calculate trajectories
- Understanding how variables change over time
- Creating a visual representation of mathematical calculations
By completing these projects, you'll gain hands-on experience with the core concepts of this module and see how they can be applied in different contexts.
Mastery Task 2 - Class Properties
Mastery Task Guidelines
Mastery Tasks are opportunities to test your knowledge and understanding through code. When a mastery task is shown in a module, it means that we've covered all the concepts that you need to complete that task. You will want to make sure you finish them in a timely fashion to stay on track and complete the sprint.
Each mastery task must pass 100% of the automated tests and code styling checks. Your code must be your own. If you have any questions, feel free to reach out for support.
AppSettings Update
Go to com.adventure.settings.AppSettings
and update the story to MT2_CaveEscape
.
Properties
A property is a Class instance variable, usually marked private, that is associated with getter/setter methods in the class. For example, a Person has the property age, which can store the value 30. One can reference that value using the getter method for the property. If you need to change the age because it's the person's birthday, you can simply assign a new value (31) to the property using it's setter method.
Working Classes
We will be working with the following class:
- Player
Player
Player is a class that has been built out considerably, but there are some new properties that we want to add as well as some methods to access the properties.
Name
The property we're adding today is name. This property will hold a String and we don't want outside classes to have direct access to it, so make the scope private.
With that property in place, we can now write the getter and setter methods for name. They are called getName and setName. The methods are already defined, but they don't do anything (at the moment). Read the comments above each method to see what the requirements are and write the code to complete the requirements.
Arithmetic in Code
The last thing you'll need to do is calculate if the player can open a door (the doors are heavy). Find the method canOpenDoor and read the comments to find out how to validate if the player can open doors.
Testing
To run the tests for this assignment, run the following:
./gradlew test --tests com.adventure.MT2
or by right-clicking the MT2 file and selecting "Run 'MT2'"
You can check your code styling by running the linter with the following command:
./gradlew checkstyleMain
You can run the game by going to the Main class and clicking on the run icon to the left of the main() method.