Skip to main content
Java beginner Lesson 5 of 58

Variables and Operators in Java

Learn how to declare variables, use Java's operators, take user input with Scanner, work with constants, and use the Math class.

Variables are named containers for data. Operators are symbols that perform operations on that data. Together they form the building blocks of every Java program — you use them to store values, transform data, compare conditions, and build expressions.

Declaring Variables

Java is statically typed — every variable has a type that never changes. Declaring the type up front makes your intent explicit and lets the compiler catch type mismatches before the program ever runs.

// type  name    value
   int   age   = 25;
   double price = 19.99;
   boolean active = true;
   String  name  = "Alice";

Naming Rules

  • Must start with a letter, _, or $ (convention: start with a letter)
  • Cannot be a Java keyword (int, class, for, etc.)
  • Case-sensitive: age, Age, and AGE are three different variables
  • Convention: camelCase for variables (firstName, totalPrice)

var — Type Inference (Java 10+)

var lets you skip writing the type name when it is already obvious from the right-hand side. The type is still fixed at compile time — this is not dynamic typing, just less ceremony for local variables.

var count  = 0;           // compiler infers int
var name   = "Alice";     // compiler infers String
var items  = new ArrayList<String>(); // compiler infers ArrayList<String>

// var requires an initialiser — type is fixed at compile time
// var x;  // COMPILE ERROR — no initialiser

Constants with final

A final variable can be assigned exactly once — after that, it is immutable. Using constants for magic numbers makes your code self-documenting and centralises values that would otherwise be scattered across the codebase. If the value ever needs to change, you update one place.

final double PI            = 3.14159265358979;
final int    MAX_ATTEMPTS  = 3;
final String APP_NAME      = "SkillByExample";

// MAX_ATTEMPTS = 5; // COMPILE ERROR — cannot reassign a final variable

By convention, constants use UPPER_SNAKE_CASE.

Arithmetic Operators

Arithmetic operators work on numeric types and produce numeric results. The most important thing to understand here is integer division — when both operands are integers, the result is an integer and the decimal part is silently discarded.

int a = 17, b = 5;

System.out.println(a + b);   // 22  — addition
System.out.println(a - b);   // 12  — subtraction
System.out.println(a * b);   // 85  — multiplication
System.out.println(a / b);   // 3   — integer division (truncates)
System.out.println(a % b);   // 2   — modulo (remainder)

// Floating-point division
System.out.println(17.0 / 5);  // 3.4
System.out.println((double) a / b); // 3.4 — cast to get decimal result

Integer Division Trap

This is one of the most common beginner bugs. When both operands are int, Java performs integer division and drops the decimal before the result is stored — even if you store it in a double.

int total = 7, count = 2;
double average = total / count;         // 3.0 — WRONG: integer division first
double correct = (double) total / count; // 3.5 — cast before dividing

Increment and Decrement

The ++ and -- operators add or subtract 1 from a variable. The difference between prefix and postfix matters when the expression’s value is used — prefix changes the value first, postfix returns the original value and then changes it.

int x = 5;
x++;   // x is now 6 (post-increment)
x--;   // x is now 5 (post-decrement)
++x;   // x is now 6 (pre-increment)

// Pre vs post in expressions:
int a = 5;
int b = a++;  // b = 5, a = 6 (post: use then increment)
int c = ++a;  // c = 7, a = 7 (pre: increment then use)

Compound Assignment

Compound assignment operators (+=, -=, etc.) are shorthand that reads more naturally and saves keystrokes. They also avoid repeating the variable name, which reduces copy-paste errors.

int n = 10;
n += 5;   // n = 15  (n = n + 5)
n -= 3;   // n = 12  (n = n - 3)
n *= 2;   // n = 24  (n = n * 2)
n /= 4;   // n = 6   (n = n / 4)
n %= 4;   // n = 2   (n = n % 4)

Comparison Operators

Comparison operators evaluate two values and always return a boolean. They are the foundation of every conditional and loop condition you will write.

