Article start
Java Programming: From Zero to Enterprise
1. Java Fundamentals

2. Data Types & Variables

Learn the difference between primitives and objects, and how to declare them.

February 22, 2026·135

[!NOTE] Variables are named containers holding data in the computer's memory. In Java, every container is strictly labeled with the exact type of data it's allowed to hold.

Statically Typed vs Dynamically Typed

If you are coming from Python or JavaScript, you are used to Dynamic Typing. You can create a variable x = 5 and later change your mind and say x = "Hello".

Java is Statically Typed. When you create a variable, you must explicitly declare its type upfront. Once declared, that variable can never hold a different type of data. If you try to put text inside an integer variable, the code simply will not compile.

Why go through the trouble?

Static typing catches 90% of your bugs at compile-time before the application even starts. In JavaScript, you might not realize an error occurred until a user clicks a button and the app crashes in production. By forcing you to declare types, Java acts as your personal safety net.

Primitive Data Types

Java has 8 foundational "Primitive" types. These are raw values, not objects. They are extremely fast and efficient, living directly on the call stack execution memory.

  1. Integral Numbers

TypeSizeRangeExample Use Case
byte8-bit-128 to 127Saving memory in enormous 2D arrays.
short16-bit-32,768 to 32,767Rarely used in modern Java.
int32-bit~ ±2 BillionDefault choice for whole numbers.
long64-bit~ ±9 QuintillionExtremely large counts (e.g., global population). Append 'L'.
int currentScore = 1500;
long viewCount = 8000000000L;

  1. Floating-Point Numbers

TypeSizePrecisionExample Use Case
float32-bit~7 Decimal DigitsSaving memory for 3D graphics. Append 'f'.
double64-bit~15 Decimal DigitsDefault choice for decimals.
double bankBalance = 1542.89;
float pi = 3.14159f;

  1. Characters & Booleans

  • char: A single 16-bit Unicode character. Must be surrounded by single quotes.
  • boolean: Simply true or false.
char grade = 'A'; // Single quotes!
boolean isGameOver = false;

Non-Primitive Data Types (Objects)

Primitives just hold values. Non-primitive types (also called Reference Types) map to fully featured Objects built in the Heap memory. They have methods you can call on them.

The most famous is String. A String is a sequence of characters, enclosed in double quotes.

String playerUsername = "DragonSlayer99";
int usernameLength = playerUsername.length(); // Calling a method on the Object
String upperCaseName = playerUsername.toUpperCase();

Strings are fundamentally different from primitives. int starts with a lowercase letter because it's baked into the language. String starts with a capital letter because it is actually a Class definition located in the java.lang package!

[!IMPORTANT] Variable Naming Conventions: In Java, variables should use camelCase. They should start with a lowercase letter, and every subsequent word should be capitalized (e.g., myFirstVariable).

Choosing the Right Type in Real Code

Types are not only syntax. They describe what kind of value your program expects. Good type choices make code easier to read, safer to change, and easier for the compiler to protect.

For ordinary whole numbers, use int. For very large counts, use long. For decimal measurements, use double. For money, do not use double in serious applications because floating-point values can introduce rounding surprises. Use BigDecimal when exact decimal precision matters.

Better Variable Names

// Weak: the type is visible, but the meaning is not clear
int x = 18;
double y = 499.99;

// Better: the variable name explains the business meaning
int minimumAge = 18;
double cartTotal = 499.99;

Primitive Defaults vs Local Variables

Fields get default values, but local variables inside methods must be assigned before use. This rule prevents accidental reads from uninitialized local data.

class ScoreCard {
    int score; // field default is 0

    void printScore() {
        int bonus;
        // System.out.println(bonus); // compile error: bonus not initialized
        bonus = 10;
        System.out.println(score + bonus);
    }
}

Common Mistakes

  • Using String for numbers that must be calculated later.
  • Forgetting the L suffix on very large long literals.
  • Comparing decimal values as if they are always exact.
  • Naming variables by type only, such as str, num, or data.

Mini Practice

Create variables for a product name, quantity, price, in-stock flag, and rating. Print a one-line invoice summary. Then change the quantity type from int to String and notice which calculations stop compiling.

Practice Lab: Build a Bill Summary

Create variables for a small shopping bill and print a clean summary.

  1. Create variables for product name, quantity, price per item, tax percentage, and whether the item is in stock.
  2. Calculate subtotal and final total.
  3. Print the result in one readable sentence.
  4. Try changing quantity from int to String and observe what breaks.

Goal: Understand why choosing correct types matters before calculations begin.

Revision Checkpoint

  • Static typing: Java checks variable types at compile time.
  • Primitive types: Store raw values such as int, double, boolean, and char.
  • Reference types: Point to objects such as String, arrays, and custom classes.
  • Default integer: Use int for ordinary whole numbers.
  • Money warning: Prefer exact decimal handling such as BigDecimal for serious money calculations.

Before the quiz: Decide whether each value should be int, long, double, boolean, char, or String.