Lesson 4 – Data Types

Data types tell Java what kind of value a variable stores. Java is a strongly typed language, which means you must clearly define the data type before using a variable.

1. Numeric Data Types

Example 1 – Full Program: Numeric Types

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

        int age = 25;
        double salary = 5599.99;
        float temperature = 33.5f;
        long population = 8000000000L;

        System.out.println(age);
        System.out.println(salary);
        System.out.println(temperature);
        System.out.println(population);
    }
}
        

2. Text Data Types

Example 2 – Full Program: String and char

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

        String name = "Khalid";
        char grade = 'A';

        System.out.println(name);
        System.out.println(grade);
    }
}
        

3. Boolean Data Type

boolean stores only two values: true or false.

Example 3 – Full Program: Boolean

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

        boolean isJavaFun = true;
        boolean isCold = false;

        System.out.println(isJavaFun);
        System.out.println(isCold);
    }
}
        

4. Mixing Data Types in Calculations

Example 4 – Full Program

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

        int a = 10;
        double b = 5.5;
        double result = a + b;

        System.out.println("Result: " + result);
    }
}
        

5. Concatenating (Joining) Text

Example 5 – Full Program

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

        String first = "Khalid";
        String last = "Khattak";
        String fullName = first + " " + last;

        System.out.println(fullName);
    }
}
        

6. Type Casting

Type casting means converting one data type into another.

• Widening (automatic)

Small → big type (safe)

Example 6 – Full Program

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

        int num = 10;
        double converted = num; // automatic conversion

        System.out.println(converted);
    }
}
        

• Narrowing (manual)

Big → small type (may lose data)

Example 7 – Full Program

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

        double value = 9.78;
        int converted = (int) value; // manual cast

        System.out.println(converted);
    }
}
        

7. Summary

Back to Top