int a = 10, b = 20;

System.out.println(a == b);  // false — equal to
System.out.println(a != b);  // true  — not equal to
System.out.println(a <  b);  // true  — less than
System.out.println(a >  b);  // false — greater than
System.out.println(a <= b);  // true  — less than or equal
System.out.println(a >= b);  // false — greater than or equal

Never use == to compare Strings — use .equals():

String s1 = "hello";
String s2 = "hello";
System.out.println(s1 == s2);      // true (coincidence — string pool)
String s3 = new String("hello");
System.out.println(s1 == s3);      // false (different objects)
System.out.println(s1.equals(s3)); // true (correct way — compares content)

Logical Operators

Logical operators combine boolean expressions. Short-circuit evaluation is especially important: && stops evaluating as soon as it finds a false, and || stops as soon as it finds a true. This is not just a performance optimisation — it is often used deliberately to guard against null dereferences or division by zero.

boolean sunny = true;
boolean warm  = false;

System.out.println(sunny && warm);   // false — AND: both must be true
System.out.println(sunny || warm);   // true  — OR: at least one must be true
System.out.println(!sunny);          // false — NOT: inverts the value

// Short-circuit evaluation prevents divide-by-zero
int x = 0;
if (x != 0 && 10 / x > 2) {  // safe: 10/x never evaluated if x == 0
    System.out.println("ok");
}

Bitwise Operators

Bitwise operators work on the individual bits of integer values. They are used in systems programming, flag masking, and performance-sensitive code where multiple boolean states need to be packed into a single integer.

int a = 0b1010;  // 10 in binary
int b = 0b1100;  // 12 in binary

System.out.println(a & b);   // 8  (0b1000) — AND
System.out.println(a | b);   // 14 (0b1110) — OR
System.out.println(a ^ b);   // 6  (0b0110) — XOR
System.out.println(~a);      // -11          — NOT (flips all bits)
System.out.println(a << 1);  // 20 (shift left = multiply by 2)
System.out.println(a >> 1);  // 5  (shift right = divide by 2)

Ternary Operator

The ternary operator is a compact inline if/else. It is most readable for simple value choices — when the condition or branches are complex, a regular if/else is clearer.

int score = 75;
String result = score >= 60 ? "Pass" : "Fail";  // "Pass"

// Equivalent to:
String result2;
if (score >= 60) result2 = "Pass";
else             result2 = "Fail";

Operator Precedence

Operator precedence determines which operations execute first in a complex expression, just like BODMAS in arithmetic. When in doubt, use parentheses — they make intent explicit and prevent hard-to-spot bugs.

PrecedenceOperators
Highest++ -- (postfix), ! ~
* / %
+ -
<< >>
< <= > >=
== !=
&&
||
Lowest= += -= etc.
int result = 2 + 3 * 4;      // 14 — multiplication first
int result2 = (2 + 3) * 4;   // 20 — parentheses first

User Input with Scanner

The Scanner class reads from an input stream — System.in for keyboard input. It parses the raw text into typed values like int and double. Handling user input is essential for interactive programs and a great way to make your early exercises feel real.

import java.util.Scanner;

public class InputDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

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

        System.out.print("Enter your height (m): ");
        double height = scanner.nextDouble();

        System.out.printf("Hello %s! Age %d, height %.2fm%n", name, age, height);

        scanner.close(); // release the resource when done
    }
}

Scanner Methods

MethodReads
nextLine()Full line as String
next()One word (stops at whitespace)
nextInt()int
nextLong()long
nextDouble()double
nextBoolean()boolean (true/false)

Common trap — mixing nextInt() and nextLine(). When nextInt() reads a number, it leaves the newline character in the input buffer. The next nextLine() call reads that leftover newline and returns an empty string instead of waiting for your input.

int age = scanner.nextInt();    // reads "25", leaves "\n" in buffer
String name = scanner.nextLine(); // reads the leftover "\n" — gets empty string!

