Sub topic 4
Variables and Types
What This Chapter Covers
In this chapter you will learn what a variable is, how Java uses types to describe what kind of data a variable holds, and how to declare, assign, and use variables in real programs.
This is an in-depth chapter. That means we will go slowly and thoroughly. We will look at every primitive type, explain the rules behind them, show common mistakes, and work through a full example. If some sections feel like review, skim them; if everything feels new, take your time.
Prerequisites
- You have read the previous chapter and understand Java program structure: a program lives inside a class, and execution starts at the
mainmethod. - You can run a Java program on your machine (or in an online Java tool).
public class Main {
public static void main(String[] args) {
System.out.println("Ready to learn about variables!");
}
}Run this program before continuing. Everything in this chapter will go inside the { } after main.
What Is a Variable?
A variable is a named box in memory that stores a value. You give the box a name, and later you can read the value from it or put a new value in it.
Here is the key idea in Java: every variable has a declared type, and that type never changes. A variable declared to hold a whole number will only ever hold whole numbers. This is called static typing, and it is one of the biggest differences between Java and languages like Python or JavaScript, where a variable can hold any kind of value at any time.
Why does Java do this? Because knowing the type ahead of time lets the compiler catch mistakes before your program runs. If you try to store text in a number variable, the program will not compile, and you will find the bug early.
Declaring and Assigning Variables
To create a variable, you write the type, then the name, then a semicolon:
int age;This line declares the variable: it creates the box but leaves it empty. To put a value in it, you assign:
age = 30;Most of the time you do both at once, in one line:
int age = 30;The = sign here is the assignment operator. It does not mean "equals" in the math sense. It means "store the value on the right into the variable on the left."
public class Main {
public static void main(String[] args) {
int age = 30;
String name = "Sara";
System.out.println(name + " is " + age + " years old.");
}
}Output:
Sara is 30 years old.Notice the + between pieces of text and a number. With strings, + glues values together. We will see more of that below.
Naming Rules and Conventions
A variable name must follow rules:
- It can contain letters, digits,
_, and$, and cannot start with a digit. - It cannot be a reserved word like
intorclass. - Names are case-sensitive:
ageandAgeare different variables.
By convention, Java programmers use camelCase: the first word is lowercase and each later word starts with a capital, like totalCost or firstName. Names should describe what the variable holds. x is legal but unhelpful.
The Primitive Types
Java's simplest types are called primitive types because they hold raw values directly, not objects. There are eight of them. You will use about half of them in everyday code, but you should know what all eight are.
Whole Numbers
| Type | Size | Range (roughly) | Typical use |
|---|---|---|---|
| `byte` | 8 bits | -128 to 127 | Tiny numbers, raw data |
| `short` | 16 bits | about ±32,000 | Rarely used |
| `int` | 32 bits | about ±2.1 billion | The default for whole numbers |
| `long` | 64 bits | huge (add `L` to literals) | Counts that can exceed int range |
For almost all whole-number work, use int. Reach for long only when values might pass about 2.1 billion, such as counting seconds since 1970.
int count = 42;
long worldPopulation = 8_000_000_000L; // L marks a long literalDecimal Numbers
| Type | Size | Precision | Typical use |
|---|---|---|---|
| `float` | 32 bits | about 7 digits | Rare; needs an `f` suffix |
| `double` | 64 bits | about 15 digits | The default for decimals |
double price = 19.99;
float ratio = 0.5f; // f is required or this will not compileUse double for nearly all decimal math.
Other Primitives
| Type | Holds | Values |
|---|---|---|
| `char` | one character | A single letter, digit, or symbol in single quotes |
| `boolean` | true or false | Only `true` or `false` |
char grade = 'A';
boolean isActive = true;Note that char uses single quotes and holds exactly one character, while the String type uses double quotes and holds text of any length. Mixing these up is a very common beginner error.
How Numbers Are Stored
Whole-number types use a fixed number of bits. If a value grows past the maximum, it overflows: it wraps around to a large negative number, with no error message. This is a real failure mode in production code, so choose long early if values could grow.
int max = Integer.MAX_VALUE; // 2147483647
System.out.println(max + 1); // prints -2147483648, no error!The String Type
String is not a primitive. It is a class, a richer type that represents text. You write it with a capital S and create it from double-quoted text:
String greeting = "Hello";Strings can be joined with +, which is called concatenation:
String first = "Java";
String second = "Rocks";
String message = first + " " + second; // "Java Rocks"When + mixes strings with numbers, Java converts the number to text automatically:
System.out.println("Score: " + 95); // "Score: 95"But be careful: if the + runs before any string appears, it does math instead:
System.out.println(1 + 2 + " total"); // "3 total"
System.out.println("Total: " + 1 + 2); // "Total: 12", not 3!The second line surprises many beginners. Java works left to right, so "Total: " + 1 makes the string "Total: 1", and then adding 2 appends text. Add parentheses if you want math first: "Total: " + (1 + 2).
Useful String Operations
Strings come with built-in methods (behaviors):
String name = " Ada Lovelace ";
String trimmed = name.trim(); // removes spaces at the ends
int length = trimmed.length(); // counts characters: 12
String upper = trimmed.toUpperCase(); // "ADA LOVELACE"
char initial = trimmed.charAt(0); // 'A'
boolean hasAda = trimmed.contains("Ada"); // trueTwo important details:
- String positions (indexes) start at 0, not 1. The first character is at index 0.
- Strings cannot be changed after creation. Methods like
toUpperCase()return a new string; the original stays the same. This property is called immutability.
How Types Interact: Conversion
Sometimes you need to turn one type into another.
Widening (Automatic)
When moving to a type that can hold more information, Java converts automatically:
int small = 100;
double big = small; // int to double, safe, automatic
System.out.println(big); // 100.0Narrowing (Manual Cast)
Moving to a type that might lose information requires a cast: writing the target type in parentheses. Java makes you do this by hand because it is dangerous.
double precise = 9.75;
int truncated = (int) precise; // result is 9; the .75 is cut off, not roundedYou can also convert between text and numbers using helper methods:
String text = "42";
int number = Integer.parseInt(text); // String to int
String back = String.valueOf(number); // int to StringInteger.parseInt throws an error at runtime if the text is not a valid number, so only use it when you trust the input or have checked it first.
Constants: When a Variable Should Not Change
If a value should never change after being set, mark it final. Trying to change it causes a compile error.
final int DAYS_IN_WEEK = 7;
// DAYS_IN_WEEK = 8; // compile error: cannot assign to a final variableBy convention, constants use ALL_CAPS names with underscores. Using constants instead of bare numbers like 7 scattered through your code makes programs easier to read and change.
Putting It Together: A Complete Example
This small program combines several variables of different types:
public class Receipt {
public static void main(String[] args) {
String item = "Coffee";
int quantity = 3;
double unitPrice = 2.50;
double subtotal = quantity * unitPrice;
final double TAX_RATE = 0.08;
double tax = subtotal * TAX_RATE;
double total = subtotal + tax;
System.out.println("Item: " + item);
System.out.println("Qty: " + quantity + " x $" + unitPrice);
System.out.println("Subtotal: $" + subtotal);
System.out.println("Tax: $" + tax);
System.out.println("Total: $" + total);
System.out.println("Paid with cash: " + true);
System.out.println("First letter of item: " + item.charAt(0));
}
}Run it and study the output. Trace each line back to the variable that produced it. Type errors here would be caught by the compiler before the program ever ran — that is the safety static typing buys you.
Common Beginner Mistakes
- Using
==to compare strings instead of.equals(). - Forgetting the
fon float literals or theLon long literals. - Assuming
(int)casts round; they truncate. - Writing
String name = 'Ada';— strings need double quotes. - Reading a variable before assigning it a value.
- Expecting
"Total: " + 1 + 2to do arithmetic.
Each of these produces either a clear compile error or a subtly wrong result. Getting them wrong once, on purpose, is the fastest way to remember them.
Summary
- A variable is a named box for a value; its type is fixed at declaration.
- Whole numbers:
intby default,longfor big values. - Decimals:
doubleby default; never for money in real code. charholds one character in single quotes;booleanholdstrue/false.Stringis a class for text; join with+, compare with.equals(), index from 0.- Widening conversions are automatic; narrowing needs a cast and may lose data.
- Use
finalfor values that must not change.
Next chapter: we put these variables to work with operators and expressions.
Exercise
What does this print, and why? System.out.println("Sum: " + 2 + 3);
Show answer
It prints "Sum: 23". Java evaluates left to right, so "Sum: " + 2 makes the string "Sum: 2", and then + 3 appends "3". Use parentheses — "Sum: " + (2 + 3) — to get "Sum: 5".
Exercise
You write int x = 7.5;. What happens, and how do you fix it?
Show answer
It is a compile error, because 7.5 is a double and storing a double in an int loses information. Fix it with a cast: int x = (int) 7.5; — which stores 7 — or change the variable type to double.
Exercise
Which type would you choose for (a) the number of pets someone has, (b) a file size in bytes that could exceed 3 billion, (c) a letter grade, (d) whether an account is locked?
Show answer
(a) int, the default for whole numbers. (b) long, since int overflows past about 2.1 billion. (c) char, holding one character like 'A'. (d) boolean, holding true or false.