0
Explore
0

Data Types and Variables in Java

Updated on July 27, 2025

“Before we build a program, we need to know how to store and use data. That’s exactly what Data Types and Variables help us do in Java!”

What is a Variable?

A variable in Java is like a container that holds data during the execution of a program.

Real-life Example:

Imagine you have a cup and you pour water into it. Here:

  • The cup is the variable
  • The water is the data
  • The type of cup (small/large) is the data type

Key Points:

  • Every variable must have a name (called an identifier)
  • Every variable must be declared with a type
  • Variables can store, update, and retrieve values

How to Declare a Variable in Java?

int age;           // declaration
age = 25;          // initialization

You can also do both at once:

int age = 25;      // declaration + initialization

What are Data Types?

Data types define the type of data a variable can store, such as numbers, characters, or true/false values. In Java, they are strongly typed, which means every variable must be declared with a specific type before use.

Key Characteristics of Data Types:

1. Strongly Typed Language

  • Java does not allow a variable to hold multiple types of values.Once a variable is declared as a type (e.g., int, char), it can only store values of that type.

int number = 10; // valid 
number = "Ten"; // ❌ error: incompatible types

2. Compile-Time Type Checking

The Java compiler checks data types at compile time to reduce errors.

3. Memory Efficient

Each data type has a fixed size in memory, which helps in efficient resource usage.

Categories of Data Types in Java

Java has two main types of data types:

CategoryData TypesExample
1. Primitivebyte, short, int, long, float, double, char, booleanint x = 5;
2. Non-PrimitiveString, Arrays, Classes, InterfacesString name = "John";

1️⃣ Primitive Data Types

These are predefined by the language. They store simple values.

Types of Primitive Data Types

Data TypeDescriptionSizeExample
byteInteger (very small)1 bytebyte a = 100;
shortInteger (small)2 bytesshort b = 20000;
intInteger (default)4 bytesint age = 25;
longBig Integer8 byteslong stars = 123456789L;
floatDecimal (less precise)4 bytesfloat pi = 3.14f;
doubleDecimal (more precise)8 bytesdouble e = 2.71828;
charSingle character2 byteschar grade = 'A';
booleanTrue or False1 bitboolean isJavaFun = true;

Java Program Primitive Data Type Example: Using int and char

public class PrimitiveDataTypesExample {
    public static void main(String[] args) {
        // int: to store age
        int age = 25;

        // char: to store grade
        char grade = 'A';

        // Display the values
        System.out.println("Student Age: " + age);
        System.out.println("Student Grade: " + grade);
    }
}

Output:

Student Age: 25
Student Grade: A

Explanation:

  • int age = 25; → Stores the whole number 25.
  • char grade = 'A'; → Stores the character ‘A’.
  • System.out.println(...) is used to print the values to the console.

2️⃣ Non-Primitive (Reference) Data Types

In Java, Non-Primitive Data Types (also called Reference Data Types) are used to store more complex data than primitive types like int, char, or boolean.

Unlike primitive types which store simple values directly, reference types store addresses (references) that point to objects in memory.

Types of Non-Primitive Data Types

Java provides many non-primitive types, but here are the most commonly used ones:

Data TypeDescription
StringSequence of characters (text)
ArrayCollection of similar elements
ClassBlueprint for creating objects
InterfaceContract for classes to follow
EnumSet of named constants
ObjectBase type for all Java classes

Example 1: String (Non-Primitive Type)

A String is a sequence of characters used to represent text.

String name = "Prakash";
System.out.println(name);  // Output: Prakash

Explanation:

  • "Prakash" is stored in memory as a String object.
  • name holds the reference to that memory location.

Behind the Scenes:

Internally, Java treats a String as a class (i.e., an object with methods).

You can use:

System.out.println(name.length()); // Get the length of the string
System.out.println(name.toUpperCase()); // Convert to uppercase

Example 2: Arrays (Non-Primitive Type)

An array is a collection of fixed-size similar elements (same data type), stored in contiguous memory.

