Java Variables, Data Types and Operators for Beginners (Java 21 LTS)

Java Variables, Data Types and Operators for Beginners (Java 21 LTS)


Welcome to a beginner-friendly guide to Java 21 variables, data types and operators for beginners. If you are a student or new to programming, this page will help you understand what variables are, how Java’s data types work (primitive vs reference), and how to use common operators correctly. We use clear examples you can run and include small “gotchas” to save your time.

What is a variable and why do we use it?

Java 21 variables and data types for beginners shown as primitives on stack and objects on heap
Primitives vs reference types in Java 21 with a clear stack–heap visual.

A variable stores a value in memory so your program can use or change it later. Java is statically typed, which means every variable has a declared type that the compiler checks. This helps prevent many runtime errors and makes your code easier to understand.

Basic syntax

  • Declare: type name;
  • Declare and initialize: type name = value;
Code
class="cd-keyword cd-access">public class Basics {
    class="cd-keyword cd-access">public static void main(String[] args) {
        int age = 18;
        double price = 499.99;
        boolean isStudent = true;
        char grade = 'A';

        System.out.println("age = " + age);
        System.out.println("price = " + price);
        System.out.println("isStudent = " + isStudent);
        System.out.println("grade = " + grade);
    }
}
Output
age = 18
price = 499.99
isStudent = true
grade = A

Kinds of variables and scope

  • Local variables: Declared inside methods/blocks. Must be initialized before use; no default value.
  • Instance variables (fields): Belong to an object; get default values (for example, 0 for numbers, false for boolean, null for references).
  • Class variables (static fields): Belong to the class; one copy shared by all objects.
Code
class="cd-keyword cd-access">public class ScopeDemo {
    static String schoolName = "CodDesire Academy"; // class (static) variable
    String studentName;                              // instance variable

    class="cd-keyword cd-access">public ScopeDemo(String name) {
        this.studentName = name;
    }

    class="cd-keyword cd-access">public void show() {
        int year = 2026; // local variable - must be initialized
        System.out.println(studentName + " - " + schoolName + " - " + year);
    }

    class="cd-keyword cd-access">public static void main(String[] args) {
        ScopeDemo s = new ScopeDemo("Anaya");
        s.show();
    }
}

Java variable naming rules and best practices for students

  • Use letters, digits, underscores, and $; cannot start with a digit.
  • Use camelCase for variables: totalMarks, maxSpeed.
  • Be descriptive: studentCount is better than sc.
  • Avoid single-letter names (except in short loops).
  • Note: In Java 21, _ (underscore) is not allowed as an identifier. It is reserved and used for unnamed variables/patterns only in preview mode.

Local variable type inference with var

Java 21 lets you use var for local variables with an initializer. The compiler infers the type. This does not make Java dynamically typed—types are still checked at compile time.

  • Allowed: local variables with initializers, enhanced for-loops, classic for loop counters, try-with-resources, lambda parameters.
  • Not allowed: fields, method parameters (except lambda parameters).
Code
class="cd-keyword cd-access">public class VarDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        var count = 10;          // inferred as int
        var message = "Hello";   // inferred as String

        for (var i = 0; i < 3; i++) {
            System.out.print(i + " ");
        }
        System.out.println();

        // var must have an initializer:
        // var x; // compile error
    }
}
Output
0 1 2

Java 21 data types: primitive vs reference

Java 21 operators for beginners visualized: arithmetic, comparison, logical, assignment, bitwise, unary
Operator categories at a glance—from arithmetic to bitwise—made beginner-friendly.

Java has two families of types: primitive types and reference types.

Primitive data types in Java 21

  • byte: 8-bit signed integer
  • short: 16-bit signed integer
  • int: 32-bit signed integer (most common for whole numbers)
  • long: 64-bit signed integer (use L suffix, e.g., 10L)
  • float: 32-bit IEEE 754 floating point (use F suffix)
  • double: 64-bit IEEE 754 floating point (default for decimals)
  • char: 16-bit unsigned UTF‑16 code unit (use single quotes: 'A', 'u0986')
  • boolean: true or false (storage size is not defined by the language)

Quick reference: Primitive types vs wrappers (Java 21)

