Java Data Types

In this tutorial, we will learn Java Data Types and how to use both primitive and non-primitive data types in Java and this will include their syntax and how to implement them in a real-world problem.We will also learn important concepts of Java data types such as the default value for each data type and the maximum and minimum values they can hold.

Data Types defines the value that a java variable can take. Once the data type is defined in Java, the variable can’t take any other value, for example, if we declare a variable as boolean, it can only store boolean value. We can’t assign any other type (e.g. int, double etc.) Note that using default values is considered a bad programming practice and should be avoided when developing applications.

Data Types in Java

On a high level, there are 2 types in the Java data types.

  1. Primitive data type.
  2. Non-primitive data type.

Java is a statically typed language. In a statically typed language, the data type of the variable is known at the compile time.This means compiler will create warning in case the type is not matching with the data type. Take a look at the following error by compiler:

Data Types in Java

In above case, we tried to assign 1 to our boolean field and the compiler raised an error. This help us prevented an error which can cause a lot of issue in a real world case.

1. Primitive Java Data Types

Primitive data types are Java data types that come with the programming language by default and Java has eight of them.Note that since Java is statically typed the data types must be declared before they are used and this involves including a variable name and its type.The type is a special keyword that is recognized by the compiler and should not be used as a variable name. We will learn how to declare the 8 primitive data types in Java and also the values available to allocate to them

1.1. byte

This is a signed data type meaning it can hold both negative and positive values and the terminology that we will encounter most is two’s complement.The data type length is 8 bits and the signed value is obtained by inverting the bits then adding one.The minimum value a byte can have is -126 or -2 7<sup> </sup>and the maximum value is 127 or 27-1 and the compiler will reject any value that is not within the range.

When working with large arrays, the byte Java data type comes in handy to save on memory being used.For example, a byte array of size 10 will use 10 bytes of memory but an int array of size 10 will use 40 bytes of memory.The values must be within -128 and 127 to avoid overflow.The following is the syntax of how to declare a byte in Java and the default value is 0 if a value is not initialized.

public class DataTypes {
    public static void main(String[] args) {
        //maximum byte value
        byte maxByteValue = 127;
        System.out.println(maxByteValue);

        //minimum byte value
        byte minByteValue = -128;
        System.out.println(minByteValue);
    }
}

1.2. short

This is a 2’s complement data type that occupies 16 bits and can also be used when working with large arrays to save on memory where necessary. The minimum value that the short data type can hold is -32,768 and the maximum value is 32,768.

When a value is not initialized during declaration it uses the default value which is 0. The syntax of declaring a short data type is as shown below and any value initialized must be within the minimum and maximum values inclusive.

public class DataTypes {
    public static void main(String[] args) {
        //maximum short value
        short maxShortValue = 32767;
        System.out.println(maxShortValue);

        //minimum short value
        short minShortValue = -32768;
        System.out.println(minShortValue);

    }
}

1.3. int

Int is one of the Java data types that is used by most developers while developing programs or web applications.It is a signed data type that has a size of 32 bits and the minimum value that it can hold is -231 and the maximum value is 231–1. The int data type has a wrapper class called Integer that provides methods to perform operations on unsigned values.

Starting from Java 8 you can use an int of size 32 bits with a minimum value of 0 and a maximum value of 232-1 to work with unsigned values. The default value for the int data type is 0 and below is the syntax of how to declare an int.

public class DataTypes {
    public static void main(String[] args) {
        //maximum int value
        int maxIntValue = 0x7fffffff;
        System.out.println(maxIntValue);

        //minimum int value
        int minIntValue = 0x80000000;
        System.out.println(minIntValue);
    }
}

1.4. long

This is a two’s complement Java data type that uses 64 bits and the minimum value that it can hold is -263 and the maximum value is 263-1. We can represent a long value of 64 bits with a minimum value of 0 and a maximum value of 264-1 starting from Java 8 onward. The data type is signed and provides the capability to work with unsigned values by leveraging a wrapper class called Long.

When we are using an int data type and the value we want to use is larger than the maximum value of int we can use long in this case. The default value is 0L and below is a syntax of how to declare a long data type in Java and note that the value must be within the minimum and maximum values that a long can hold to avoid overflow.

