Data Types

Data Types

A school program needs reliable data and clear rules. A type describes which values and operations are allowed. An int can represent a whole mark, a double can represent a decimal average, and a boolean can represent a decision.

  1. Understand

    A type describes which values and operations are allowed.

  2. Apply

    Trace the Java example, predict its output and explain the result before running it.

  3. Avoid mistakes

    Dividing two integers performs integer division before assignment. A double destination alone does not recover a discarded fraction.

Data Types in Java

In Java, every variable you use must have a declared type. Data type determines 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:

  • Primitive Data Types – Built-in, simple types provided by the Java language
  • Non-Primitive Data Types – More complex types derived from classes

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:

  • String – A sequence of characters
  • Arrays – Collection of variables of the same type
  • Classes and Interfaces – Blueprint for objects

Example: Working with Strings and Arrays

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

        System.out.println("Name: " + name);
        System.out.println("Scores:");
        for (int score : scores) {
            System.out.println(score);
        }
    }
}
Name: Arjun
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 TypeMismatchExample {
    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 InitErrorExample {
    public static void main(String[] args) {
        int x;
        System.out.println(x);
    }
}
InitErrorExample.java:4: error: variable x might not have been initialized
        System.out.println(x);
                           ^
1 error
ERROR!
error: compilation failed

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 IncompatibleTypesExample {
    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.

  • == checks whether references point to the same object.
  • .equals() checks whether the objects have the same content.
public class StringComparisonExample {
    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.

Important boundaries and mistakes

Dividing two integers performs integer division before assignment. A double destination alone does not recover a discarded fraction.

Try the school example

Before running this Java program, write down each line you expect to see. Identify the value, branch, object or exception responsible for each line. Then explain whether the following assumption is valid: Dividing two integers performs integer division before assignment.

Java 17 · Main.java · complete practice program

public class Main  {
  public static void main(String[] args)  {
    int total = 145;
    double average = total / 2.0;
    System.out.println(average);
  }
}

Now change one thing: Replace total with 151. Predict the new behavior before checking the worked variation.

Worked answer and reasoning

Java 17 · Main.java · source repeated for this answer

public class Main  {
  public static void main(String[] args)  {
    int total = 145;
    double average = total / 2.0;
    System.out.println(average);
  }
}

Expected output

72.5

A type describes which values and operations are allowed. An int can represent a whole mark, a double can represent a decimal average, and a boolean can represent a decision.

Dividing two integers performs integer division before assignment. A double destination alone does not recover a discarded fraction.

Run with javac Main.java, then java Main. The declaration of Main names the class; main starts the example, and println writes a complete output line.

Worked variation: Replace total with 151. Dividing by 2.0 produces 75.5; dividing by 2 would produce 75 before conversion.

Check your understanding

For the complete practice program in this lesson, which output is expected on Java 17?
Choose one answer. You can try again.

Answer and explanation

72.5

A type describes which values and operations are allowed. An int can represent a whole mark, a double can represent a decimal average, and a boolean can represent a decision. Dividing two integers performs integer division before assignment. A double destination alone does not recover a discarded fraction.

Check a common mistake

What is stored by double average = 145 / 2;?
Choose one answer. You can try again.

Answer and explanation

72.0, because integer division happens before conversion.

Both operands are integers, so division discards the fraction. The integer result can then widen to double; use 2.0 to perform floating-point division.

What to remember

A type describes which values and operations are allowed. An int can represent a whole mark, a double can represent a decimal average, and a boolean can represent a decision. Dividing two integers performs integer division before assignment. A double destination alone does not recover a discarded fraction.

Related explanations: Java Variables, Java If Statement - Syntax and Examples, Java Class - Blueprint of Objects, Exceptions in Java Introduction.

Supporting documentation: Official Java learning guide and Java 17 language specification.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Operators →