Java 21+: Variables, Data Types, and Operators for Beginners with Simple Programs and Output

Java 21+: Variables, Data Types, and Operators for Beginners with Simple Programs and Output


Learning Java starts with three pillars: variables, data types, and operators. This beginner-friendly guide explains each concept in simple language with Java 21+ in mind. You’ll see short, complete programs and outputs, learn the syntax step by step, avoid common mistakes, and build confidence for your next practice session.

What is a variable in Java?

Beginner-friendly visual of Java variables and data types with icons for primitives and references for beginners
How Java stores values: variables mapped to primitive types and references, explained visually.

A variable is a named storage location that holds a value while your program runs. In Java, every variable has a type (like int or String) and a name (like age or message). Java is statically typed, which means the compiler knows each variable’s type and checks it before running the program.

Why variables are used

  • To store input or intermediate results
  • To make programs readable (good names explain intent)
  • To control program flow (conditions based on variable values)

Basic syntax

  • Declaration: type name; (e.g., int count;)
  • Initialization: name = value; (e.g., count = 10;)
  • Combined: type name = value; (e.g., double price = 49.99;)
  • Local type inference with var (Java 10+): var city = "Jaipur"; The compiler infers the type from the initializer. It’s still statically typed.

How to declare and use variables in Java step by step

Code
class="cd-keyword cd-access">public class VariablesIntro {
    class="cd-keyword cd-access">public static void main(String[] args) {
        // Explicit types
        int age = 18;
        double price = 49.99;
        boolean passed = true;
        char grade = 'A';
        String name = "Riya";

        // Local type inference (Java 10+)
        var city = "Jaipur"; // inferred as String
        var score = 92;      // inferred as int

        // Update and use variables
        score = score + 5;

        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Grade: " + grade);
        System.out.println("Passed: " + passed);
        System.out.println("Price: " + price);
        System.out.println("City: " + city);
        System.out.println("Score: " + score);

        // ___CDPHSTR10___ limitations (these lines would not compile if uncommented)
        // var notSet;            // Error: ___CDPHSTR11___ requires an initializer
        // var nothing = null;    // Error: cannot infer type for local variable
    }
}
Output
Name: Riya
Age: 18
Grade: A
Passed: true
Price: 49.99
City: Jaipur
Score: 97

Variable scope and lifetime (beginner guide)

Scope is the region of code where a variable can be used. Lifetime is how long the variable exists during execution.

  • Local variables (inside methods/blocks): must be initialized before use; no default value.
  • Fields (variables inside a class, but outside methods): get default values (e.g., 0, 0.0, false, 'u0000', null).
  • Block scope: a variable declared inside { } is not visible outside that block.
Code
class="cd-keyword cd-access">public class ScopeDemo {
    int count; // instance field; default value is 0

    class="cd-keyword cd-access">public static void main(String[] args) {
        ScopeDemo demo = new ScopeDemo();
        System.out.println("Default field 'count': " + demo.count); // 0

        if (true) {
            int inside = 10;
            System.out.println("Inside block: " + inside);
        }
        // System.out.println(inside); // Error: cannot find symbol

        // Local variables must be initialized before use:
        // int notInitialized;
        // System.out.println(notInitialized); // Error: might not have been initialized
    }
}
Output
Default field 'count': 0
Inside block: 10

Variable lifecycle in Java (declare → initialize → use → update → out of scope)
1. Declare
int count;
Name + type

2. Initialize
count = 1;
Locals must be set before use

3. Use
System.out.println(count);
Read/print/value in expressions

4. Update
count++;
Reassign or mutate state

5. Out of scope
} // block ends
Local variable is no longer accessible

Java data types overview

Illustration of Java operators for beginners, grouping arithmetic, comparison, logical, assignment, unary and ternary as icon
See how Java operator categories connect and evaluate expressions at a glance.

Java (21+) includes two broad categories: primitive types and reference types.

Primitive types (8)

  • Integers: byte, short, int, long
  • Floating point: float, double
  • Character: char
  • Boolean: boolean

Use int for whole numbers by default; use long for very large integers. Use double for most real numbers. Use boolean for true/false logic, char for single Unicode characters.

