Java — Variables & Data Types

☕ Java 🟢 Lesson 2 📅 August 2026

A variable is a named storage location used to keep data while a program runs. Unlike Python, Java is statically typed, so every variable must have a data type before it can store a value.

1 Creating Variables

In Java, we write the data type first, then the variable name, and finally assign a value using =:

Java — Variable Declaration ▶ Run Code
public class Main {
    public static void main(String[] args) {
        String username = "Balaji";
        int age = 25;
        double height = 5.9;
        boolean isDeveloper = true;

        System.out.println(username);
        System.out.println(age);
        System.out.println(height);
        System.out.println(isDeveloper);
    }
}
2 Core Data Types

Java has primitive data types for storing simple values. The most common types are:

TypeDescriptionExample
intWhole numbers42
longVery large whole numbers9000000000L
doubleDecimal numbers3.1415
charOne character inside single quotes'A'
booleantrue or falsetrue
StringText inside double quotes"Java"

You can check a value's type indirectly through its declared type. Java checks the type during compilation.

Java — Different Data Types ▶ Run Code
public class Main {
    public static void main(String[] args) {
        int score = 99;
        char grade = 'A';
        boolean isOnline = false;
        String language = "Java";

        System.out.println(score);
        System.out.println(grade);
        System.out.println(isOnline);
        System.out.println(language);
    }
}
3 Type Casting

Type casting means converting a value from one data type to another. Smaller compatible types can usually be assigned to larger types automatically. Converting a larger type to a smaller type requires explicit casting.

Java — Type Casting ▶ Run Code
public class Main {
    public static void main(String[] args) {
        int number = 10;
        double largerNumber = number;
        System.out.println(largerNumber);

        double price = 19.99;
        int wholePrice = (int) price;
        System.out.println(wholePrice); // 19
    }
}
⚠️ Variable Naming Rules:
  • Names can contain letters, numbers, and underscores.
  • A variable name cannot start with a number.
  • Java variable names are usually written in camelCase, such as totalPrice.
  • Java is case-sensitive: age and Age are different names.
  • Do not use reserved keywords such as class, int, or public.
4 Coding Challenge

Create a Java program that declares a product name, price, discount percentage, available quantity, and stock status. Print every value and calculate the final price after the discount.