Learn Java · 2/15

Java Fundamentals: Building Blocks

10 min read

☕ Java Fundamentals: Building Blocks

Welcome to the foundational concepts of Java! Think of this as learning the alphabet and basic grammar before you start writing epic novels. We'll cover the absolute essentials you'll use every single day as a Java developer. Let's get brewing!


📦 1. Variables and Primitives: Memory Boxes for Your Data

The Problem: Imagine you're building a simple calculator. You need a way to hold the numbers the user enters and the result of the calculation. How do you "remember" these values while your program is running?

The Solution: You store them in variables! A variable is like a labeled box in your computer's memory where you can keep a piece of information. To make sure the computer knows what kind of information you're storing (a whole number, a decimal, a single character?), you give it a type.

In Java, the most basic types are called primitive data types. These are the fundamental building blocks for all other data in Java.

The "Must-Know" Primitives

While Java has eight primitive types, in the real world, you'll find yourself using these four most of the time:

  • int: This is for whole numbers, both positive and negative. Think of counting things: the number of users, the score in a game, or your age. 🔢

    • Example: int userAge = 30;
    • Under the hood: An int in Java uses 32 bits of memory. This means it can hold numbers from -2,147,483,648 to 2,147,483,647. If you try to store a number larger than that, you'll get an "overflow" error. It's like trying to pour a gallon of water into a pint glass!
  • double: This is for numbers with a decimal point, also known as floating-point numbers. Use this for things that need precision, like prices, measurements, or scientific calculations. 💰

    • Example: double price = 19.99;
    • Industry Practice: You might see float being used as well, but double has more precision and is the default for decimal numbers in Java. For financial calculations, developers often use a special BigDecimal class to avoid tiny rounding errors, but double is perfect for most other cases.
  • boolean: This is the simplest of them all. It can only have one of two values: true or false. It's perfect for tracking states or answering yes/no questions. 🤔

    • Example: boolean isLoggedIn = true;
    • Fun Fact: The boolean type is named after George Boole, an English mathematician who created Boolean algebra, which is the foundation of all modern computer logic. So, every time you use a boolean, you're tipping your hat to a 19th-century genius!
  • char: This holds a single character. It's enclosed in single quotes.

    • Example: char grade = 'A';

Declaring and Initializing Variables

Creating a variable is a two-step process, though you can often do it in one line.

  1. Declaration: You state the type and the name of the variable.
    java
    int numberOfStudents;
  2. Initialization: You assign a value to it for the first time.
    java
    numberOfStudents = 25;

Or, you can do it all at once, which is what you'll usually do:

java
int numberOfStudents = 25;
double accountBalance = 150.75;
boolean isCompleted = false;
char firstInitial = 'J';

System.out.println(numberOfStudents); // This will print 25 to the console

🧮 2. Operators: Performing Math, Logic, and Comparisons

The Problem: Okay, so we have our data stored in variables. Now what? How do we actually do things with it? How do we add two numbers, check if a user's age is over 18, or see if two conditions are true at the same time?

The Solution: We use operators! Operators are special symbols that perform operations on our variables and values.

Arithmetic Operators

These are the ones you learned in math class. They let you perform calculations.

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
  • % (Modulus - this one gives you the remainder of a division. Super useful!)
java
int score = 100;
int newScore = score + 20; // newScore is now 120

int players = 10;
int teams = 4;
int playersLeftOut = players % teams; // playersLeftOut is 2, because 10 / 4 is 2 with a remainder of 2.

Funny Exaggeration: Without the modulus operator, you'd have to figure out who's left out of a team-building exercise by doing long division on a whiteboard. The horror!

Comparison Operators

These operators compare two values and give you a boolean (true or false) result. They are the heart of decision-making in your code.

  • == (Equal to)
  • != (Not equal to)
  • > (Greater than)
  • < (Less than)
  • >= (Greater than or equal to)
  • <= (Less than or equal to)
java
int userAge = 18;
boolean isAdult = userAge >= 18; // isAdult will be true

int yourScore = 95;
int myScore = 95;
boolean areScoresEqual = yourScore == myScore; // areScoresEqual will be true