Primitive Example literal Wrapper class Field default Typical use
byte 127 Byte 0 Small integers; I/O buffers
short 10_000 Short 0 Memory‑sensitive integer arrays
int 1_000_000 Integer 0 Counts, indices (most common)
long 9_000_000_000L Long 0L Large counters, timestamps
float 3.14F Float 0.0f Large arrays of approximate decimals
double 2.71828 Double 0.0d Default for fractional numbers
char ‘A’, ‘u0986’ Character ‘u0000’ Single UTF‑16 code unit
boolean true, false Boolean false Flags, conditions
Field defaults shown; local variables have no default and must be initialized.

Difference between int, double and boolean in Java 21

int holds whole numbers, double holds decimals, and boolean is for logical truth values. Integer division truncates the result; double division keeps the fraction.

Code
class="cd-keyword cd-access">public class TypesDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        int a = 5, b = 2;
        System.out.println("int division: " + (a / b)); // 2

        double c = 5.0, d = 2.0;
        System.out.println("double division: " + (c / d)); // 2.5

        boolean passed = (a > b);
        System.out.println("passed = " + passed);
    }
}
Output
int division: 2
double division: 2.5
passed = true

Reference types and wrapper classes

Reference types include classes (e.g., String), arrays, interfaces, records, and enums. For each primitive, Java provides a wrapper class (e.g., Integer for int, Double for double). Wrappers are necessary for collections and generics. Java automatically converts between primitives and wrappers: boxing (primitive to wrapper) and unboxing (wrapper to primitive).

Code
class="cd-keyword cd-access">public class BoxingDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        Integer n = 7;  // boxing
        int m = n;      // unboxing
        System.out.println("n + m = " + (n + m));

        Integer maybeNull = null;
        // int x = maybeNull; // would throw NullPointerException at runtime
        System.out.println("maybeNull = " + maybeNull);
    }
}

Operators in Java 21

Operators let you manipulate values. Categories include unary, arithmetic, shift, relational (including instanceof), equality, bitwise/logical, conditional (?:), and assignment. Operator precedence affects how expressions are evaluated; use parentheses to make the intent clear.

Arithmetic operators and numeric promotion

Arithmetic: +, -, *, /, %. Unary: +, -, ++, --. In expressions, byte, short, and char are promoted to int. This can surprise beginners:

Code
class="cd-keyword cd-access">public class PromotionDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        byte x = 10, y = 20;
        // byte z = x + y; // compile error: result is int
        byte z = (byte) (x + y); // explicit cast
        System.out.println("z = " + z);

        int sum = x + y; // OK because promoted to int
        System.out.println("sum = " + sum);
    }
}

Relational, equality, and instanceof (with pattern matching)

  • Relational: <, <=, >, >=
  • Equality: ==, != (for primitives: value comparison; for references: same object vs not)
  • Pattern matching instanceof lets you test and cast in one step.
Code
class="cd-keyword cd-access">public class InstanceofDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        Object obj = "Java";
        if (obj instanceof String s && s.length() >= 4) {
            System.out.println("String length = " + s.length());
        }
    }
}

Logical and bitwise operators

  • Logical (short-circuit): &&, ||, !
  • Bitwise: &, |, ^, ~; Shifts: <<, >>, >>>
Code
class="cd-keyword cd-access">public class LogicalDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        int a = 3, b = 0;
        if (b != 0 && (a / b) > 1) { // right side not evaluated if b == 0
            System.out.println("won&#039;t divide by zero");
        }

        int mask = 0b0101;
        int flags = 0b0011;
        int result = flags & mask; // bitwise AND
        System.out.println(Integer.toBinaryString(result)); // ___CDPHSTR0___ (binary)
    }
}

Assignment, compound assignment, and string concatenation

Use = to assign. Compound assignments like +=, -=, *= update in place. When one operand is a String, + concatenates.

Code
class="cd-keyword cd-access">public class ConcatDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        int n = 2;
        n += 3; // n is 5
        String s = "Score: " + n; // concatenation
        System.out.println(s);
    }
}

Conditional operator and operator precedence

The conditional operator ?: is a compact if-else. Precedence determines evaluation order—multiplication/division bind tighter than addition/subtraction. Add parentheses for clarity.

Code
class="cd-keyword cd-access">public class ConditionalDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        int age = 17;
        String label = (age >= 18) ? "adult" : "minor";
        System.out.println(label);

        System.out.println(1 + 2 * 3);     // 7
        System.out.println((1 + 2) * 3);   // 9
    }
}

