JavaBasics

Java Data Types

Learn about Java data types including primitive and non-primitive types, size, default values, and usage in programming.

Java Data TypesLink to this section

Data types define the type of data a variable can hold in Java. Choosing the correct data type is essential for **efficient memory usage** and **error-free programming**.

Primitive Data TypesLink to this section

Java provides 8 primitive data types that store simple values. They include numeric, character, and boolean types.

tip

Use int for general integer operations, double for decimal calculations, and boolean for flags.

Non-Primitive Data TypesLink to this section

Non-primitive (reference) types include:

  • Strings (sequence of characters)
  • Arrays (collection of elements)
  • Classes and Objects
  • Interfaces and Enums

note

Non-primitive types are stored as references, not actual values, and default to null.

Variable Declaration and InitializationLink to this section

A variable must be declared before use, specifying the data type.

warning

Using a variable without initialization may cause a compilation error if it’s used in expressions.

Type Conversion in JavaLink to this section

Java allows type conversion (casting) in two ways:

  • **Implicit Casting (Widening):** Smaller type → larger type automatically (safe)
  • **Explicit Casting (Narrowing):** Larger type → smaller type manually (may lose data)

tip

Avoid unnecessary narrowing conversions as it may truncate values.
Java Data Types
Question 1 of 5

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

Java Data Types

medium
  1. Declare variables of all primitive types, assign values, and print them to the console.
  2. Create a program that calculates the sum of a byte, short, and int variable, and print the result.
  3. Write a program that demonstrates explicit type casting from double to int.
  4. Create a boolean flag isPassed and assign a value. Print “Passed” if true, otherwise “Failed”.
  5. Create a String variable to store your full name and print each character using a loop.