Primitives in Java

by Dimitris Tasios
59 views

In this article, we will learn about which the primitives in Java are (also called primitive data types in Java), how and when to use each of them.

1. Which are the primitives in Java?

A primitive data type describes the type a variable can be. They represent raw, non-null values, like a number or a character. There are eight primitives in Java: byte, short, int, long, float, double, char, and boolean.

Before digging into each of them, let’s have a look at an example raw value for each primitive, their size in bits, and their default value when we don’t declare a raw value for them.

Primitive TypeDefault ValueSize (bits)Example
byte08byte myByte = 24;
short016short myShort = 1000;
int032int myInt = 1234567890;
long064long myLong = 555444333222111L;
float0.032float myFloat = 0.342F;
double0.064double myDouble = 4534.56731;
char\u000016char myChar = 'D';
booleanfalse1boolean myBoolean = true;
Figure 1. A quick overview of primitives in Java

Note that String is not a primitive type but an Object which happens to also be predefined, just like the primitives.

2. Analyzing the primitives in Java

Now, it’s time to take a deeper look into each primitive and explain them a bit further.

It should be noted that the default variable of a primitive type cannot be set to local variables (variables inside a method), but only to class variables. Because of that, all variables declared with a default variable, in the following examples, will be class variables. Also, due to the fact that these default variables are used in a static method (main), they have to be declared static.

We can categorize those eight primitive types into three categories: Integer, Floating-Point and Other primitive data types.

2.1 Integer Primitives in Java

Firstly, let’s begin with integer primitives. These primitive data types represent signed, integer values. A signed value is one that can accept both positive and negative numbers. We cannot assign a decimal (floating-point) value to an integer without converting it to an integer first. By doing that, the decimal part will be truncated, like so:

    private static void convertDecimalToInteger() {
        int anInt = (int) 5.6;

        System.out.println("convertDecimalToInteger()");
        System.out.println("Converting 5.6 to integer is " + anInt);
        System.out.println();
    }

Output

convertDecimalToInteger()
Converting 5.6 to integer is 5

2.1.1 byte

A byte is the most compact (in size) integer primitive data type that we can use. It accepts small values, from -28 to 28-1. We will explain later what happens if we put a number outside this range.

public class JavaPrimitivesExamplesClass {
    static byte defaultByte;

    private static void byteExample() {
        byte myByte = 33;

        System.out.println("Assigned value: " + myByte);
        System.out.println("Default value: " + defaultByte);
    }

    public static void main(String[] args) {
        byteExample();
    }
}

Output

byteExample()
byte assigned value: 33
byte default value: 0

2.1.2 short

A short accepts values from – 216 to 216-1.

    private static void shortExample() {
        short myShort = 500;

        System.out.println("shortExample()");
        System.out.println("short assigned value: " + myShort);
        System.out.println("short default value: " + defaultShort);
        System.out.println();
    }

Output

shortExample()
short assigned value: 500
short default value: 0

2.1.3 int

An int is the most commonly used integer primitive data type. It accepts values from – 232-1 to 232-1.

    private static void intExample() {
        int myInt = 100000;

        System.out.println("intExample()");
        System.out.println("int assigned value: " + myInt);
        System.out.println("int default value: " + defaultInt);
        System.out.println();
    }

Output

intExample()
int assigned value: 100000
int default value: 0

2.1.4 long

A long can hold values between – 264 and 264-1. In order for an integer to be treated as a long, we must add the letter “L” at the end of the number (capital or lowercase letter). Otherwise, it will be treated as an int.

    private static void longExample() {
        long myLong = 3000000000l;

        System.out.println("longExample()");
        System.out.println("long assigned value: " + myLong);
        System.out.println("long default value: " + defaultLong);
        System.out.println();
    }

Output

longExample()
long assigned value: 3000000000
long default value: 0

2.2 Floating-Point Primitives in Java

Moving on, these primitives represent decimal, signed numbers. An integer primitive can be converted to a floating-point primitive. By doing so, a decimal part is appended to the integer, since, for example, 5 = 5.0.

    private static void convertIntegerToDecimal() {
        double aDouble = 42;

        System.out.println("convertIntegerToDecimal()");
        System.out.println("Converting 42 to integer is " + aDouble);
        System.out.println();
    }

Output

convertIntegerToDecimal()
Converting 42 to integer is 42.0

2.2.1 float

A float stores numbers in 32 bits. Like long, we have to add the letter “F” (capital or lowercase letter). Otherwise, it will be treated as a double.

    private static void floatExample() {
        // The following will not compile without the "f", because the compiler thinks it's a double.
        float myFloat = -432.660f;

        System.out.println("floatExample()");
        System.out.println("float assigned value: " + myFloat);
        System.out.println("float default value: " + defaultFloat);
        System.out.println();
    }

Output

floatExample()
float assigned value: -432.66
float default value: 0.0

2.2.2 double

A double offers double the precision of a float, storing numbers in 64 bits. We may or may not add the letter “D” at the end (capital or lowercase letter), since the compiler is treating decimal numbers as double by default.

    private static void doubleExample() {
        double myDouble = -432.660;

        System.out.println("doubleExample()");
        System.out.println("double assigned value: " + myDouble);
        System.out.println("double default value: " + defaultDouble);
        System.out.println();
    }

Output

doubleExample()
double assigned value: -432.66
double default value: 0.0

2.3 Other Primitives in Java