Pattern matching for switch (Java 21)

Java 21 finalizes pattern matching for switch and record patterns. You can switch on Object and match by type, with optional guards using when.

Code
record Point(int x, int y) {}

class="cd-keyword cd-access">public class SwitchPatternDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        Object obj = new Point(2, 2);

        String desc = switch (obj) {
            case Integer i -> "int " + i;
            case String s when s.length() > 3 -> "long string";
            case Point(int x, int y) when x == y -> "diagonal point";
            case Point(int x, int y) -> "point " + x + "," + y;
            default -> "something else";
        };

        System.out.println(desc);
    }
}
Output
diagonal point

Note: Java 21 also offers preview “unnamed variables and patterns” using _. They require --enable-preview and may change; most beginners can safely ignore them.

How to choose the right data type

  • Counts, indices: int (or long if values can exceed ~2.1 billion).
  • Money/precise decimal: prefer BigDecimal (reference type); avoid float/double for exact currency math.
  • True/false flags: boolean.
  • Single UTF‑16 code unit: char; for full Unicode text use String.
  • Collections and generics: use wrapper types like Integer, Double, Boolean.
  • If unsure between float and double, choose double for better precision.

Beginner-friendly data type picker (flow)

What value do you need to store?
Money with exact decimals? Use BigDecimal (avoid float/double for currency).
Fractional numbers (measurements)? Use double (float only if memory‑sensitive).
Whole numbers (counts/indices)? Use int (or long for very large ranges).
True/false? Use boolean.
Text? Use String (use char only for a single UTF‑16 code unit).
Need to store primitives in collections/generics? Use wrappers (Integer, Double, Boolean, Character).

Common mistakes and how to fix them

  • Using variables before initialization (locals): always assign a value first.
  • Expecting byte/short/char arithmetic to stay in their type: Java promotes them to int; cast or use int.
  • Comparing String values with ==: use .equals() for content comparison.
  • Forgetting integer vs floating-point division: cast or use double to keep decimals.
  • Unboxing a null wrapper (e.g., Integer): check for null to avoid NullPointerException.
  • Overusing var: keep code readable; choose explicit types when inference is unclear.
  • Relying on default values for locals: only fields get defaults; locals must be initialized.
Hands‑on checklist: Java 21 variables, data types and operators for beginners
  • Initialize every local variable before first use.
  • Pick types by intent: counts → int; large counts → long; fractions → double; money → BigDecimal; flags → boolean.
  • Use .equals() for String content; == only checks if the same object.
  • Add L for long and F for float literals when needed (e.g., 10L, 3.14F).
  • Remember numeric promotion: byte/short/char → int in expressions; cast intentionally.
  • Prevent integer division truncation by using double or casting (e.g., (double) a / b).
  • Use var only when the initializer makes the type obvious.
  • Avoid unboxing null (e.g., Integerint); check for null first.
  • Clarify complex expressions with parentheses to avoid precedence mistakes.

FAQ: People also ask

What is a variable in Java for beginners?

A variable is a named storage location with a specific type. You declare the type once, and the compiler ensures you use it correctly.

What are the primitive data types in Java 21?

byte, short, int, long, float, double, char, boolean.

How do arithmetic and logical operators work in Java?

Arithmetic operators perform math on numbers; logical operators combine boolean expressions with short-circuit behavior (&&, ||). Remember operator precedence and use parentheses to make intentions clear.

What is the difference between primitive and reference types in Java?

Primitives store simple values directly (like numbers and booleans). Reference types store references to objects (like String, arrays, and custom classes). Wrappers (e.g., Integer) are reference types that correspond to primitives.

How do I choose the right data type for a Java variable?

Pick the smallest type that fits your needs: use int for counts, double for fractional numbers, boolean for flags, and wrapper types for collections. Use BigDecimal for precise money calculations.

Practice next steps

  • Write a program that reads two numbers, prints their sum, difference, product, and quotient as both int and double.
  • Create a class with instance and static fields, and practice accessing them.
  • Try a switch with pattern matching over Object values and add a guarded pattern with when.

Continue learning in our Java 21 basics for students series on CodDesire: Explore more Java tutorials.

Sources / Further reading

By practicing these foundations—what are variables in Java 21 with examples, Java primitive vs reference types for beginners, and how to use arithmetic and logical operators in Java—you will build the confidence to write clear, correct code. Keep going!

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted