1. java
  2. /basics
  3. /data-types

Java Data Types - A Beginner's Guide

Diving into Java Data Types

To maneuver in Java's vast landscape, we'll inevitably have to understand the significance of data types. These types determine the kind of data we can store in variables, which is an instrumental aspect of our programs. As we explore each category, we'll examine their unique characteristics and use cases, providing you with the foundation needed to create more complex programs.

Primitive Data Types - The Building Blocks

Consider the primitives as the elementary building blocks for data manipulation in Java. These data types are the simplest and most basic, representing immutable values that embody the core types of data. Let's explore them in detail.

Integer Data Types - Byte, Short, Int, Long

Java provides four integer data types to store whole numbers, accommodating both positive and negative values. These data types — byte, short, int, and long — vary in size and range, allowing you to choose the one that best suits your specific needs. Let's take a closer look at each of these integer types and their characteristics.

byte b = 100;
short s = 200;
int i = 300;
long l = 40000L;

// Print the values of byte, short, int, and long data types to the console

System.out.println("Byte value: " + b); // Output: Byte value: 100

System.out.println("Short value: " + s); // Output: Short value: 200

System.out.println("Int value: " + i); // Output: Int value: 300

System.out.println("Long value: " + l); // Output: Long value: 40000
  • The byte data type is an 8-bit signed integer, using two's complement representation. It has a range from -128 to 127 and proves useful for conserving memory in large arrays.

  • The short data type is a 16-bit signed integer, also based on two's complement representation. It spans a range from -32,768 to 32,767 and serves to save memory in sizable arrays.

  • The int data type is a widely-used 32-bit signed integer, represented using two's complement. Its range extends from -2^31 to 2^31-1, making it the go-to data type for storing integral values.

  • The long data type is a 64-bit signed integer, employing two's complement representation. With a range of -2^63 to 2^63-1, it caters to situations where you need a broader scope than the int data type can provide.

Floating-Point Data Types – Float and Double

Java offers two floating-point data types, float and double, to represent real numbers. They differ in memory usage and precision, allowing you to choose the appropriate data type depending on your requirements.

float f = 3.14f;
double d = 3.141592653589793238;

// Print the values of float and double data types to the console

System.out.println("Float value: " + f); // Output: Float value: 3.14

System.out.println("Double value: " + d); // Output: Double value: 3.141592653589793

The float data type adheres to the single-precision 32-bit IEEE 754 floating-point standard. Its range spans approximately ±3.40282347E+38F, with 6-7 significant decimal digits ensuring a reasonable degree of precision.

On the other hand, the double data type complies with the double-precision 64-bit IEEE 754 floating-point standard. It provides a broader range of approximately ±1.79769313486231570E+308 and offers higher precision with 15 significant decimal digits.

Both float and double cater to different needs in terms of memory efficiency and precision, making them indispensable tools in a Java developer's arsenal.

Character Handling with Char Type

We employ the char data type to store a single character value. It plays a pivotal role in handling text and character-based operations.

char c = 'A';

// Print the value of char data type to the console

System.out.println("Char value: " + c); // Output: Char value: A

The char data type represents a 16-bit Unicode character, ranging from '\u0000' (0) to '\uffff' (65,535). This wide range ensures compatibility with various character sets and languages, making it a versatile tool for globalized applications.

The Boolean Type

Java's boolean data type is specifically designed to store true or false values. It's a fundamental component of conditional statements and loops, as it controls the flow of your program.

boolean bool = true;

// Print the value of boolean data type to the console
System.out.println("Boolean value: " + bool); // Output: Boolean value: true

With only two possible values — true and false — the boolean data type streamlines decision-making processes in your code, ensuring clear and concise logic.

Non-Primitive Data Types - Beyond the Basics

The non-primitives, also known as reference types, are more intricate than the primitive ones. They refer to objects and encompass arrays, classes, interfaces, and strings. Before we dive into these, let's address how you can incorporate the previous examples into a Java program.

In a typical Java setup, we would place the examples in the main method.

public class DataTypesExamples {
    public static void main(String[] args) {
        // Your example code goes here
    }
}

We omitted this setup in the previous sections to avoid repetitiveness. To experiment with the examples, insert them into the main method, replacing the comment.

Grouping Elements with Arrays

Arrays in Java are a unique case. They are neither purely primitive nor like other classes. While primitive data types are stack allocated, classes and arrays are heap allocated. Arrays have their unique byte code operations designed for their manipulation, and their size and layout in memory depend on the item type and the number of entries the array is created for.

// Declare and initialize an array of integers

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

// Print the values of the array elements to the console

for(int i = 0; i < arr.length; i++) {
    System.out.println("Element at index " + i + ": " + arr[i]);
}

Arrays are particularly useful when you need to organize a collection of elements with the same data type, providing efficient storage and easy access.

Defining Objects with Classes

A class is a layout for creating objects in Java. This non-primitive data type encapsulates data and behavior, enabling you to define custom data types with their unique properties and actions.

// Declare and define a class named Person
class Person {
    String fullName;
    int age;
    String address;

    // Constructor method for the Person class
    public Person(String fullName, int age, String address) {
        this.fullName = fullName;
        this.age = age;
        this.address = address;
    }

    // Method to print the details of the person
    public void displayDetails() {
        System.out.println("Name: " + fullName);
        System.out.println("Age: " + age);
        System.out.println("Address: " + address);
    }
}

// Create an object of the Person class and call its method
Person examplePerson = new Person("John Doe", 30, "123 Main St");
examplePerson.displayDetails();

Classes shine when you need to create a custom data type with specific attributes and behaviors tailored to your application.

Establishing Contracts with Interfaces

An interface in Java is a mechanism to attain abstraction. It can contain non-implemented methods (lacking a method body), often referred to as abstract methods. This characteristic sets it apart from a class. By defining a contract that classes implementing the interface must follow, interfaces lay the foundation for the shared behavior of these classes.

// Declare and define an interface named Drawable

interface Drawable {
    void draw();
}

// Create a class that implements the Drawable interface

class Rectangle implements Drawable {
    public void draw() {
        System.out.println("Drawing a rectangle");
    }
}

// Create an object of the Rectangle class and call its method

Rectangle rectangle = new Rectangle();
rectangle.draw();

The Versatile String Data Type

We use the string data type to store a sequence of characters, representing text. Unlike primitive data types, the string class allows you to hold multiple characters within a single variable, making it more convenient than working with character arrays.

String str1 = "Hello, world!";
String str2 = new String("Hello, world!");

// Print the value of String data type to the console

System.out.println("String value using literal: " + str1);

System.out.println("String value using constructor: " + str2);

The output would be as follows:

String value using literal: Hello, world!
String value using constructor: Hello, world!

Final Thoughts

We hope that we provided you with a solid enough understanding of both types of categories. As you continue to explore and learn about Java, you'll find these aspects crucial to your success as a Java developer. To further your knowledge, we strongly suggest visiting these useful resources below.

Useful Resources

The Basics of Java Syntax

Stack vs. Heap Memory explained

FAQ tagged Java on Stack Overflow