Heads up! A very common beginner mistake is to use a single = for comparison. Remember, = is for assigning a value, while == is for comparing values. Mixing them up can lead to some head-scratching bugs!

Logical Operators

These are used to combine multiple boolean expressions.

  • && (AND): Returns true only if both conditions are true.
  • || (OR): Returns true if at least one of the conditions is true.
  • ! (NOT): Flips the value of a boolean ( true becomes false, and false becomes true).
java
boolean hasValidID = true;
boolean hasTicket = true;

// Can this person enter the venue?
boolean canEnter = hasValidID && hasTicket; // This will be true

boolean isMember = false;
boolean hasCoupon = true;

// Can they get a discount?
boolean canGetDiscount = isMember || hasCoupon; // This will be true

boolean isTired = true;
boolean isReadyToGo = !isTired; // isReadyToGo will be false

🚦 3. Control Flow (If/Else, Switch): Making Decisions

The Problem: Your program runs from top to bottom, one line at a time. But what if you want it to do different things based on certain conditions? For example, show a "Welcome back!" message if a user is logged in, and a "Please log in" message if they are not.

The Solution: You use control flow statements to direct the "flow" of your program's execution.

The if/else if/else Statement

This is the most common way to make decisions in code. It's like your program is at a fork in the road and has to decide which path to take.

The basic structure is:

java
if (condition) {
  // Do this code if the condition is true
} else {
  // Do this code if the condition is false
}

Real-life scenario: Let's say we're coding the logic for an ATM.

java
double accountBalance = 500.00;
double withdrawalAmount = 600.00;

if (withdrawalAmount <= accountBalance) {
  System.out.println("Withdrawal successful. Please take your cash.");
  accountBalance = accountBalance - withdrawalAmount;
} else {
  System.out.println("Insufficient funds. You can't withdraw more than you have!");
}

You can also chain them together to check multiple conditions:

java
int score = 85;

if (score >= 90) {
  System.out.println("You got an A!");
} else if (score >= 80) {
  System.out.println("You got a B!");
} else if (score >= 70) {
  System.out.println("You got a C.");
} else {
  System.out.println("You need to study more.");
}

The program checks each condition from top to bottom and runs the code for the first one that is true.

The switch Statement

A switch statement is a clean way to handle multiple if/else if conditions when you're comparing a single variable against a list of possible values.

The Problem it Solves: Imagine you have a variable that can be one of 10 different values, and you need to do something different for each. An if/else if chain would be long and a bit messy.

The switch solution:

java
int dayOfWeek = 4; // 1 = Sunday, 2 = Monday, etc.
String dayName;

switch (dayOfWeek) {
  case 1:
    dayName = "Sunday";
    break; // The 'break' is important! It stops the execution.
  case 2:
    dayName = "Monday";
    break;
  case 3:
    dayName = "Tuesday";
    break;
  case 4:
    dayName = "Wednesday";
    break;
  case 5:
    dayName = "Thursday";
    break;
  case 6:
    dayName = "Friday";
    break;
  case 7:
    dayName = "Saturday";
    break;
  default: // This runs if none of the cases match
    dayName = "Invalid day";
    break;
}

System.out.println("Today is " + dayName); // Prints "Today is Wednesday"

Industry Practice: The switch statement is often used for things like handling menu options, interpreting error codes, or dealing with a fixed set of states in your application. Modern Java has introduced enhanced switch expressions that are even more concise!


🔄 4. Loops (For, While, Do-While): Repeating Actions Efficiently

The Problem: You need to print the numbers from 1 to 100. Are you going to write System.out.println(1);, System.out.println(2);, and so on, 100 times? Of course not! That would be insane. We're programmers; we make the computer do the boring, repetitive work.

The Solution: Loops! Loops allow you to execute a block of code over and over again until a certain condition is met.

The for Loop

This is your go-to loop when you know exactly how many times you want to repeat an action.

It has three parts inside the parentheses, separated by semicolons:

  1. Initialization: A counter variable is created (int i = 0;). This happens only once.
  2. Condition: The loop will continue to run as long as this condition is true (i < 5;).
  3. Increment/Decrement: What to do with your counter after each repetition (i++ means "add one to i").
