Data Types in Java

Data Types in Java are types of data which can be stored in a variable. Data types in Java have two types:

  1. Primitive Data Types
  2. Non-Primitive Data Types

Primitive Data Types

Java has 8 primitive data types. These data types are the building blocks of data manipulation. These data types are the most basic data types within Java.boolean

  1. boolean
  2. byte
  3. char
  4. short
  5. int
  6. long
  7. float
  8. double

Boolean (boolean)

The boolean data types is known as the decision maker data type. Either the value of a boolean can be true or false. That’s it! Nothing else. Boolean can store only 2 states which can be either true or false. Boolean is the best way to track a condition or turn things on/off in the world of programming.

JAVA PROGRAM EXAMPLE

public class Main {
    public static void main(String[] args) {

        // Declaring boolean data type
        boolean isEqual;

        double valueOne = 100.0;
        double valueTwo = 100.0;

        if (valueOne != valueTwo) {
            isEqual = false;
        } else {
            isEqual = true;
        }

        System.out.println(isEqual);

    }
}

Output

 true

Challenge

Try changing values of valueOne and valueTwo and run the program. Run the program and let us know the output in the comments.


Byte (byte)

The byte data type is an 8-bit signed 2’s complement integer. The value of byte ranges from -128 to 127 which means if you try to initialize a value of +128 or -129, there will be an error. The range of these data type make them unique to one another. These ranges are best for practicing limits for your memory. When working on a production app or a website, there will be conditions where user will be limited to a certain amount of memory which can help save databases from overflowing. Byte data types is used to save memory within large arrays where memory efficiency & limitation of memory is most required. Byte data type is 4 times smaller than an integer.

JAVA PROGRAM EXAMPLE

public class Main {

    public static void main(String[] args) {

        // Declaring byte data type
        byte lowestValue = -128;
        byte highestValue = 127;

        System.out.println("The lowest value in byte is " + 
                lowestValue +" while the highest is " 
                + highestValue);
    }
}

Output

The lowest value in byte is -128 while the highest is 127

Challenge

Try changing the values to a different number and perform an arithmetic operation between them.


Short (short)

Short is a 16 bit signed 2’s complement integer. The value of short ranges between -32,768 to +32,767. The short data type is 2 times smaller than the integer data type. As every data type has its range, short is also considered to limit memory according to required conditions.

JAVA PROGRAM EXAMPLE

public class Main {

    public static void main(String[] args) {

        // Declaring short data type
        short lowestValue = -32768;
        short highestValue = 32767;

        System.out.println("The lowest value in short is " +
                lowestValue + " while the highest is "
                + highestValue);

        // Applying arithmetic operation
        short valueOne = 20000;
        short valueTwo = 21000;

        short result = (short) (valueTwo - valueOne);
        System.out.println("The result of subtracting is "
                + result);
    }
}

Output

The lowest value in short is -32768 while the highest is 32767
The result of subtracting is 1000

Challenge

Try using a condition within the arithmetic operation. If the value is less than 500 print your name and if greater than 800 then print the name of your most favorite person.


Integer (int)

An integer is the most common data type in Java. An integer is a 32 bit signed 2’s complement integer. The range of int lies between 2,147,483,648 to 2,147,483,647. Huh! Who’s going to learn that. No one and you don’t need to until you’re Cassandra Cillian but really you don’t need to because as this is the most common data type in java. An integer data type is not a good option for limited memory. It is a data type which has a very long range so it is better to use it freely rather than limiting it.

JAVA PROGRAM EXAMPLE

public class Main {
    public static void main(String[] args) {

        // Declaring byte data type
        int lowestValue = -2147483648;
        int highestValue = 2147483647;

        System.out.println("The lowest value in int is " +
                lowestValue +" while the highest is "
                + highestValue);

        int valueOne = 823;
        int valueTwo = 414;

        int result = valueOne * valueTwo;
        if (result > 50000) {
            System.out.println("Result is too large!");
        } else {
            System.out.println("The result of multiplying is "
                    + result);
        }
    }
}

Output

The lowest value in int is -2147483648 while the highest is 2147483647
Result is too large!

Challenge

Try applying multiple conditions with multiple outputs to the console. For example, if the result is less than 10,000 then print something else, and if the result is greater than 500 than print something else and keep on changing values to make every if case true.


Long (long)

A long data type is a 64-bit 2’s complement integer. The range of long is obviously very long and lies between -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. The default value is said to be 0. What is the default value? What a data type is not initialized then it is set to its original/default value in which case long’s default value is 0. A long data type is preferred when execution is based on time/date.

JAVA PROGRAM EXAMPLE

public class Main {
    public static void main(String[] args) {

        // Declaring long data type and initializing it to
        // get the current time from the System
        long currentTime = System.currentTimeMillis();
        System.out.println("System based time: " + currentTime);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(currentTime);

        SimpleDateFormat simpleDateFormat =
                new SimpleDateFormat("YYYY/MM/dd HH:MM");
        System.out.println("Calendar based time: " +
                simpleDateFormat.format(calendar.getTime()));
    }
}

Output

System based time: 1556181144137
Calendar based time: 2019/04/25 13:04

Challenge

Try changing the date format into finding the date only rather than both the time and date.


Float (float)

The float data type is a single-precision (.0) 32-bit IEEE 754 floating point. The float data type has no ranges. It is said to be unlimited, capable of any kind of decimal-based number. A float data type is recommended if your saving memory in large arrays of floating point numbers. The default value of float is 0.0f in Java.

