Java Fundamentals, Part 1: Variables, Types, and Control Flow
Java & Spring Boot for Beginners · Part 3 of 14
- #Java
- #Spring Boot
- #Beginners
- #Fundamentals
In Part 2 you got a JDK, IntelliJ, and
a Hello program running from both the IDE and the terminal. Now we start
writing the language itself.
This is the first of three fundamentals posts. It covers the pieces you'll reach for in literally every program: how to store a value, what types Java gives you, how to combine values with operators, and how to make the program take one path or another. None of it is hard. The goal is to build a clear mental model now so the later parts — classes, collections, Spring — have something solid to sit on.
I'll build up one small example as we go: a program that prices cinema tickets for a group. By the end it'll do something genuinely useful, and every concept will have earned its place in it.
Variables: a name for a value
A variable is a named box that holds a value. In Java you say what kind of value goes in the box, then the name, then the value:
int age = 34;
double basePrice = 12.50;
boolean isMember = true;
String name = "Ana";
Read those right to left: take the value 34, put it in a box called age,
and that box holds ints from now on. The type on the left is a promise the
compiler holds you to — assign age = "old" later and the code won't compile.
That sounds restrictive; in practice it catches a genuinely large share of bugs
before the program ever runs, which is most of why people choose Java for
systems that have to stay correct.
Once declared, you can reassign a variable (as long as the new value fits the
type) or mark it final to freeze it:
final double TAX_RATE = 0.09; // reassigning this is now a compile error
I use final liberally. A value that never changes is one less thing to track
when you're reading code later.
Types: the eight primitives, and everything else
Java values come in two families, and the difference matters more than any other single thing in this post.
Primitives are the eight built-in types that hold a raw value directly:
| Type | Holds | You'll use |
|---|---|---|
int | whole numbers, ~±2.1 billion | constantly |
long | whole numbers, very large | IDs, timestamps, money-in-cents |
double | decimal numbers | measurements, rates |
boolean | true or false | every condition |
char | a single character | rarely, on its own |
byte, short, float | smaller / narrower versions | almost never as a beginner |
For 90% of beginner code the honest shortlist is int, long, double,
boolean. Reach for the others when you have a specific reason.
Everything else is an object, accessed through a reference — the variable
holds not the value itself but the address of a value living elsewhere in
memory. String is the one you'll meet first:
String greeting = "Hello";
int length = greeting.length(); // objects have methods; primitives don't
Two consequences of the primitive/object split that trip up every beginner eventually:
- An object reference can be
null— it points at nothing. Call a method on anullreference and you get aNullPointerException, the single most common Java error. A primitive can never benull. - Compare primitives with
==. Compare objects —Strings especially — with.equals().==on two objects asks "the same box?", not "the same contents?", and that is almost never the question you mean to ask.
var: let the compiler write the type
Since Java 10 you can write var for a local variable and the compiler infers
the type from the right-hand side:
var age = 34; // inferred as int
var name = "Ana"; // inferred as String
var prices = new ArrayList<Double>(); // saves repeating the type twice
var is still static typing — age is exactly as much an int as before, and
you still can't assign a string to it. It's purely less to type. My rule: use it
when the type is obvious from the same line (new ArrayList<>()), spell the type
out when it isn't (var result = calculate(); — inferred as what?).
Starting the example
Here's the beginning of the ticket program:
final double BASE_PRICE = 12.50;
final double TAX_RATE = 0.09;
int customerAge = 34;
String dayOfWeek = "TUESDAY";
boolean isStudent = false;
Operators: doing things with values
Operators combine values. The arithmetic ones are unsurprising — + - * / — with
two catches worth knowing on day one:
int result = 7 / 2; // 3, not 3.5 — integer division truncates
double real = 7 / 2.0; // 3.5 — one double operand makes the whole thing double
int remainder = 7 % 2; // 1 — modulo, the leftover; great for "every Nth"
+ also concatenates strings, and mixing a string with anything converts that
thing to text:
String label = "Age: " + customerAge; // "Age: 34"
Comparison operators (== != < > <= >=) produce a boolean. Logical
operators combine booleans: && (and), || (or), ! (not).
boolean getsDiscount = customerAge < 16 || customerAge >= 65 || isStudent;
&& and || short-circuit: a() && b() never calls b() if a() is already
false. That's not just a performance note — it's the idiom for guarding against
null:
if (name != null && name.length() > 0) { ... } // safe: length() only runs if name isn't null
Finally, the shorthands you'll see everywhere: total += price means
total = total + price, and count++ adds one.
Control flow: making the program choose
So far the program runs top to bottom. Control flow lets it take different paths.
if / else
The workhorse. The condition in parentheses must be a boolean:
double price = BASE_PRICE;
if (customerAge < 16) {
price = price * 0.5; // children half price
} else if (customerAge >= 65 || isStudent) {
price = price * 0.7; // seniors and students 30% off
} else {
price = BASE_PRICE; // everyone else full price
}
Always use braces, even for one line. Skipping them is a well-documented source of bugs, and every team style guide I've worked under requires them.
switch
When you're checking one value against many fixed options, a switch says that
intent more clearly than a ladder of else ifs. Modern Java's arrow form is
clean and doesn't have the old "fell through because I forgot break" trap:
double matineeDiscount = switch (dayOfWeek) {
case "MONDAY", "TUESDAY", "WEDNESDAY" -> 2.00; // midweek: $2 off
case "THURSDAY" -> 1.00;
default -> 0.00; // weekend: no discount
};
price = price - matineeDiscount;
A switch can be a statement (do something) or, as here, an expression that
produces a value you assign. The default branch is required when it's an
expression — the compiler makes sure you've covered every case.
Loops
Loops repeat a block. Three forms, in rough order of how often I use them:
// for-each — "do this for every item". The default when you have a collection.
int[] groupAges = {34, 9, 70, 41};
double groupTotal = 0.0;
for (int a : groupAges) {
groupTotal += priceFor(a);
}
// classic for — when you need the index, or a specific number of iterations
for (int i = 0; i < groupAges.length; i++) {
System.out.println("Ticket " + (i + 1) + " of " + groupAges.length);
}
// while — when you don't know the count up front (read until end-of-input, retry until success)
while (!queue.isEmpty()) {
process(queue.poll());
}
break exits a loop early; continue skips to the next iteration. Use them
sparingly — a loop that reads straight through is easier to reason about.
Putting it together
Here's the whole thing, every concept in this post pulling its weight:
public class TicketPricer {
static final double BASE_PRICE = 12.50;
static final double TAX_RATE = 0.09;
public static void main(String[] args) {
int[] groupAges = {34, 9, 70, 41};
String dayOfWeek = "TUESDAY";
boolean allStudents = false;
double subtotal = 0.0;
for (int age : groupAges) {
subtotal += priceFor(age, dayOfWeek, allStudents);
}
double total = subtotal * (1 + TAX_RATE);
System.out.printf("Party of %d — total: $%.2f%n", groupAges.length, total);
}
static double priceFor(int age, String day, boolean isStudent) {
double price;
if (age < 16) {
price = BASE_PRICE * 0.5;
} else if (age >= 65 || isStudent) {
price = BASE_PRICE * 0.7;
} else {
price = BASE_PRICE;
}
double matineeDiscount = switch (day) {
case "MONDAY", "TUESDAY", "WEDNESDAY" -> 2.00;
case "THURSDAY" -> 1.00;
default -> 0.00;
};
return Math.max(0, price - matineeDiscount);
}
}
Run it and you'll get Party of 4 — total: $37.64. Change the day, the ages, the
student flag, and watch the number move. That's a real program: typed values,
operators combining them, if and switch choosing a path, a loop doing the
work once per person.
What to take away
- Two families of values: primitives hold a value, objects hold a
reference that might be
null. Compare primitives with==, objects with.equals(). - The beginner shortlist of types is
int,long,double,boolean, plusString. Usevarwhen the type is obvious on the line. if/elsebranches on a boolean;switchfans out on one value and reads cleaner when there are more than a couple of cases; loops repeat, and for-each is the default.&&and||short-circuit — that's the standard way to guard anullcheck.
Type the TicketPricer example out by hand, run it, break it, fix it. That does
more than re-reading this ever will.
Next up: Part 4 — Java fundamentals, part 2: classes, objects, and object-oriented thinking. We stop using other people's types and start defining our own.