Lastly, this section includes primitive data types that are not numeric.

2.3.1 char

A char represents a single Unicode character. Furthermore, its size is 16 bits so, its possible values are within 0 and 65535 (or 216, inclusive), or from 0x0000 to 0xFFFF in hexadecimal. By using the Unicode table and converting a character’s hex (a number in the power of 16) value into decimal (a number in the power of 10), we can print any of those char values we wish.

Now, there are two ways to declare a char variable:

  • With a character enclosed in single quotation marks (‘).
  • With an integer that is within the aforementioned range, with the help of the Unicode table. For instance, we can look at the table for the pi’s character hex code, convert that to decimal and assign it to a variable.
    private static void charExample() {
        char myChar = 'p';
        char piChar = 960; // hex value is 03C0 (0x03C0), so decimal value is 960

        System.out.println("charExample()");
        System.out.println("char assigned value: " + myChar);
        System.out.println("char pi: " + piChar);
        System.out.println("char default value: " + defaultChar);
        System.out.println();
    }

Output

charExample()
char assigned value: p
char pi: π
char default value:  

The default value of a char variable is the Unicode character for null, with a hex code of 0x0000. As such, this character has no printable value, hence the empty space in “char default value: ” statement in the output.

2.3.2 boolean

Last but certainly not least, one of the most simplistic, yet vital, primitive data types in Java is boolean, taking its name from George Boole. A boolean is a simple value that accepts only two values: true or false. Because of that, it is stored in a single bit (1 bit). Boolean values are the cornerstone of altering the flow of the program, for example in an if, for, or while statement.

Now, a boolean variable does not have to be explicitly assigned with either a true or false keyword. Instead, you have the ability to assign a mathematical expression, like equality or inequality, and depending on the expression’s validity, the variable will be either assigned with a true or false value.

    private static void booleanExample() {
        boolean myBoolean = true;
        boolean threeGreaterThanTwoBoolean = 3 > 2; // a wrong mathematical inequality will assign false to the variable

        System.out.println("booleanExample()");
        System.out.println("boolean assigned value: " + myBoolean);
        System.out.println("boolean 3 > 2? : " + threeGreaterThanTwoBoolean);
        System.out.println("boolean default value: " + defaultBoolean);
        System.out.println();
    }

Output

booleanExample()
boolean assigned value: true
boolean 3 > 2? : true
boolean default value: false

3. Getting out of range

As we have mentioned for each of the primitives in Java, there is a specific range that they allow values. So, what would happen if we assigned a value to a variable, that’s either too large or too small for the variable’s type?

The answer is that the variable will either overflow (if it’s too large) or underflow (if it’s too small). What this means is that the variable cannot be correctly represented by the number of bits it has available, leading to incorrect and unexpected results.

    private static void overflowAndUnderflowExample() {
        byte maxByte = Byte.MAX_VALUE; // maximum value of byte

        System.out.println("overflowAndUnderflowExample()");
        System.out.println("maxByte before overflow: " + maxByte);

        maxByte++; // increase its value by one, causing the variable to overflow

        System.out.println("maxByte after overflow: " + maxByte);

        int minInt = Integer.MIN_VALUE; // minimum value of int
        System.out.println("minInt before underflow: " + minInt);

        minInt--; // decrease its value by one, causing the variable to underflow

        System.out.println("minInt after underflow: " + minInt);

        System.out.println();
    }

Output

overflowAndUnderflowExample()
maxByte before overflow: 127
maxByte after overflow: -128
minInt before underflow: -2147483648
minInt after underflow: 2147483647

Let’s see what happened.

  • Overflow:
    • Line 2: we set maxByte the maximum value it can hold (127 in decimal, 11111111 in bits), with the help of the built in MAX_VALUE variable, available for all primitives in Java, except boolean.
    • Line 7: we add one more to maxByte (128 in decimal 100000000 in bits). The problem with that is that 128 requires 9 bits, but byte only has eight. So, the leftmost bit is ignored, giving us the value of -128 (00000000 in bits, since it’s signed). In other words, during an overflow, when you go beyond the maximum value, the variable goes back to the minimum value.
  • Underflow: On the other side:
    • Line 11 we set minInt the minimum value it can hold (32 zeroes in bits), with the help of the built in MIN_VALUE variable.
    • Line 14 we subtract one more to minInt, taking us straight to the maximum value, the opposite of the overflow’s case.

4. Conclusion

By now, you should be able to have understood all there is to know about primitives in Java. You can find the source code on our GitHub page.

5. Sources

[1]: Primitive Data Types – Oracle

[2]: Unicode Character Table

[3]: George Boole – Wikipedia

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

3 comments

https://casinovavada.Blogspot.com/2021/12/Blog-post.html January 10, 2022 - 16:28

Hi, i feel that i saw yoou viwited my web site so i got here
to return the want?.I’m attempting too to find things to improve myy site!I suppose its ok to use a few
off your concepts!! https://casinovavada.blogspot.com/2021/12/blog-post.html

Reply
Georgios - Nikolaos Palaiologopoulos January 10, 2022 - 20:01

Hello,
Of course as long as you refer Dimitrios Tasios’ article, we are okay 🙂

Reply
Josue Neundorfer April 29, 2022 - 14:22

A motivating discussion is worth comment. I do think that you ought to publish more about this subject matter, it might not be a taboo matter but generally people do not discuss such subjects. To the next! Kind regards!!

Reply

Related Posts