// Fix: add an extra nextLine() to consume the newline
int age = scanner.nextInt();
scanner.nextLine();             // consume leftover newline
String name = scanner.nextLine(); // now reads correctly

The Math Class

java.lang.Math provides common mathematical operations with no import needed — it is part of java.lang, which Java imports automatically. It covers everything from basic rounding to trigonometry.

Math.abs(-42)          // 42     — absolute value
Math.max(10, 20)       // 20     — larger of two values
Math.min(10, 20)       // 10     — smaller of two values
Math.pow(2, 10)        // 1024.0 — 2 to the power of 10
Math.sqrt(144)         // 12.0   — square root
Math.cbrt(27)          // 3.0    — cube root
Math.ceil(3.2)         // 4.0    — round up
Math.floor(3.9)        // 3.0    — round down
Math.round(3.5)        // 4      — round to nearest int
Math.log(Math.E)       // 1.0    — natural log
Math.log10(1000)       // 3.0    — log base 10
Math.PI                // 3.141592653589793
Math.E                 // 2.718281828459045

// Random number between 0.0 (inclusive) and 1.0 (exclusive)
double rand = Math.random();

// Random int between min (inclusive) and max (exclusive)
int min = 1, max = 7;
int dice = (int)(Math.random() * (max - min)) + min; // 1 to 6

Exercises

Calculator

import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter first number: ");
        double a = sc.nextDouble();

        System.out.print("Enter operator (+, -, *, /): ");
        String op = sc.next();

        System.out.print("Enter second number: ");
        double b = sc.nextDouble();

        // switch expression cleanly maps each operator to its result
        double result = switch (op) {
            case "+" -> a + b;
            case "-" -> a - b;
            case "*" -> a * b;
            case "/" -> b != 0 ? a / b : Double.NaN;
            default  -> throw new IllegalArgumentException("Unknown operator: " + op);
        };

        System.out.printf("%.2f %s %.2f = %.2f%n", a, op, b, result);
        sc.close();
    }
}

Temperature Converter

import java.util.Scanner;

public class TempConverter {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter temperature: ");
        double temp = sc.nextDouble();
        System.out.print("Convert from (C/F): ");
        String unit = sc.next().toUpperCase();

        if (unit.equals("C")) {
            double fahrenheit = temp * 9.0 / 5.0 + 32;
            System.out.printf("%.2f°C = %.2f°F%n", temp, fahrenheit);
        } else if (unit.equals("F")) {
            double celsius = (temp - 32) * 5.0 / 9.0;
            System.out.printf("%.2f°F = %.2f°C%n", temp, celsius);
        } else {
            System.out.println("Unknown unit. Use C or F.");
        }

        sc.close();
    }
}

BMI Calculator

import java.util.Scanner;

public class BMICalculator {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Weight (kg): ");
        double weight = sc.nextDouble();
        System.out.print("Height (m): ");
        double height = sc.nextDouble();

        double bmi = weight / (height * height);
        String category;

        // Chained if-else maps BMI ranges to WHO categories
        if      (bmi < 18.5) category = "Underweight";
        else if (bmi < 25.0) category = "Normal weight";
        else if (bmi < 30.0) category = "Overweight";
        else                 category = "Obese";

        System.out.printf("BMI: %.1f — %s%n", bmi, category);
        sc.close();
    }
}

Frequently Asked Questions

What is the difference between = and == in Java?
= is the assignment operator — it stores a value in a variable. == is the equality operator — it compares two values. A common bug is writing if (x = 5) instead of if (x == 5); the former assigns 5 to x and always evaluates to true.
What does final mean in Java?
final on a variable means it can only be assigned once — it becomes a constant. By convention, constants are named in UPPER_SNAKE_CASE. final int MAX_SIZE = 100 cannot be changed after declaration.
How do I read user input in Java?
Use the Scanner class from java.util. Create Scanner scanner = new Scanner(System.in), then call scanner.nextLine() for strings, scanner.nextInt() for integers, etc.