java-foundations Lesson 1 20 min read

Variables & Types

Named boxes that remember things

Reading: Reges & Stepp: Ch. 2 §2.1–2.2

Quick check before you start: Do you know the difference between print and println? If not, review the previous lesson. Can you write a program that prints your name?

Practice this topic: Lab 1 exercises on variables

After this lesson, you will be able to:

  • Declare and initialize variables of the four core primitive types
  • Explain why Java requires explicit type declarations
  • Choose the correct type for different kinds of data
  • Use meaningful variable names following Java conventions
  • Create constants with the final keyword

Named Boxes

So far, your programs have only used hardcoded values — string literals like "Hello, World!" that never change. Real programs work with data that varies: ages, prices, temperatures, scores. To work with data, you need somewhere to store it. That place is a variable.

A variable is a named storage location in memory. Think of it as a labeled box. You choose the label (the name) and what goes inside (the type).

int age = 25;
double gpa = 3.75;
String name = "Alice";

Once you declare a variable as an int, it holds integers — always. You cannot suddenly put a string in it. This is Java’s strong typing, and it is the single biggest shift from Python.

From CSCD 110: In Python, you wrote age = 25 and Python figured out the type. You could even change it later: age = "twenty" and Python would not complain. In Java, you declare the type upfront, and it is permanent: int age = 25; — and then you can never assign a string to age.


Declaration and Initialization

Every variable in Java must be declared before use. A declaration tells the compiler the type and the name.

Declaration Only

int age;           // declares age as an int (no value yet)
double gpa;        // declares gpa as a double
String name;       // declares name as a String

These variables exist in memory, but they have no value. Local variables (inside a method) have no default value in Java. If you try to use an uninitialized variable, the compiler refuses:

int count;
System.out.println(count);  // COMPILER ERROR: variable might not have been initialized

Declaration with Initialization

The safer approach: declare and initialize in one step:

int age = 25;
double gpa = 3.75;
String name = "Alice";
boolean isEnrolled = true;

Do this almost every time. Declare, give it a value, move on.

Reassignment

You can change a variable’s value — but only to a value of the same type:

int age = 25;
age = 30;         // OK: 30 is an int
age = age + 1;   // OK: age + 1 is an int (31)
age = 3.14;      // COMPILER ERROR: double cannot be converted to int

Watch out: The = sign in Java is assignment, not equality. int age = 25; means “set age to 25,” not “age equals 25 forever.” The equality comparison operator is ==, which you will learn in Week 2.


The Four Core Types

Java has eight primitive types, but four cover 99% of what you need. Learn these four deeply.

int — Whole Numbers

Use int for values without decimals: ages, counts, years, IDs, loop counters.

int age = 25;
int year = 2026;
int studentCount = 150;
int temperature = -5;     // ints can be negative

An int is 32 bits, ranging from about -2.1 billion to +2.1 billion. Plenty for CS1.

double — Decimal Numbers

Use double for values that have or might have decimals: prices, GPAs, measurements.

double gpa = 3.75;
double price = 19.99;
double temperature = 98.6;
double pi = 3.14159;

A double is 64 bits with about 15-16 digits of precision.

Key insight: If a value could ever have a decimal point, use double. Prices, GPAs, averages, measurements — all double. Ages, counts, IDs — int. When in doubt, double is safer.

boolean — True or False

Use boolean for values that are either true or false — nothing else.

boolean isEnrolled = true;
boolean isGraduated = false;
boolean hasPassedExam = true;

Unlike Python, Java’s boolean is not an integer. You cannot use 0 for false or 1 for true. The only valid values are the keywords true and false.

char — Single Character

Use char for exactly one character, enclosed in single quotes:

char grade = 'A';
char initial = 'J';
char symbol = '!';
char digit = '7';     // the CHARACTER '7', not the NUMBER 7

Watch out: Do not confuse char and String:

  • 'A' (single quotes) is a char — exactly one character
  • "A" (double quotes) is a String — a sequence of characters
  • char x = "A"; is a compiler error

Check Your Understanding
What type would you use for a person's age?
Aint — whole number, no decimals
Bdouble — could have decimals
CString — it is text
Dboolean — yes or no
Answer: A. Age is a whole number — you are 25, not 25.3. Use int.