java
// This loop will run 5 times
for (int i = 0; i < 5; i++) {
  System.out.println("This is loop number: " + (i + 1));
}

Output:

ada
This is loop number: 1
This is loop number: 2
This is loop number: 3
This is loop number: 4
This is loop number: 5

The while Loop

The while loop is used when you want to loop as long as a condition is true, but you don't necessarily know how many times it will run beforehand.

Real-life scenario: Imagine a game where a player needs to keep rolling a die until they get a 6. You don't know if it will take one roll or fifty rolls.

java
int diceRoll = 0;
int attempts = 0;

while (diceRoll != 6) {
  // Math.random() gives a random double between 0.0 and 0.999...
  // We multiply by 6, cast to int, and add 1 to get a number from 1 to 6.
  diceRoll = (int)(Math.random() * 6) + 1;
  attempts++;
  System.out.println("Attempt " + attempts + ": You rolled a " + diceRoll);
}

System.out.println("Success! You rolled a 6 in " + attempts + " attempts.");

Warning: Be careful with while loops! If the condition never becomes false, you'll create an infinite loop, and your program will run forever (or until you stop it). It's the programming equivalent of a car that won't stop accelerating.

The do-while Loop

This one is a variation of the while loop. The only difference is that the code inside a do-while loop is guaranteed to run at least once, because the condition is checked after the code block is executed.

java
int userChoice;
// We use a Scanner to get input from the user. Don't worry about the details for now.
Scanner scanner = new Scanner(System.in);

do {
  System.out.println("--- Main Menu ---");
  System.out.println("1. Start New Game");
  System.out.println("2. Load Game");
  System.out.println("3. Exit");
  System.out.print("Enter your choice: ");
  userChoice = scanner.nextInt();
} while (userChoice != 3); // Keep showing the menu until the user chooses to exit.

System.out.println("Thanks for playing!");

This is perfect for menus because you always want to show the menu options at least once.


📚 References for Extra Reading

Challenge

Inventory Management Simulator

Your task is to write a Java program within the main method to simulate a simple inventory management system for a single product over 5 days. You must use variables, operators, a for loop, a switch statement, and if/else logic.

Requirements:

  1. Declare and initialize the following variables before any loops:

    • An int named stockCount with an initial value of 100.
    • A double named price with a value of 24.99.
    • An int named lowStockThreshold with a value of 25.
    • A boolean named isStockCritical, initialized to false.
  2. Create a for loop that runs for exactly 5 iterations, representing 5 days (from day 0 to day 4).

  3. Inside the for loop, use a switch statement that operates on the loop's counter variable. This will simulate different events for each day:

    • case 0: A sale occurs. Decrease stockCount by 15.
    • case 1: A large sale occurs. Decrease stockCount by 70.
    • case 2: A restock arrives. Increase stockCount by 50.
    • case 4: Another sale occurs. Decrease stockCount by 12.
    • For any other day (default), do nothing.
  4. Immediately after the switch statement but still inside the loop, implement the following logic using an if/else statement and comparison operators:

    • Check if the current stockCount is less than the lowStockThreshold.
    • If it is, set the isStockCritical boolean to true.
    • Otherwise, set isStockCritical to false.

Expected result

Your code should correctly implement the inventory simulation logic. A correct solution will feature:

  • Proper declaration and initialization of the four required variables (stockCount, price, lowStockThreshold, isStockCritical) with their specified initial values.
  • A for loop that is correctly structured to iterate exactly 5 times (e.g., for (int i = 0; i < 5; i++)).
  • Inside the loop, a switch statement that correctly handles case 0, case 1, case 2, case 4, and a default case, modifying the stockCount variable with the appropriate arithmetic operators (+ or -).
  • An if/else block placed after the switch statement but inside the loop.
  • This if/else block must use a comparison operator (<) to compare stockCount and lowStockThreshold and correctly assign true or false to the isStockCritical boolean variable in each iteration.

After the 5-day simulation, the final value of stockCount should be 53 and the final value of isStockCritical should be false.

java

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.