Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ReferenceJava Reference1

Java Data Types
Primitive and Non-Primitive



Data Types in Java

Java is a statically typed language, which means every variable you use must have a declared type. Understanding data types is one of the basic steps in leanring Java because they determine how much memory is allocated and what kind of operations you can perform on that data.

Types of Data Types in Java

Java data types are broadly categorized into two groups:

1. Primitive Data Types in Java

Java has 8 primitive data types, and each has a specific purpose and memory size.

TypeSizeDefault ValueDescription
byte1 byte0Useful for saving memory in large arrays
short2 bytes0Shorter-range integers
int4 bytes0Standard integer type
long8 bytes0LLarger-range integers
float4 bytes0.0fSingle-precision decimals
double8 bytes0.0dDouble-precision decimals
char2 bytes'\u0000'Single character (Unicode)
boolean~1 bitfalseTrue or false values

Example: Using Primitive Data Types

public class PrimitiveExample {
    public static void main(String[] args) {
        int age = 25;
        double salary = 45600.75;
        char grade = 'A';
        boolean isEmployed = true;

        System.out.println("Age: " + age);
        System.out.println("Salary: " + salary);
        System.out.println("Grade: " + grade);
        System.out.println("Employed: " + isEmployed);
    }
}
Age: 25
Salary: 45600.75
Grade: A
Employed: true

2. Non-Primitive Data Types in Java

Non-primitive types are created by the programmer and can hold multiple values or have behavior. These include:

Example: Working with Strings and Arrays

public class NonPrimitiveExample {
    public static void main(String[] args) {
        String name = "Java Learner";
        int[] scores = {85, 90, 78};

        System.out.println("Name: " + name);
        System.out.println("Scores:");
        for (int score : scores) {
            System.out.println(score);
        }
    }
}
Name: Java Learner
Scores:
85
90
78

Type Verification and Best Practices

Understanding how Java enforces type safety is crucial when working with literals. Java is a statically typed language, meaning types are checked at compile-time, helping catch errors early and ensuring predictability in program behavior.

1. Always match the type with the value:

Java does not allow assigning a float or double literal to an int variable without an explicit cast. This prevents accidental loss of precision or data.

public class TypeMismatch {
    public static void main(String[] args) {
        // int x = 3.14; // Compile-time error
        int x = (int) 3.14; // Works but loses decimal
        System.out.println(x);
    }
}
3

While casting may resolve the error, it’s usually better to use the right data type from the start to preserve intent and accuracy.

2. Use suffixes:

Java treats numeric literals as int by default for integers and double for decimals. If you intend to use a long or float, suffixes like L or F must be added.

public class SuffixExample {
    public static void main(String[] args) {
        long population = 7800000000L;
        float pi = 3.14159F;
        double gravity = 9.8; // no suffix needed, double is default
        System.out.println(population);
        System.out.println(pi);
        System.out.println(gravity);
    }
}
7800000000
3.14159
9.8

Without the correct suffix, you'll either encounter a compilation error (for long) or a potential precision mismatch (for float).

3. Check for overflow:

Java primitives like byte and short have narrow ranges. Arithmetic operations that exceed their limits will silently wrap around (overflow), leading to unexpected results.

public class OverflowDemo {
    public static void main(String[] args) {
        byte b = 127;
        b += 1; // wraps around to -128
        System.out.println(b);
    }
}
-128

For arithmetic-heavy applications, use int or long to avoid such silent overflows.

Common Mistakes to Avoid

Even seasoned developers stumble over these classic pitfalls. Here’s how you can avoid them:

1. Forgetting to initialize variables:

Java enforces definite assignment. Local variables must be explicitly initialized before use—otherwise, the compiler will throw an error.

public class InitError {
    public static void main(String[] args) {
        int x;
        System.out.println(x); // Error: variable x might not have been initialized
        x = 10;
        System.out.println(x); // Works fine
    }
}

Class-level fields are auto-initialized (e.g. int to 0, boolean to false), but local variables are not.

2. Mixing incompatible types without casting:

Attempting to combine different types (e.g. int with String) or assign a higher precision type to a lower one without casting will lead to compile-time errors.

public class IncompatibleTypes {
    public static void main(String[] args) {
        double d = 5.5;
        int i = (int) d; // Explicit cast
        System.out.println(i); // Output: 5
    }
}
5

Use casting carefully as it may lead to data truncation or loss of precision.

3. Misunderstanding == vs .equals() for reference types:

Beginners often confuse these two when comparing strings or objects.

public class StringComparison {
    public static void main(String[] args) {
        String a = new String("hello");
        String b = new String("hello");
        System.out.println(a == b);       // false (different objects)
        System.out.println(a.equals(b));  // true (same content)
    }
}
false
true

When comparing object values, always use .equals() unless you're explicitly checking for reference equality.

QUIZ

Question 1:Which of the following is a primitive data type in Java?

Question 2:Java allows using a float literal without a suffix like 'F'.

Question 3:Which of the following are characteristics of primitive data types in Java?

Question 4:What will be the output of the following code?
byte b = 127;
b += 1;
System.out.println(b);

Question 5:In Java, local variables are automatically initialized with default values.

Question 6:Which of the following are considered non-primitive data types in Java?



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M