Reading history

Java Variables and Data Types (Primitives, var, Casting)

4 min read 0 views

Learn Java variables and data types: the eight primitives and their ranges, String, final constants, var, casting, overflow and parsing.

Java is a statically typed language: every variable has a fixed type that the compiler checks before the program runs. That catches many mistakes early, but it means you need to know the types. This lesson covers declaring variables, Java’s eight primitive types, String, constants, var, and converting between types.

In this lesson you will learn

  • How to declare and initialise variables
  • The eight primitive types and their ranges
  • The difference between primitives and String
  • Constants with final, and var
  • Widening, casting, overflow and parsing

Declaring Variables

A declaration names the type, then the variable: int age = 21;. Every statement ends with a semicolon.

public class Main {
    public static void main(String[] args) {
        int age = 21;
        double cgpa = 3.75;
        char grade = 'A';
        boolean enrolled = true;
        String name = "Nila";
        long population = 171_000_000L;

        System.out.println(name + " is " + age + " years old");
        System.out.println("CGPA: " + cgpa + ", grade " + grade);
        System.out.println("Enrolled: " + enrolled);
        System.out.println("Population: " + population);

        final double VAT = 0.15;      // a constant
        var price = 200;              // type inferred as int
        System.out.println("VAT on " + price + " = " + price * VAT);
    }
}

Output

Nila is 21 years old
CGPA: 3.75, grade A
Enrolled: true
Population: 171000000
VAT on 200 = 30.0
  • char uses single quotes ('A'); String uses double quotes.
  • A long literal ends in L. Underscores in numbers (171_000_000) are only there for readability.
  • final makes a constant that cannot be reassigned. Constant names are usually written in CAPITALS.
  • var (Java 10+) lets the compiler work out the type from the value. The type is still fixed; price is an int.

The Eight Primitive Types

TypeSizeHoldsExample
byte1 byte-128 to 127byte b = 100;
short2 bytesabout ±32 thousandshort s = 3000;
int4 bytesabout ±2.1 billionint n = 42;
long8 bytesvery large whole numberslong l = 9_000_000_000L;
float4 bytesdecimals, ~7 digitsfloat f = 2.5f;
double8 bytesdecimals, ~15 digitsdouble d = 3.75;
char2 bytesone Unicode characterchar c = 'A';
boolean–true or falseboolean ok = true;

String is not a primitive; it is a class, so a String variable holds a reference to an object with methods like length(). See Java Strings.

Ranges, Casting and Overflow

public class Main {
    public static void main(String[] args) {
        System.out.println("int range: " + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE);
        System.out.println("byte range: " + Byte.MIN_VALUE + " to " + Byte.MAX_VALUE);

        int whole = 7;
        double widened = whole;           // automatic (widening) conversion
        double pi = 3.99;
        int narrowed = (int) pi;          // explicit cast drops the decimals
        System.out.println(widened + " " + narrowed);

        int big = Integer.MAX_VALUE;
        System.out.println("Overflow: " + (big + 1));

        int parsed = Integer.parseInt("250");
        String text = String.valueOf(3.5);
        System.out.println(parsed * 2 + " " + text.length());
    }
}

Output

int range: -2147483648 to 2147483647
byte range: -128 to 127
7.0 3
Overflow: -2147483648
500 3
  • Widening (smaller to larger type, like int to double) happens automatically.
  • Narrowing needs an explicit cast: (int) 3.99 gives 3. It cuts off the decimals; it does not round.
  • Overflow: adding 1 to the largest int wraps around to the smallest. Java does not warn you; use long when values can get large.
  • Integer.parseInt() turns text into a number, and String.valueOf() does the reverse.

Common Mistakes

  1. Using a variable before giving it a value. Local variables have no default; the compiler reports “might not have been initialized”.
  2. float f = 2.5; fails, because decimal literals are double. Write 2.5f.
  3. Integer division surprises. 5 / 2 is 2; write 5 / 2.0 for 2.5.
  4. Comparing strings with ==. Use .equals().

Practice Exercises

Exercise 1. Store the price 499.99 and quantity 3, then print the total.

Show answer
double price = 499.99;
int qty = 3;
System.out.println("Total: " + price * qty);

Exercise 2. What does (int) 9.99 + (int) 0.5 print?

Show answer

9. The casts give 9 and 0, because casting drops the decimal part.

Frequently Asked Questions

What is the difference between int and Integer?

int is a primitive value. Integer is its wrapper class, an object that can be null and can be stored in collections like ArrayList<Integer>. Java converts between them automatically (autoboxing).

Should I use float or double?

Use double by default; it is more precise. For money, professional code uses BigDecimal to avoid rounding errors.

Summary

  • Every Java variable has a type: type name = value;
  • There are eight primitives; String is a class.
  • final makes constants; var infers the type.
  • Widening is automatic, narrowing needs a cast, and int can overflow.

Next: Java Operators.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *