Java Data Types

Java Data Types

As explained in the previous chapter, a variable in Java must be a specified data type. Data types are divided into two groups:

  1. Primitive data types: Includes byte, short, int, long, float, double, boolean and char.
  2. Non-primitive data types (Reference Types): Includes String, Arrays, and Classes.

1. Primitive Data Types

A primitive data type specifies the size and type of variable values, and it has no additional methods. They are the most basic data types available in Java.

Integer Types

Integer types store whole numbers, positive or negative, without decimals.

Integer Types Example

byte myByte = 100;
short myShort = 5000;
int myInt = 100000;
long myLong = 15000000000L;
System.out.println(myLong);

Floating-Point Types

Floating-point types represent numbers with a fractional part.

Floating-Point Example

float myFloat = 5.75f;
double myDouble = 19.99d;
System.out.println(myFloat);

Other Primitive Types

Boolean and Char Example

boolean isJavaFun = true;
char myGrade = 'B';
System.out.println("Is Java fun? " + isJavaFun);
System.out.println("My grade is: " + myGrade);

2. Non-Primitive (Reference) Data Types

Non-primitive data types are called reference types because they refer to objects.

The main difference between primitive and non-primitive data types are:

Examples of non-primitive types include Strings, Arrays, Classes, Interfaces, etc.

String as a Reference Type

public class Main {
  public static void main(String[] args) {
    // The 'greeting' variable holds a reference to a String object
    String greeting = "Hello World";
    // We can call methods on the object
    System.out.println("The length of the string is: " + greeting.length());
  }
}