Java Variables and Operators for Beginners: Data Types, var, and Scanner Input

Java Variables and Operators for Beginners: Data Types, var, and Scanner Input


Learning Java starts with two essentials: variables to store data and operators to compute with that data. This beginner-friendly guide walks you through Java variables and operators for beginners, including data types, the var keyword for local type inference, and how to read user input using Scanner. All examples use modern Java (Java 25 LTS) and focus on clear, practical steps you can follow today.

Java variables introduction

Java variables and operators for beginners: data types overview with var type inference visualization
Data types at a glance with var inferencing for new Java learners

A variable is a named storage location in memory. You declare a variable with a type, and Java guarantees that only compatible values can be stored in it. This strong typing helps you catch many mistakes at compile time—great for beginners.

Declaring and initializing variables

Common syntax: Type name = value;. Local variables must be initialized before use. Fields (variables declared inside a class but outside methods) receive default values, but local variables do not.

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

        // Reference types
        String name = "Riya";
        int[] scores = {90, 85, 92};

        System.out.println("Age: " + age);
        System.out.println("Price: " + price);
        System.out.println("Grade: " + grade);
        System.out.println("Passed: " + passed);
        System.out.println("Name: " + name);
        System.out.println("First score: " + scores[0]);

        // Note: local variables must be initialized before use
        // int x; System.out.println(x); // Compile-time error: x not initialized
    }
}
Output
Age: 18
Price: 19.99
Grade: A
Passed: true
Name: Riya
First score: 90

Primitive and reference types (quick guide)

Java has 8 primitive data types: byte, short, int, long, float, double, boolean, and char.

  • Whole numbers: byte, short, int, long
  • Decimals: float, double (use double for most general decimals; use BigDecimal for money)
  • Booleans: boolean (true/false)
  • Characters: char (single quotes, e.g., ‘A’)

Everything else is a reference type—for example, String, arrays, and your own classes. String is not a primitive; it’s a reference type.

Primitive vs Reference types — beginner comparison

Aspect Primitive types Reference types
What is stored The value itself A reference to an object (or null)
Examples int, double, boolean, char String, arrays, List<T>, your classes
Defaults (for fields) 0 / 0.0 / false / ‘u0000’ null
Equality == compares values == compares references; use equals() for content
Immutability Values cannot change “inside” the variable type Object can be mutable or immutable depending on class
Common tips Use int for general integers, double for general decimals Use String for text, collections for groups, custom classes for models

Numeric literals and readability

Java supports decimal, hex (prefix 0x), and binary (prefix 0b) literals. You can use underscores for readability. For monetary calculations, prefer BigDecimal for precise decimal arithmetic.

Code
class="cd-package">import java.math.BigDecimal;

class="cd-keyword cd-access">public class NumericLiteralsDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        int decimal = 42;
        int hex = 0xFF;         // 255
        int binary = 0b1010;    // 10
        long big = 1_000_000_000L;
        double pi = 3.141_592_653_589;

        BigDecimal price = new BigDecimal("19.95"); // exact decimal value

        System.out.println(decimal + ", " + hex + ", " + binary);
        System.out.println("big=" + big + ", pi=" + pi);
        System.out.println("price=" + price);
    }
}
Output
42, 255, 10
big=1000000000, pi=3.141592653589
price=19.95

Java data types for beginners: primitive vs reference

Java variables and operators for beginners: Scanner input flowing into int, double, and string variables with operators
From Scanner input to results using arithmetic, comparison, and logical operators

As a beginner guide to Java primitive and reference types, remember:

  • Pick the smallest suitable type. For general integers, use int. For decimals, use double unless you need exact decimal precision (then BigDecimal).
  • Local variables don’t have default values; you must assign before use. Fields do have defaults (e.g., 0 for numbers, false for boolean, null for references).
  • Strings are immutable reference types; operations like concatenation create new strings.

Java var keyword explained

Since Java 10, you can use var for local variable type inference. The compiler infers the static type from the initializer. Java stays statically typed: the type is decided at compile time and doesn’t change.

Syntax and examples

Code
class="cd-package">import java.util.ArrayList;
class="cd-package">import java.util.function.BiFunction;

class="cd-keyword cd-access">public class VarDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        var message = "Hello";           // inferred as String
        var count = 10;                  // inferred as int
        var list = new ArrayList<String>(); // inferred as ArrayList<String>

        list.add("alpha");
        // message = 42; // Compile-time error: incompatible types

        // Using var in lambda parameters (Java 11+)
        BiFunction<Integer, Integer, Integer> add = (var x, var y) -> x + y;
        System.out.println(message + " x " + count);
        System.out.println("Sum via lambda: " + add.apply(2, 3));
    }
}
Output
Hello x 10
Sum via lambda: 5

Rules and common mistakes

  • Only for local variables and lambda parameters. Not for fields or regular method parameters.
  • Must have an initializer: var x = 5; works; var x; does not.
  • Cannot be initialized with null because type cannot be inferred from null alone.
  • var is a reserved type name, not a full keyword; it works in type positions, and the inferred type remains fixed.
  • For lambdas, if one parameter uses var, all must use var.