public class DataTypes {
    public static void main(String[] args) {
        //maximum long value
        long maxLongValue = 0x7fffffffffffffff L;
        System.out.println(maxLongValue);

        //minimum long value
        long minLongValue = 0x8000000000000000 L;
        System.out.println(minLongValue);
    }
}

1.5. float

The float data types in Java is a single-precision data type of size 32 bits and is defined in IEEE 754 standard for Binary Floating-point Arithmetic. Single precision means the number of bits used to represent the floating-point number and float uses 32 bits. According to IEEE 754 standard, it not only includes positive and negative numbers but also sign, magnitude, positive and negative zeros, positive and negative infinities, and Not-a-Number values denoted as NaN.

The NaN is used to represent certain operations that are not valid such as division by zero. It is crucial to know these values do exist, but in this tutorial, we will only cover the minimum and maximum values because other values are used on rare occasions.The largest positive finite value that a float can hold is (2-223).2127 and the smallest positive nonzero value is 2-149.

When working with floating-point values float data type is considered compared to double as it saves on memory when working with large arrays. The default value of float is 0.0f and since certain operations require precise values such as currency BigDecimal should be used in such situations but not float. Below is the syntax used to declare a float data type and note that the compiler will interpret it as a double if we don’t add an f after initialization.

public class DataTypes {
    public static void main(String[] args) {
        //maximum float value
        float maxFloatValue = 0x1.fffffeP + 127 f; // 3.4028235e+38f
        System.out.println(maxFloatValue);

        //minimum float value
        float minFloatValue = 0x0 .000002 P - 126 f; // 1.4e-45f
        System.out.println(minFloatValue);
    }
}

1.6. double

This Java data type is a floating point also defined by IEEE 754 and uses 64 bits to represent the floating-point number hence the name double precision.When working with decimal values double is the preferred choice and it should not be used with values that require precision such as currency.

Since double is also defined in IEEE 754 as we have seen with the float data type it not only has positive and negative values but also sign, magnitude, positive and negative zeros, positive and negative infinities, and Not-a-Number values (NaN). The largest positive finite value of type double is (2-2-52).21023 and the smallest positive nonzero value of type double is 2-1074.

The default value for the double data type is 0.0d and it is a good practice to add a d after initialization so that the compiler interprets that our value is of type double. Below is the syntax that we use to declare a value of type double.

public class DataTypes {
    public static void main(String[] args) {
        //maximum double value
        double maxDoubleValue = 0x1.fffffffffffffP + 1023;
        //1.7976931348623157e+308
        System.out.println(maxDoubleValue);

        //minimum double value
        double minDoubleValue = 0x0 .0000000000001 P - 1022; // 4.9e-324
        System.out.println(minDoubleValue);
    }
}

1.7. boolean

This is a data types in java that is used to control the flow of a program based on whether a result returned was true or false. This data type can only have true or false values and the default value it provides is false if neither of them is initialized. The size of boolean is not precisely defined but it only stands for one bit of information. Below is a syntax of how to declare a value of type boolean.

public class DataTypes {
    public static void main(String[] args) {
        //boolean true value
        boolean valid = true;
        System.out.println(valid);

        //boolean false value
        boolean inValid = false;
        System.out.println(inValid);

    }
}

1.8 char

This Java data types is used to represent a single character and the default character that it provides out of the box is ‘\u0000’. The minimum value is the smallest value of type char and the maximum value is the largest value of type char which are ‘\u0000’ and ‘\uffff’ respectively and note that the values are inclusive. Below is an example showing the syntax of how to declare a value of type char and adding more characters is interpreted as a string literal by the compiler.

public class DataTypes {
    public static void main(String[] args) {
        //maximum character value
        char maxCharValue = '\uFFFF';
        System.out.println(maxCharValue);

        //minimum character value
        char minCharValue = '\u0000';
        System.out.println(minCharValue);
    }
}

To give us a complete overview of the different primitive data types in Java, here is a complete example for your reference.

package com.javadevjournal;