JAVA PROGRAM EXAMPLE

public class Main {
    public static void main(String[] args) {

        // Declaring byte data type
        float valueOne = 200.5f;
        float valueTwo = 100.5f;

        float result = valueOne * valueTwo;
        if (result > 50000) {
            System.out.println("Result is too large!");
        } else {
            System.out.println("The result of multiplying is "
                    + result);
        }
    }
}

Output

The result of multiplying is 20150.25

Challenge

Try using a condition in which if the number after the decimal point is greater than 25, print your favorite Baseball team.


Double (double)

The double data type is a double-precision 64 bit IEEE 754 floating point number. Its range is also unlimited as a float. A double data type is mostly preferred when working with a number with or without decimal point number as float data type requires an ‘f’ at the end of every assigned value to notify the data type. The default value for double data type is 0.0 / 0.0d.

JAVA PROGRAM EXAMPLE

public class Main {
    public static void main(String[] args) {

        // Declaring double data type
        double valueOne = 200;
        double valueTwo = 100.5;
        
        double result = valueOne * valueTwo;
        if (result > 500) {
            for (int i = 0; i < 5; i++) {
                System.out.println("Running a loop for the " + i);
            }
        } else {
            System.out.println("The result of multiplying is "
                    + result);
        }
    }
}

Output

Running a loop for the 0
Running a loop for the 1
Running a loop for the 2
Running a loop for the 3
Running a loop for the 4

Challenge

Try changing the loop into a while loop.


Char (char)

The character data type is a single 16-bit Unicode character which stores characters within a variable. It’s value ranges between 0 to 65,535 but the values aren’t numeric. The values within a character data type are mixed with numeric and alphabets. The values within a char data type start from ‘u\0000’ (0) to ‘\uffff’ (65,535) as mentioned. To write an alphabet within a char data type, it is covered within single quotes.

Java Program Example

public class Main {
    public static void main(String[] args) {

        // Declaring char data type
        char number = '\u0031';
        char alphabet = 'a';
        char unicode = '\u002A';

        System.out.println("Characters have numbers: "
                + number);
        System.out.println("Characters have alphabets: "
                + alphabet);
        System.out.println("Characters have unicode: "
                + unicode);
    }
}

Output

Characters have numbers: 1
Characters have alphabets: a
Characters have unicode: *

Challenge

Try writing your name by storing Unicode characters within an array and printing them on the console.


Non-Primitive Data Types

We will only discuss about the two most important Non-primitive data types in Java which are String & Array.

String (String)

A string data type is the most used data type in Java. A string is a collection of characters within an array. A string is also known as String literals which means the same as I said. To initialize a String it should be enclosed within double quotes. A number within the enclosed double quotes will be considered a string, not a number so no arithmetic operations can be performed in such cases.

JAVA PROGRAM EXAMPLE

public class Main {
    public static void main(String[] args) {

        // Declaring String data type
        String name = "Arslan Mushtaq";
        String title = "Mr.";
        String occupation = "Android App Developer";
        String contact = "email@gmail.com";

        System.out.println(title + " " +
                name + " " +
                "is an " + occupation +
                ". Contact him at " + contact);
    }
}

Output

Mr. Arslan Mushtaq is an Android App Developer. Contact him at email@gmail.com

Challenge

Try changing every string into your own data and add your favorite car as a String. Print it in the console.


Arrays

Arrays

In Java, Arrays are objects in which similar data types are stored. Arrays are limited to a similar data type, multiple data types cannot be stored within an array. To declare an array the chosen data type is ended with square brackets ([]) to notify that an Array is being initialized. An Array can either contain limited elements of a single data type or unlimited depending on the need of the program. The index for the Array starts at 0 so if there are 4 elements in an array, the count will start from 0, 1, 2, 3, which are four but starting with 0.

JAVA PROGRAM EXAMPLE

public class Main {
    public static void main(String[] args) {

        // Declaring String data type
        String[] stringArray = {"Jack", "Robert", "Elise", "Mary"};
        int[] integerArray = {2, 3, 4, 5};
        char[] charArray = {'H', 'e', 'l', 'l', 'o'};

        // String Array Manipulation
        System.out.println("Length of String array: " +
                stringArray.length);
        System.out.println("Calling Robert: " +
                stringArray[1]);
        for (String s : stringArray) {
            if (s.startsWith("R") || s.startsWith("M")) {
                System.out.println(s + " is absent");
            } else {
                System.out.println(s + " is present");
            }
        }

        // Integer Array Manipulation
        int sum = 0;
        for (int i : integerArray) {
            sum = sum + i;
        }
        System.out.println("Sum of integerArray: " +
                sum);
        
        // Character Array Manipulation
        for (char c : charArray) {
            System.out.print(c);
        }

    }
}

Output

Length of String array: 4
Calling Robert: Robert
Jack is present
Robert is absent
Elise is present
Mary is absent
Sum of integerArray: 14
Hello

Challenge

Try printing all the numbers within int array and use 2 new arrays and manipulate them.

This is all for today and I hope you have learned about Java data types. If you’re a beginner and you’re having a difficult time understand the programming code blocks then don’t worry, keep doing them. They are different parts of Java Programming which you will be learning soon. Try taking the challenges and post the output in the comments.

Related:

  • Conditional Statement in Java
  • Loops in Java