Lesson 6: Mastering Variables and Data Types

Hello, everyone!
Today, we’re diving deeper into variables. If you’ve already read our article Variables and Their Role in Java some of this might feel familiar. But repetition is the key to mastery, right?
Let’s get started!


What is a variable?

Imagine you’re making a shopping list:

  • Milk
  • Bread
  • Apples

Each item is like a variable. It has a name (e.g., “milk”) and a value (quantity or description). In programming, variables work in a similar way—they have a name and hold data.


Types of Variables in Java

In Java, there are two main types of variables:

  1. Primitive Variables
    These hold simple data, like numbers, characters, or true/false values.
  2. Reference Variables
    These store a reference (or address) to more complex objects, like text.
    For example, think of the phrase “Hello, World!” as an object. A reference variable stores the “location” of that text in memory.

Primitive Types: 8 “Boxes”

Integers

  1. byte: For small numbers, ranging from -128 to 127.
    Efficient for memory usage.
  2. short: A bit larger, from -32,768 to 32,767. Great for storing a year of birth, for example.
  3. int: The standard type for whole numbers (from -2 billion to 2 billion). Ideal for something like age.
  4. long: For very large numbers, such as the number of stars in a galaxy.

Floating-Point Numbers (Decimals)

  1. float (32 bits):
    • Stores single-precision decimal numbers.
    • Takes up less memory (4 bytes).
    • Suitable for values requiring lower precision (~6–7 digits).
    Example:
float pi = 3.14f; // The 'f' is mandatory for float literals

Why the ‘f’?
Java interprets decimal numbers as double by default, which requires more memory (8 bytes). Explicitly adding ‘f’ tells Java to treat it as a float.

  1. double (64 bits):
  • Stores double-precision decimal numbers.
  • Uses more memory (8 bytes).
  • Provides higher precision (~15–16 digits).

Example:

double precisePi = 3.141592653589793;

When to Use

  • Choose float when saving memory is crucial and ~7 digits of precision are enough.
  • Use double for higher precision or large numbers (default choice).

Comparison Example:

public class Main {
public static void main(String[] args) {
float floatNumber = 1.1234567f;
double doubleNumber = 1.123456789012345;

System.out.println("Float: " + floatNumber); // Rounds to 1.1234567
System.out.println("Double: " + doubleNumber); // Retains higher precision
}
}

Summary:

  • float: Less memory, lower precision.
  • double: More memory, higher precision.

  1. Characters
  • char: Stores a single character, like ‘A’, ‘@’, or even a space.
  1. Boolean Values
  • boolean: Only two values: true or false.
    Example:
    Is the person a student?
    • Answer: true (yes) or false (no).

Reference Types: Strings

Reference variables can be more complex. One of the most popular reference types is String (Reference Types in Java — Strings), which holds text.
Example:

String greeting = "Hello, World!";

Here:

  • greeting is the variable name.
  • "Hello, World!" is the value it holds.

Note: String is actually a class, and greeting is a variable of that class. We’ll explore this further in future lessons.


How to Declare Variables

Before using a variable, you must declare it. Follow these simple rules:

  1. Choose a clear name.
    • Variable names in Java are not limited in length, but it’s best to keep them descriptive yet concise.
    • Aim for names that clearly convey their purpose without being overly long.
    • ❌ Bad examples: a, b, c.
    • ✅ Good examples: age, price, isStudent.
    • ✅ Acceptable longer name: numberOfStudentsEnrolled (clear and precise, but not excessive).
  2. Start with a letter.
    Names can include letters, digits, underscores (_), and dollar signs ($).
    However, they cannot start with a digit.
  3. Avoid reserved words.
    You can’t use Java keywords like class or public as variable names.
  4. Remember: Case matters.
    Variable names Age and age are different.
  5. Pick the right type.
    Think about what data you’re storing: numbers, text, or a true/false value.

By following these rules, you’ll create variable names that are both valid and easy to understand in your code.


Examples of Variable Declarations

  • Whole number: int age = 30; // Age
  • Decimal number: double price = 9.99; // Price
  • Character: char initial = ‘A’; // First letter of a name
  • Boolean: boolean isHappy = true; // Are they happy?
  • String: String name = “Anna”; // Name

Summary

  • Variables are “boxes” for storing data.
  • Java has 8 primitive types for numbers, characters, and true/false values.
  • Reference variables, like String, store text.
  • To create a variable: choose a clear name, pick the right type, and follow naming rules.

Quick Task for You

Think about what kind of data you would store in variables for a project.
For instance, in an expense tracker app, you might need:

  • A variable for the user’s name.
  • A variable for the total amount spent.
  • A variable for the date of each expense.

Take a moment to write down some ideas on paper!

Leave a Reply