Skip to main content

Data types

What are Data Types?

Data types in Java specify the kind of data a variable can hold. For example, a variable can store different kinds of data like integers, decimals, characters, and more. Java is a statically-typed language, which means that you must declare the data type of a variable when you first create it.

Categories of Data Types

Java data types are divided into two main categories:

  1. Primitive Data Types
  2. Reference (or Non-Primitive) Data Types

Primitive Data Types: The Building Blocks

Java has eight primitive data types, each serving a unique purpose. These are:

  1. byte
  • Size: 1 byte (8 bits)
  • Range: -128 to 127
  • Example: byte age = 25;

Use byte when you need to save memory and the range of values is small.

  1. short
  • Size: 2 bytes (16 bits)
  • Range: -32,768 to 32,767
  • Example: short year = 2024;

Similar to byte, but with a wider range.

  1. int
  • Size: 4 bytes (32 bits)
  • Range: -2^31 to 2^31-1
  • Example: int population = 1000000;

This is the most commonly used data type for integer values.

  1. long
  • Size: 8 bytes (64 bits)
  • Range: -2^63 to 2^63-1
  • Example: long distance = 1234567890L;

Use long for larger integer values. Note the L at the end of the number.

  1. float
  • Size: 4 bytes (32 bits)
  • Range: Approximately ±3.40282347E+38F (7 decimal digits)
  • Example: float price = 19.99f;

Use float for single-precision decimal numbers. Note the f at the end.

  1. double
  • Size: 8 bytes (64 bits)
  • Range: Approximately ±1.79769313486231570E+308 (15 decimal digits)
  • Example: double salary = 12345.67;

Use double for double-precision decimal numbers.

  1. char
  • Size: 2 bytes (16 bits)
  • Range: 0 to 65,535 (characters from the Unicode set)
  • Example: char grade = 'A';

Used to store a single character.

  1. boolean
  • Size: 1 bit
  • Values: true or false
  • Example: boolean isJavaFun = true;

Used for true/false values.

Non-Primitive Data Types: Beyond Numbers and Characters

Reference data types are more complex and include:

  1. Strings

Example: String greeting = "Hello, World!";

Strings are used to store sequences of characters.

  1. Arrays

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

Arrays hold multiple values of the same type.

  1. Classes and Interfaces

These are advanced topics that you'll learn as you progress. Classes are blueprints for creating objects, while interfaces define methods that a class must implement.

Summary

Understanding these basic data types will help you get started with Java programming.

Here's a quick recap:

Primitive Data Types: byte, short, int, long, float, double, char, boolean Reference Data Types: String, Arrays, Classes, Interfaces

Remember to always choose the right data type based on the kind of data you want to store and the memory efficiency you need.