int[] numbers = {1, 2, 3, 4};
System.out.println(numbers[0]);  // Output: 1

Explanation:

  • The array holds 4 int values.
  • numbers is a reference that points to the memory location of the array.
  • You can access elements using indexes: numbers[0], numbers[1], etc.

More Array Operations:

System.out.println(numbers.length);   // Output: 4
System.out.println(numbers[2]);       // Output: 3

Example 3: Classes and Objects

A class is a blueprint. An object is an instance of a class. Classes are user-defined non-primitive data types.

class Student {
    String name;
    int age;
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();   // s1 is a reference variable
        s1.name = "Ravi";
        s1.age = 20;

        System.out.println(s1.name + " is " + s1.age + " years old.");
    }
}

Explanation:

  • Student is a class (non-primitive type).
  • s1 is a variable that refers to a Student object in memory.

Example 4: Interfaces

An interface is like a contract that classes must follow. It doesn’t have actual code — only method declarations.

interface Animal {
    void makeSound();
}

class Dog implements Animal {
    public void makeSound() {
        System.out.println("Woof");
    }
}

Explanation:

  • Animal is an interface (non-primitive type).
  • Dog implements the interface by providing the method body.

Differences Between Primitive and Non-Primitive

FeaturePrimitive Data TypesNon-Primitive Data Types
StoresActual valueReference to object
SizeFixedCan vary (depends on object)
Can be null?NoYes
Includes methods?NoYes (e.g., String.length())
Examplesint, char, booleanString, Array, Class

Important Notes

  • Default values of non-primitive types (if not initialized) are null.
  • You can use .equals() to compare two non-primitive types like Strings.
  • Non-primitive types are stored on the heap and accessed via references.

Variable Naming Rules in Java

  1. Must start with a letter, _ or $
  2. Cannot start with a number
  3. Cannot use Java reserved keywords (e.g., int, class)
  4. Case-sensitive (Age and age are different)
  5. Should be meaningful (e.g., use marks not x)

✅ Good: studentAge, totalMarks, isEligible

🚫 Bad: 1age, total@marks, int

Variable Types Based on Scope

TypeDefined insideAccessible within
LocalMethodsThat method only
InstanceClassAll methods (non-static)
Static/ClassClassAll static methods

Example with Multiple Data Types

public class DataTypeExample {
    public static void main(String[] args) {
        int age = 24;
        double weight = 72.5;
        char grade = 'A';
        boolean isPassed = true;
        String name = "Ravi";

        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Weight: " + weight);
        System.out.println("Grade: " + grade);
        System.out.println("Passed: " + isPassed);
    }
}

Output

Name: Ravi
Age: 24
Weight: 72.5
Grade: A
Passed: true

Why Choosing the Right Data Type Matters?

Choosing the correct data type:

  • Optimizes memory
  • Prevents errors
  • Improves performance

Example:
If you just need to store a small number like 10, using int is better than long.

Java is a Strongly Typed Language

This means Java does not allow assigning a value of one type to another type without explicit conversion.

int x = 10;
double y = x; // valid (int → double is widening)
int z = y;    // ❌ error (double → int needs casting)

What is Type Casting?

Widening Casting (automatically): smaller to larger data type

int a = 100;
double b = a; // OK

Narrowing Casting (manually): larger to smaller data type

double x = 123.45;
int y = (int) x; // need to cast

Practice Set for Students

Q1: Write a Java program to declare variables of all primitive data types and print them.

Q2: Create a program where:

  • You declare String name, int age, double percentage
  • Then print: "My name is Ravi, I am 20 years old, and scored 85.5%"

Q3: Write a Java program that uses type casting to convert:

  • double value = 87.56 into int
  • Print both values before and after casting

Summary

✅ Variables in Java are containers to store data.
✅ Data types define what kind of data you can store.
✅ Java has primitive and non-primitive data types.
✅ Always declare variables before use with proper data type.
✅ Naming rules and scope should be followed carefully.