← Back to Home

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

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 and myvar are different variables)
  • Cannot use reserved words like int or class 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 line
  • System.out.print(x) - Prints the value of x without moving to a new line
  • System.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:

  1. Parentheses ()
  2. Unary operators (++, --, +, -)
  3. Multiplication, Division, Modulus (*, /, %)
  4. Addition, Subtraction (+, -)
  5. 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?

Declaring variables in Java

Primitive Data Types

Writing Console Output in Java

Assignment, Arithmetic, and Unary Operators

Java Compound Operators

Java Type Casting

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.