Quick reference: Java primitive types for beginners (field defaults shown)
Type Size Range / Notes Default (field) Literal examples
byte 8-bit -128 to 127 0 (byte)120, 0b0110
short 16-bit -32768 to 32767 0 (short)20000, 0x7FFF
int 32-bit ~ -2.1B to 2.1B 0 123, 1_000_000, 0b1010
long 64-bit Very large integers 0L 9_000_000_000L, 0xFFL
float 32-bit Decimal (approximate) 0.0f 3.14F, 1e-3F
double 64-bit Decimal (approximate) 0.0d 3.14, 1e-9
char 16-bit Single Unicode character 'u0000' 'A', '₹', 'u0939'
boolean — (logical) Only true or false false true, false
Note: Default values apply to fields. Local variables must be initialized before use.

Reference types

Everything else is a reference type: String, arrays (int[]), classes, interfaces, records, and enums. Reference variables hold references that point to objects in memory.

Primitive vs reference types (what’s the difference?)

  • Primitives store actual values (e.g., 42).
  • References store the address of an object (e.g., a String object).
  • Equality: For objects, use .equals(...) to compare content; == compares references.
Code
class="cd-keyword cd-access">public class StringEqualityDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        String a = "hi";
        String b = new String("hi");
        System.out.println(a == b);        // compares references
        System.out.println(a.equals(b));   // compares content
    }
}
Output
false
true

Beginner guide to Java type casting

  • Widening (safe, automatic): small type to bigger type (e.g., int to double).
  • Narrowing (explicit, may lose data): bigger type to smaller type (e.g., double to int).
Code
class="cd-keyword cd-access">public class CastingDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        int items = 5;
        double avg = items; // widening (int -> double)
        System.out.println("avg = " + avg); // 5.0

        double gpaExact = 8.75;
        int gpaRoundedDown = (int) gpaExact; // narrowing, truncates
        System.out.println("gpaRoundedDown = " + gpaRoundedDown); // 8

        char letter = 'A';
        int code = letter; // char -> int (Unicode code point)
        System.out.println("code = " + code); // 65

        // Type mismatch example (would not compile if uncommented):
        // int x = 10.5; // Error: cannot convert from double to int
    }
}
Output
avg = 5.0
gpaRoundedDown = 8
code = 65

Java operators explained with simple programs and output

Operators perform actions on variables and values. Below are the most common groups you will use in beginner programs.

Arithmetic operators

  • +, -, *, /, %
  • Unary: ++, --

Integer division truncates toward 0. To get a decimal result, make at least one operand a floating-point number.

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

        // Avoid double/float for money; use BigDecimal for exact decimals
        System.out.println(0.1 + 0.2);  // 0.30000000000000004
        java.math.BigDecimal x = new java.math.BigDecimal("0.1");
        java.math.BigDecimal y = new java.math.BigDecimal("0.2");
        System.out.println(x.add(y));   // 0.3
    }
}
Output
2
2.5
0.30000000000000004
0.3

Relational and logical operators

  • Relational: <, <=, >, >=, ==, !=
  • Logical: && (AND), || (OR), ! (NOT)
  • Short-circuit: with && and ||, the right side may not run if not needed.
Code
class="cd-keyword cd-access">public class LogicalShortCircuitDemo {
    static boolean riskyDivide(int n) {
        System.out.println("Dividing 10 by " + n);
        return 10 / n > 1; // would throw if n == 0
    }

    class="cd-keyword cd-access">public static void main(String[] args) {
        int n = 0;
        boolean ok = (n != 0) && riskyDivide(n); // right side not evaluated
        System.out.println("ok = " + ok);

        boolean value = true || riskyDivide(2); // not evaluated due to short-circuit
        System.out.println("value = " + value);
    }
}
Output
ok = false
value = true

Bitwise and shift operators (integers)

  • Bitwise: &, |, ^, ~
  • Shifts: << (left), >> (arithmetic right), >>> (logical right)
Code
class="cd-keyword cd-access">public class BitwiseShiftDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        int p = 0b1111; // 15
        int q = 0b1010; // 10
        System.out.println(p & q); // 10
        System.out.println(p | q); // 15
        System.out.println(p ^ q); // 5

        int n = -8;
        System.out.println(n >> 1);   // -4 (arithmetic right shift)
        System.out.println(n >>> 1);  // 2147483644 (logical right shift)
    }
}
Output
10
15
5
-4
2147483644

Conditional (ternary) operator

The conditional operator ? : picks one of two values based on a boolean expression.

Code
class="cd-keyword cd-access">public class ConditionalOperatorDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        int marks = 72;
        String result = (marks >= 33) ? "Pass" : "Fail";
        System.out.println(result);
    }
}
Output
Pass

Modern Java pattern variables (Java 21)

Java 21 finalizes pattern matching for switch. A pattern can both test a type and bind a pattern variable if it matches. This is part of “Java 21 basics for students” you should know.

Code
class="cd-keyword cd-access">public class PatternSwitchDemo {
    static void printInfo(Object o) {
        switch (o) {
            case Integer i -> System.out.println("Twice: " + (i * 2));
            case String s -> System.out.println("Length: " + s.length());
            case null -> System.out.println("Null value");
            default -> System.out.println("Unknown type: " + o.getClass().getSimpleName());
        }
    }

    class="cd-keyword cd-access">public static void main(String[] args) {
        printInfo(123);
        printInfo("Java");
        printInfo(3.14);
        printInfo(null);
    }
}
Output
Twice: 246
Length: 4
Unknown type: Double
Null value

Common beginner mistakes and how to fix them

  • Using == for strings: == checks references, not content. Use .equals().
  • Forgetting integer division: 5/2 is 2, not 2.5. Use 5/2.0 or cast: (double)5/2.
  • Type mismatch errors: Assigning a double to an int without a cast causes a compile-time error.
  • Not initializing local variables: Always assign a value before using local variables.
  • Misusing var: It’s only for local variables with an initializer; not for fields, parameters, or null-only initializers.
  • Using float/double for currency: Floating-point rounding can surprise you. For money, prefer BigDecimal.

Build-and-run checklist: Java variables, data types and operators for beginners
  • Pick types wisely: int (whole), double (decimal), boolean (true/false), String (text).
  • Initialize local variables before use; fields get defaults, locals do not.
  • Use literal suffixes when needed: L for long, F for float (e.g., 10L, 3.5F).
  • Compare strings with .equals(), not ==.
  • Force decimal division when needed: 5/2.0 or (double)a / b.
  • Money math: prefer BigDecimal with string constructors.
  • Using var? It must be a local variable with an initializer; not for fields or null-only.
  • Watch overflow: promote to long before large multiplications (e.g., 100000L * 100000).
  • Use parentheses to clarify complex boolean expressions.
  • Print values while learning: System.out.println("x = " + x);

Practice exercises using Java data types and operators for students

  1. Temperature converter
    • Read a Celsius value in a variable, convert to Fahrenheit using F = C * 9/5 + 32. Print both.
    • Try with int and with double; observe the difference.
  2. Marks grading
    • Use the conditional operator to print "Pass"/"Fail" from a marks variable.
    • Extend with ranges: A for 90+, B for 80+, etc.
  3. Bitwise practice
    • Given int mask = 0b0101; and int value = 0b1100;, print results of &, |, and ^.
    • Shift value left and right, and print results.
  4. Type casting challenge
    • Store 3.99 in a double, cast it to int, and explain the result.
    • Store '₹' in char and print its code point as int.

FAQ: Java variables, data types and operators for beginners

What is a variable in Java and how do I declare one?

A variable is a named container for a value. Declare it with type name = value; For example: int count = 5;. In Java 10+, you can use var for local variables with an initializer: var count = 5;.

Which data types does Java 21 include and when should I use them?

Java has 8 primitives: byte, short, int, long, float, double, char, boolean; plus reference types like String, arrays, classes, records, and enums. Start with int for whole numbers, double for real numbers, and boolean for true/false.

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

Primitives hold raw values (e.g., 10), while reference types hold addresses to objects (e.g., String). For objects, compare content with .equals() instead of ==.

How do Java arithmetic and logical operators work with examples?

Arithmetic operators like +, -, *, /, and % do math. Logical operators &&, ||, and ! combine booleans. For instance, 5/2 yields 2 (integer division), while 5/2.0 yields 2.5.

Why do I get type mismatch errors and how can I fix them in Java?

They happen when you assign a value of one type to a variable of another incompatible type. Fix by matching types or adding an explicit cast when safe (e.g., int x = (int) 10.5;), but remember narrowing casts can lose data.

Notes for learners on Java 21+

  • Local variable type inference (var) keeps Java statically typed; it only infers types for local variables with initializers.
  • Pattern matching for switch is finalized in Java 21 and introduces pattern variables safely.
  • String Templates were a preview in Java 21/22 but were withdrawn in Java 23, so do not rely on them in production learning paths.
  • These fundamentals are stable from Java 21 to the current releases (Java 25 LTS and beyond).

Keep learning

Continue with more beginner-friendly lessons and examples in our Java track: CodDesire Java Tutorials.

Sources / Further reading

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted