Unit 1 · Java setup and first programs
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.
Integer.MAX_VALUE + 1 and explain the result.int and double division?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.
1. What is the result of 7 / 2 when both operands are int?
2. Which type is best for a true/false value?
charbooleandoubleStringboolean stores true or false.3. Why cast before division?
double makes the division floating-point, preserving the fractional result.Choose a type for a person's age, a bank balance, whether a file exists, and a single initial.
int age, double balance, boolean fileExists, and char initial.Write an expression for 3 completed tutorials out of 4 as a percentage.
double percentage = 100.0 * 3 / 4; produces 75.0. Using 100 * 3 / 4 also works here, but using a decimal documents the intended arithmetic.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.