public class DataTypes {
    public static void main(String[] args) {
        //        //maximum byte value
        byte maxByteValue = 127;
        System.out.println(maxByteValue);

        //minimum byte value
        byte minByteValue = -128;
        System.out.println(minByteValue);

        //        //maximum short value
        short maxShortValue = 32767;
        System.out.println(maxShortValue);

        //minimum short value
        short minShortValue = -32768;
        System.out.println(minShortValue);


        //maximum int value
        int maxIntValue = 0x7fffffff;
        System.out.println(maxIntValue);

        //minimum int value
        int minIntValue = 0x80000000;
        System.out.println(minIntValue);

        //maximum long value
        long maxLongValue = 0x7fffffffffffffff L;
        System.out.println(maxLongValue);

        //minimum long value
        long minLongValue = 0x8000000000000000 L;
        System.out.println(minLongValue);

        //maximum float value
        float maxFloatValue = 0x1.fffffeP + 127 f; // 3.4028235e+38f
        System.out.println(maxFloatValue);

        //minimum float value
        float minFloatValue = 0x0 .000002 P - 126 f; // 1.4e-45f
        System.out.println(minFloatValue);

        //maximum double value
        double maxDoubleValue = 0x1.fffffffffffffP + 1023; // 1.7976931348623157e+308
        System.out.println(maxDoubleValue);

        //minimum double value
        double minDoubleValue = 0x0 .0000000000001 P - 1022; // 4.9e-324
        System.out.println(minDoubleValue);

        //boolean true value
        boolean valid = true;
        System.out.println(valid);

        //boolean false value
        boolean inValid = false;
        System.out.println(inValid);

        //maximum character value
        char maxCharValue = '\uFFFF';
        System.out.println(maxCharValue);

        //minimum character value
        char minCharValue = '\u0000';
        System.out.println(minCharValue);
    }
}

2. Non-Primitive Data Types in Java

Non-primitive Java data types are also known as reference types which means that the actual data is stored somewhere else and the object acts as a pointer to it. These reference types will contain null as their default values and will throw a NullPointerException the object is not initialized with a value.

2.1. class

This data type acts as a blueprint for creating custom objects and can inherit behaviors from other classes. A class has its properties and behaviors and it is from these concepts that we can solve real-world problems through simulation of real objects. Below is a syntax for creating a Java class with a custom constructor to help in creating objects from the blueprint.

class Customer {
    private String firstName;
    private String lastName;

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

2.2. interface

An interface consists of abstract fields and methods and these are contracts that must be implemented by the class. An interface is not used to create objects but can be used to achieve multiple inheritances in Java because we can not inherit from more than one class. Below is the syntax of creating an interface with one abstract method that must be implemented by the service implementation class.

interface CustomerService {
    Customer findCustomer();
}

2.3. Object

Note that there is an object class which is the super class of all the classes in Java but we are not talking about that object in this case. An object is an instance of a class and is created using the new keyword as shown below.

public class DataTypes {
    public static void main(String[] args) {
        Customer customer = new Customer("john", "doe");
        System.out.println(customer);
    }
}

2.4. String

A string is by default a class in Java and any character strings created to represent an instance of this class. A string is immutable meaning that its values cannot be changed once they are created but string buffers support mutable strings. We can represent an array of characters as a string of characters because of the immutability factor of string that allows sharing.

Below is an example of the syntax used to declare a value of type string and note that a null value is also assignable but will throw a NullPointerException.

public class DataTypes {
    public static void main(String[] args) {
        String stringValue = "This is a string";
        System.out.println(stringValue);

    }
}

Here is a complete example of the different Non-primitive data types in Java for your reference:

package com.javadevjournal;

public class DataTypes {
    public static void main(String[] args) {
        Customer customer = new Customer("john", "doe");
        System.out.println(customer);

        Customer[] customers = {
            new Customer("mary", "public"),
            new Customer("peter", "parker")
        };
        System.out.println(Arrays.asList(customers));




        String stringValue = "This is a string";
        System.out.println(stringValue);

    }
}

class Customer {
    private String firstName;
    private String lastName;

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "Customer{" +
            "firstName='" + firstName + '\'' +
            ", lastName='" + lastName + '\'' +
            '}';
    }

}

interface CustomerService {
    Customer findCustomer();
}

class CustomerServiceImpl implements CustomerService {
    // method to retrieve Customer from a data source
    @Override
    public Customer findCustomer() {
        return null;
    }
}

Summary

In this tutorial we covered the different data types in Java, we have learned the basics of Java primitive and non-primitive data types where on the first section we covered byte, short, int, long, float, double, boolean, and char data types. We finally went through the primitive data types which included class, interface, object, array, and string. For source code , please check our GitHub Repository

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.