Code
class="cd-keyword cd-access">public class VarGotchas {
    // var field = 10;         // Compile-time error: var not allowed for fields

    static void greet(/* var name */) { // Compile-time error: not for method params
        // ...
    }

    class="cd-keyword cd-access">public static void main(String[] args) {
        // var x;              // Error: needs initializer
        // var y = null;       // Error: cannot infer type from null
        var z = 5;             // OK: inferred as int
        System.out.println(z);
    }
}

When to use var

  • Use it when the initializer makes the type obvious (e.g., var map = new HashMap<String, Integer>();).
  • Avoid when it hurts readability (e.g., complex APIs where explicit types aid understanding).

Java operators made easy

Operators let you compute values and control logic. Categories you’ll use daily: arithmetic, assignment, comparison, logical, bitwise/shift, and the ternary operator. Remember operator precedence: multiplication/division before addition/subtraction, and string concatenation with +.

Arithmetic and assignment

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

        System.out.println("a / b = " + (a / b)); // 3 (integer division!)
        System.out.println("a % b = " + (a % b)); // 1

        double da = 7, db = 2;
        System.out.println("da / db = " + (da / db)); // 3.5

        int x = 10;
        x += 5;   // 15
        x++;      // 16
        System.out.println("x = " + x);
    }
}

Comparison and logical (with short-circuit)

Code
class="cd-keyword cd-access">public class LogicDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        int a = 4, b = 0;

        boolean ok1 = a > 3;          // true
        boolean ok2 = a == b;         // false
        boolean ok3 = a != b && a > 0; // true (both sides true)

        // Short-circuit: right side only evaluated if needed
        boolean safe = (b != 0) && ((a / b) > 1); // right side NOT evaluated because b != 0 is false
        System.out.println(ok1 + ", " + ok2 + ", " + ok3 + ", safe=" + safe);
    }
}

String concatenation and precedence

+ concatenates strings. Use parentheses to control order.

Code
class="cd-keyword cd-access">public class ConcatDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        int a = 2, b = 3;
        System.out.println("Sum=" + a + b);       // ___CDPHSTR1___
        System.out.println("Sum=" + (a + b));     // ___CDPHSTR3___
    }
}

Conditional (ternary) operator

Code
class="cd-keyword cd-access">public class TernaryDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        int n = 7;
        String parity = (n % 2 == 0) ? "even" : "odd";
        System.out.println("n is " + parity);
    }
}

Bitwise and shift (quick view)

Code
class="cd-keyword cd-access">public class BitwiseDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        int flags = 0b0010;
        int mask  = 0b0100;
        int set   = flags | mask;     // 0b0110
        int both  = flags & mask;     // 0b0000
        int shift = mask << 1;        // 0b1000

        System.out.println(Integer.toBinaryString(set));
        System.out.println(Integer.toBinaryString(both));
        System.out.println(Integer.toBinaryString(shift));
    }
}
Output
110
0
1000

Modern pattern matching: instanceof (beginner-friendly upgrade)

Pattern matching reduces boilerplate casting when checking types.

Code
class="cd-keyword cd-access">public class InstanceofDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        Object obj = "hello";
        if (obj instanceof String s) { // Java 16+
            System.out.println(s.toUpperCase());
        } else {
            System.out.println("Not a String");
        }
    }
}
Output
HELLO

Java 21 also finalized pattern matching for switch, and Java 25 previews primitive patterns. These features clean up type checks, but you can master them later once you’re comfortable with basics.

Java Scanner input tutorial

The Scanner class is a simple way to read input from the console or files. By default, it reads tokens separated by whitespace. A classic beginner pitfall is mixing nextInt() with nextLine() without consuming the end-of-line.

Read integers, doubles, and lines (with newline handling)

Code
class="cd-package">import java.util.Scanner;

class="cd-keyword cd-access">public class ScannerDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); // Do not close early if you need more input later

        System.out.print("Enter age (int): ");
        int age = sc.nextInt();

        // Consume the end-of-line left by nextInt()
        sc.nextLine();

        System.out.print("Enter full name (line): ");
        String name = sc.nextLine();

        System.out.print("Enter price (double): ");
        double price = sc.nextDouble();

        System.out.println("You entered: " + name + ", age=" + age + ", price=" + price);
        
        // Close at the very end of the program if no more input is needed:
        sc.close();
    }
}

Alternative: read a line and parse

Another safe pattern is reading the whole line and parsing it yourself. This avoids newline issues entirely.

Code
class="cd-package">import java.util.Scanner;

class="cd-keyword cd-access">public class ScannerParseDemo {
    class="cd-keyword cd-access">public static void main(String[] args) {
        try (Scanner sc = new Scanner(System.in)) { // OK to close at end
            System.out.print("Enter age: ");
            int age = Integer.parseInt(sc.nextLine().trim());

            System.out.print("Enter price: ");
            double price = Double.parseDouble(sc.nextLine().trim());

            System.out.println("Age=" + age + ", Price=" + price);
        }
    }
}

