Java Data Types & Variables

Understand Java's primitive and non-primitive data types and how to use them.

Quick Summary

  • Java has 8 primitive data types (byte → double).
  • Non-primitive types include String, arrays, classes, etc.
  • Variables must be declared with a type.
  • Widening casting happens automatically; narrowing requires explicit casting.
  • Use final to create constants.

1. What Are Data Types in Java?

Java is a statically typed language, which means every variable must have a defined data type before use. Data types tell Java what kind of values a variable can store and how much memory it needs.

A. Primitive Data Types (Built-in)

Java provides 8 primitive types:

TypeSizeDescription
byte1 byteWhole numbers (−128 to 127)
short2 bytesWhole numbers (−32768 to 32767)
int4 bytesDefault integer type
long8 bytesVery large whole numbers
float4 bytesDecimal numbers (6–7 digits)
double8 bytesPrecise decimal numbers (~15 digits)
boolean1 bittrue or false
char2 bytesSingle character

B. Non-Primitive Data Types (Reference Types)

These are created by programmers and store references, not values. Examples include:

  • String
  • Arrays
  • Classes
  • Interfaces

2. Declaring and Initializing Variables

Try this example with

public class VariableDemo {
    public static void main(String[] args) {

        int count = 10;
        double price = 199.99;
        boolean active = true;
        char grade = 'A';
        String tool = "VINAR TECH";

        System.out.println("Count: " + count);
        System.out.println("Price: " + price);
        System.out.println("Active: " + active);
        System.out.println("Grade: " + grade);
        System.out.println("Tool Name: " + tool);
    }
}

3. Type Casting in Java

Type casting means converting one data type into another. Java supports two kinds of casting.

A. Widening Casting (Automatic)

Small → large. No extra code required.

Try example:

public class WideningDemo {
    public static void main(String[] args) {
        int num = 25;
        double result = num; // automatic conversion
        System.out.println("Converted value: " + result);
    }
}
B. Narrowing Casting (Manual)

Large → small. Requires explicit casting.

Try example:

public class NarrowingDemo {
    public static void main(String[] args) {
        double value = 99.99;
        int result = (int) value; // manual conversion
        System.out.println("Converted value: " + result);
    }
}

4. Constants in Java

Use the final keyword to create unchangeable variables (read-only).

Try example:

public class ConstantDemo {
    public static void main(String[] args) {
        final int MAX_USERS = 100;
        System.out.println("Max supported users: " + MAX_USERS);
    }
}
Sidebar Ad Space
Advertisement Space