Tutorial 2: Variables and Primitive Types

Unit 1 · Java setup and first programs

Objectives

Values and variables

A variable is a named location whose type determines which values it can hold. Declare a variable with its type and name, then initialize it before reading it. Prefer meaningful names that describe the value rather than its representation.

int tutorialCount = 4;
double completionRate = 0.75;
boolean enrolled = true;
char section = 'A';

completionRate = completionRate + 0.05;

Java's common primitive types include int, long, double, float, boolean, and char. Integer arithmetic stays integral. A wider type can usually receive a narrower value automatically, but narrowing needs an explicit cast and may lose information.

int completed = 3;
int total = 4;
double rate = (double) completed / total;

long population = 8_000_000_000L;
int truncated = (int) population;

Use underscores in numeric literals when they improve readability. Be cautious with overflow: an int cannot represent every possible integer.

Practice

  1. Declare variables for a student's name, age, average mark, and completion status.
  2. Calculate a percentage without integer division.
  3. Experiment with Integer.MAX_VALUE + 1 and explain the result.

Self-check

  1. Why must a local variable be initialized before use?
  2. What is the difference between int and double division?
  3. What risk comes with narrowing a long to an int?

Mastery task: Create a study-time calculator that converts hours and minutes into total minutes, then reports the fraction of a weekly target completed.

Self-Check Quiz

1. What is the result of 7 / 2 when both operands are int?

Answer(A) Integer division discards the fractional part.

2. Which type is best for a true/false value?

Answer(B) boolean stores true or false.

3. Why cast before division?

AnswerConverting one operand to double makes the division floating-point, preserving the fractional result.

Exercises

Exercise 1: Type Selection

Choose a type for a person's age, a bank balance, whether a file exists, and a single initial.

Sample answerint age, double balance, boolean fileExists, and char initial.

Exercise 2: Calculate a Rate

Write an expression for 3 completed tutorials out of 4 as a percentage.

Sample answerdouble percentage = 100.0 * 3 / 4; produces 75.0. Using 100 * 3 / 4 also works here, but using a decimal documents the intended arithmetic.

Homework

  1. Write a study-time calculator that reads hours and minutes and reports total minutes.
  2. Read four marks and print their average with two decimal places.
  3. Test your program with zero, negative, and decimal inputs and state which inputs should be rejected.
Sample homework answer
int hours = 2;
int minutes = 30;
int totalMinutes = hours * 60 + minutes;
System.out.printf("Total: %d minutes%n", totalMinutes);
A complete solution validates non-negative hours and minutes, uses double for the average, and explains its boundary decisions.