Reading from a file with try-with-resources

Code
class="cd-package">import java.nio.file.Path;
class="cd-package">import java.util.Scanner;

class="cd-keyword cd-access">public class FileScannerDemo {
    class="cd-keyword cd-access">public static void main(String[] args) throws Exception {
        Path file = Path.of("numbers.txt");
        int sum = 0;
        try (Scanner sc = new Scanner(file)) {
            while (sc.hasNextInt()) {
                sum += sc.nextInt();
            }
        }
        System.out.println("Sum = " + sum);
    }
}
  • Don’t close a Scanner that wraps System.in until your program is done with all console input.
  • Understand tokenization: next(), nextInt(), nextDouble() read the next token; nextLine() reads the rest of the line.

Scanner input flow — two safe patterns

Choose a pattern to avoid newline pitfalls
A) Token-by-token + consume newline
1) int age = sc.nextInt();
↓ consume EOL
2) sc.nextLine();
↓ read text
3) String name = sc.nextLine();
Use when mixing numbers and full-line text in one session.

B) Read line then parse numbers
1) String s = sc.nextLine();
↓ parse
2) int n = Integer.parseInt(s.trim());
Avoids newline issues entirely; great for beginners.

Tip: Close Scanner(System.in) only when all console input is finished, or use try-with-resources at program end.

Practice: put it all together

This mini-program reads two numbers, uses operators to compute results, and demonstrates string concatenation and a ternary check.

Code
class="cd-package">import java.util.Scanner;

class="cd-keyword cd-access">public class MiniCalculator {
    class="cd-keyword cd-access">public static void main(String[] args) {
        try (Scanner sc = new Scanner(System.in)) {
            System.out.print("Enter first integer: ");
            int a = Integer.parseInt(sc.nextLine().trim());
            System.out.print("Enter second integer: ");
            int b = Integer.parseInt(sc.nextLine().trim());

            int sum = a + b;
            int diff = a - b;
            int prod = a * b;
            String quotient = (b != 0) ? String.valueOf(a / b) : "undefined";
            String parity = (sum % 2 == 0) ? "even" : "odd";

            System.out.println("a=" + a + ", b=" + b);
            System.out.println("Sum=" + sum + " (" + parity + ")");
            System.out.println("Difference=" + diff);
            System.out.println("Product=" + prod);
            System.out.println("Quotient=" + quotient);
            System.out.println("As text: " + "Sum=" + sum); // String concatenation
        }
    }
}

Beginner checklist: Java variables and operators for beginners

  • Declare with an explicit type or use var only when the initializer makes the type obvious.
  • Local variables must be initialized before use; fields get defaults (numbers 0, boolean false, references null).
  • Use int for general integers, double for general decimals; use BigDecimal for money.
  • With var, do not write var x; or var y = null; — both are invalid.
  • Integer division truncates. For 3.5, use 7.0 / 2 or cast: (double) a / b.
  • String concatenation uses +; add parentheses to control order: "Sum=" + (a + b).
  • Use short-circuit logic to avoid errors: (b != 0) && (a / b > 1).
  • When mixing nextInt() and nextLine(), consume the leftover newline once with sc.nextLine().
  • Don’t close Scanner(System.in) until all input is done; OK to use try-with-resources at the end of main.
  • Compare object content with equals() (e.g., str.equals("hi")), not ==.

FAQ: Java variables and operators for beginners

What are variables in Java and how do I declare them?

Variables are named storage locations with a fixed type. Declare them as Type name = value; For example: int count = 5; Local variables must be initialized before you use them.

What are the primitive data types in Java for beginners?

byte, short, int, long, float, double, boolean, char. Everything else (e.g., String, arrays, classes) is a reference type.

When should I use the var keyword in Java?

Use var for local variables when the initializer makes the type obvious and code stays readable, e.g., var list = new ArrayList<String>(); Don’t use it for fields or method parameters, and you must provide an initializer that’s not null.

How do I read user input in Java using Scanner?

Create Scanner sc = new Scanner(System.in); Use nextInt(), nextDouble(), next(), or nextLine() as needed. If you call nextInt() and then nextLine(), consume the leftover newline first by calling sc.nextLine() once.

What are the basic arithmetic and comparison operators in Java?

Arithmetic: + - * / %; assignment variants like +=, ++. Comparison: == != > < >= <=. Logical: && and || (short-circuit), !. Use parentheses to clarify precedence, especially with string concatenation.

Next steps

Practice by writing small programs that declare variables, compute with operators, and read input. Then explore more tutorials in our Java section: CodDesire Java Tutorials.

Sources / Further reading

With these fundamentals—how to declare variables in Java with examples, beginner-friendly data types, using var in Java for local variables, simple Java operators with step by step examples, and how to read user input with Scanner in Java for beginners—you’re ready to build your first console apps confidently.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted