Skip to main content
Java Basics
CHAPTER 04 Beginner

Variables and Data Types

Updated: May 17, 2026
5 min read

# CHAPTER 4

Variables and Data Types

1. Introduction

Variables are the building blocks of any program. They are containers that store data in your computer's memory. Think of a variable as a labeled jar — the label is the variable name, and the contents inside is the value. In this chapter, we'll learn about Java's data types and how to use variables effectively.

2. Learning Objectives

  • Declare and initialize variables.
  • Understand all 8 primitive data types.
  • Differentiate between primitive and non-primitive types.
  • Use constants with the final keyword.
  • Perform type casting (widening and narrowing).

3. What is a Variable?

A variable is a named storage location in memory that holds a value.
java
12
int age = 25;        // 'age' is the variable, 25 is the value
String name = "John"; // 'name' is the variable, "John" is the value
1234567
Memory Visualization:
+----------+----------+
| Variable | Value    |
+----------+----------+
| age      | 25       |
| name     | "John"   |
+----------+----------+

4. Declaring Variables

Syntax: dataType variableName = value;
java
123456789
// Declaration and initialization
int score = 100;

// Declaration first, assignment later
int level;
level = 5;

// Multiple declarations
int x = 1, y = 2, z = 3;

5. Primitive Data Types

Java has 8 primitive data types — this is a critical interview topic:
TypeSizeRangeExample
byte1 byte-128 to 127byte b = 100;
short2 bytes-32,768 to 32,767short s = 30000;
int4 bytes-2.1B to 2.1Bint i = 100000;
long8 bytesVery largelong l = 99999L;
float4 bytes6-7 decimal digitsfloat f = 3.14f;
double8 bytes15 decimal digitsdouble d = 3.14159;
char2 bytesSingle characterchar c = 'A';
boolean1 bittrue or falseboolean b = true;
java
123456789101112131415161718192021
public class DataTypesDemo {
    public static void main(String[] args) {
        byte myByte = 127;
        short myShort = 32000;
        int myInt = 100000;
        long myLong = 15000000000L;  // Note the 'L' suffix
        float myFloat = 3.14f;       // Note the 'f' suffix
        double myDouble = 3.14159265;
        char myChar = 'A';
        boolean myBool = true;

        System.out.println("byte: " + myByte);
        System.out.println("short: " + myShort);
        System.out.println("int: " + myInt);
        System.out.println("long: " + myLong);
        System.out.println("float: " + myFloat);
        System.out.println("double: " + myDouble);
        System.out.println("char: " + myChar);
        System.out.println("boolean: " + myBool);
    }
}

6. Non-Primitive Data Types

Non-primitive types are created by the programmer and refer to objects:
  • String — A sequence of characters
  • Arrays — A collection of elements
  • Classes — User-defined blueprints
  • Interfaces — Contracts for classes
java
12
String greeting = "Hello, Java!";
int[] numbers = {1, 2, 3, 4, 5};

Key Difference: Primitive types store actual values. Non-primitive types store *references* (memory addresses) pointing to objects on the Heap.

7. Constants with final

A constant is a variable whose value cannot be changed after assignment.
java
1234
final double PI = 3.14159;
final int MAX_USERS = 1000;

// PI = 3.0; // ERROR! Cannot reassign a final variable

8. Type Casting

Widening (Automatic): Smaller type → Larger type (safe, no data loss)
java
123
int myInt = 100;
double myDouble = myInt;  // Automatic: int → double
System.out.println(myDouble); // 100.0

Narrowing (Manual): Larger type → Smaller type (risky, possible data loss)

java
123
double myDouble = 9.78;
int myInt = (int) myDouble;  // Manual cast required
System.out.println(myInt);   // 9 (decimal part is lost!)
12345
Widening (automatic):
byte → short → int → long → float → double

Narrowing (manual):
double → float → long → int → short → byte

9. var Keyword (Java 10+)

Java 10 introduced local variable type inference:
java
123
var name = "Alice";     // Compiler infers String
var age = 25;           // Compiler infers int
var price = 19.99;      // Compiler infers double

10. Common Mistakes

  • Using float without the f suffix: float f = 3.14; causes an error. Use float f = 3.14f;.
  • Using long without the L suffix: Large numbers need long x = 999999999L;.
  • Integer overflow: int x = 2147483647 + 1; wraps around to a negative number!
  • Confusing = and ==: = is assignment, == is comparison.

11. Best Practices

  • Use int for whole numbers (most common).
  • Use double for decimals (most common).
  • Use boolean for flags and conditions.
  • Use final for values that should never change.
  • Name constants in UPPERSNAKECASE.

12. Exercises

  1. 1. Declare variables to store your name, age, GPA, and enrollment status.
  1. 2. Create a program that demonstrates widening and narrowing type casting.
  1. 3. Try to assign a new value to a final variable. What error do you get?

13. MCQ Quiz with Answers

Question 1

How many primitive data types does Java have?

Question 2

Which data type would you use to store a person's age?

Question 3

What suffix is required for a float literal?

Question 4

What keyword makes a variable constant?

Question 5

What is narrowing type casting?

Question 6

What is the default value of an int instance variable?

Question 7

Which type stores true/false values?

Question 8

What is the size of a double in Java?

Question 9

Which is a non-primitive data type?

Question 10

What happens with int x = (int) 9.99;?

14. Interview Questions

  • Q: What is the difference between primitive and non-primitive data types?
  • Q: What happens when an int overflows in Java?
  • Q: Explain widening and narrowing type casting with examples.
  • Q: What is the difference between float and double?

15. FAQs

Q: Why does Java have so many integer types (byte, short, int, long)? A: Memory optimization. On embedded systems or when storing millions of values, using byte instead of int saves significant memory.

16. Summary

Variables store data in memory. Java has 8 primitive types covering integers, decimals, characters, and booleans. Non-primitive types reference objects. Constants use final. Type casting converts between types — widening is safe and automatic, narrowing is manual and risky.

17. Next Chapter Recommendation

Now that you can store data, you need to manipulate it. In Chapter 5: Operators in Java, we'll learn arithmetic, relational, logical, and bitwise operators.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·