Check Your Understanding
What is wrong with this code?
ANothing — it will compile and run
BDouble quotes are used instead of single quotes for a char
CThe variable name 'grade' is not allowed
Dboolean should be used instead
Answer: B. char requires single quotes: char grade = 'A';
char grade = "A";  // WRONG: double quotes make a String

</div>


Strings: Your First Reference Type

You have been using String since Lecture 1, but it is not a primitive. It is a reference type — a class. You will learn what that means in Week 9.

For now, treat String as “text”:

String name = "Alice";       // double quotes
String empty = "";           // valid: empty string (zero characters)
String greeting = "Hello, " + name + "!";  // concatenation

Notice String starts with uppercase S. This is a clue it is a class, not a primitive. All primitives (int, double, boolean, char) start with lowercase.

The trick: Lowercase first letter = primitive. Uppercase first letter = class (reference type). This naming convention tells you instantly what kind of type you are looking at.


Type Safety: The Compiler Catches Bugs

Java’s type system catches bugs before your program runs:

int age = 25;
age = 3.14;          // ERROR: double -> int
age = "twenty-five"; // ERROR: String -> int
age = true;          // ERROR: boolean -> int

Every one of these fails at compile time — before the program ever runs. The compiler is catching bugs that, in Python, would not appear until that line executed.

Widening: Safe Automatic Conversion

An int can always fit in a double. Java allows this widening automatically:

int x = 5;
double y = x;        // OK: y becomes 5.0
System.out.println(y);  // prints: 5.0

Narrowing: Requires a Cast

Putting a double into an int loses the decimal part. Java requires you to explicitly cast:

double gpa = 3.99;
int truncated = (int) gpa;    // truncated becomes 3 (NOT rounded!)
System.out.println(truncated); // prints: 3

The (int) cast tells the compiler: “I know I am losing data, and I accept that.”

Key insight: Widening (small → big) is automatic. Narrowing (big → small) requires a cast and truncates. When in doubt, Java makes you be explicit.


Naming Conventions

Java has conventions for how you name things. Follow them — code looks unprofessional and is harder to read when you do not.

The Three Styles

Style Used For Examples
camelCase Variables and methods age, studentName, isEnrolled
PascalCase Classes and interfaces Student, Scanner, String
UPPER_SNAKE_CASE Constants (final) MAX_AGE, TAX_RATE, PI

Meaningful Names

Names should describe what the variable holds:

// BAD: What do these mean?
int x = 25;
double y = 3.14;
String s = "Alice";

// GOOD: Instantly clear
int age = 25;
double gpa = 3.14;
String studentName = "Alice";

You will read your code far more than you write it. Spend the extra seconds to type meaningful names.


Constants with final

Some values never change: the number of months in a year, the value of pi, the sales tax rate. Use the final keyword:

final double TAX_RATE = 0.08;
final int MONTHS_IN_YEAR = 12;
final double PI = 3.14159;

If you accidentally try to reassign a final variable, the compiler stops you:

final int MAX_STUDENTS = 200;
MAX_STUDENTS = 250;  // COMPILER ERROR: cannot assign to final variable

By convention, constants use UPPER_SNAKE_CASE to stand out.


Putting It Together: Rectangle Calculator

Let us apply everything with a real example:

public class Variables {
    public static void main(String[] args) {
    // Declare and initialize
    double width = 5.0;
    double height = 3.0;

    // Calculate area and perimeter
    double area = width * height;
    double perimeter = 2 * (width + height);

    // Print results
    System.out.println("Width: " + width);
    System.out.println("Height: " + height);
    System.out.println("Area: " + area);
    System.out.println("Perimeter: " + perimeter);
    }
}

Output:

Width: 5.0
Height: 3.0
Area: 15.0
Perimeter: 16.0

Notice the D step from IPO-CDS guided our choices. Everything is a measurement, so everything is double.


What you learned

  • Variables are named storage locations. Declare the type and name, then initialize: int age = 25;
  • Four core types cover 99%: int (whole numbers), double (decimals), boolean (true/false), char (single character)
  • String is for text. Uppercase S, uses double quotes.
  • Java is strongly typed. The compiler enforces type rules. Widening is automatic; narrowing requires a cast.
  • Names matter. Use camelCase for variables, meaningful names, and final for constants in UPPER_SNAKE_CASE.

What Comes Next

Next we go deeper into data types — all eight primitive types, memory sizes, and when to use the less common ones like long and float. You will also learn how Java handles mixed-type arithmetic.

Then, Lecture 5: Scanner — reading input from users.