Java Programming Handbook

    Data Types in Java

    When writing Java programs, we need to store and manipulate different types of data, such as numbers, characters, and boolean values. Java provides various data types to define the kind of data a variable can hold. Understanding data types is essential for writing efficient and error-free code.

    Types of Data Types in Java#

    Java data types are broadly categorized into two types:

    Data Types in Java

    1. Primitive Data Types#

    Primitive data types are the most basic types of data. Java has 8 primitive data types:

    a) Integer Types#

    These data types are used to store whole numbers (both positive and negative).

    byte: Stores small integers (-128 to 127).

    byte age = 25;

    short: Stores numbers from -32,768 to 32,767.

    short year = 2024;

    int: Stores larger integers (-2 billion to 2 billion).

    int salary = 50000;

    long: Stores very large numbers. Needs an L at the end.

    long population = 7800000000L;

    b) Floating-Point Types#

    Used to store decimal numbers.

    float: Stores decimal values with less precision. Needs an F at the end.

    float price = 10.99F;

    double: Stores decimal values with higher precision.

    double pi = 3.14159265359;

    c) Character Type#

    char: Stores a single character using single quotes (' ').

    char grade = 'A';

    d) Boolean Type#

    boolean: Stores only true or false values.

    boolean isJavaFun = true;

    2. Non-Primitive Data Types#

    Non-primitive data types are more complex than primitive types and include objects, arrays, and strings.

    String: A sequence of characters enclosed in double quotes (" ").

    String message = "Hello, Java!";

    Arrays: A collection of elements of the same type.

    int[] numbers = {1, 2, 3, 4, 5};

    Conclusion#

    In this blog, we explored the two main categories of data types in Java: primitive and non-primitive types. We covered the 8 primitive types (byte, short, int, long, float, double, char, and boolean), along with examples. We also introduced non-primitive types like String and arrays. Understanding data types is crucial for writing efficient Java programs. Choosing the right data type helps in optimizing memory usage and improving performance.

    Last updated on Apr 09, 2025