Categories
java

Java Data Types: A Comprehensive Guide For Beginners

It is so important to learn the Java Data Types because data types are indispensable in Java. This guide will help you learn the Java Data Types in the easiest way possible.

So without further delay, let’s jump into the topic.!

Previous Topic: Java Variables

Next Topic: Java Class  & Java Objects

Page Contents

Java Data Types

A Data type as the name suggests is the type of data item.

For example, Digits (369,999), Characters (‘G’, ‘E’, ‘E’, ‘K’, ‘Y’), Strings (“Data Types in Java”, “Learn Java Data Types Fast”).

‘Digit’, ‘Character’, ‘String’ all are the data types of the values. Each data-type by its name tells us which type of data you can store or assign to them.

So, when I say ‘it’s a digit.!‘, you know which type of data I am talking about.

Just like this, Java also has some pre-defined words (Java keywords) for each of the data types.

In Java, whenever you declare a variable or a constant, it’s mandatory to provide the data type first.

There isn’t anything that is type-less in Java. You can’t declare something that has no data type in Java. Everything must and will have a data type. Whether it’s a digit or a string or an object, etc.

Before moving on to the data types in Java, let me give you a brief idea about how data is represented on a computer.

Well, why do you need to read about binary and bits?

You will understand it while you read the next section in this guide.

Binary and Bits

In computers, data is represented as 0s and 1s. This is known as the binary number system.

Binary means something that involves two things. Here the two things are 0 and 1. So this is a base-2 number system.

Computers stores data in binary format, no matter whether it’s a digit, a string, a song, or an image.

So how do we measure the size of computer data?

We measure the size of any data in computers using bits.

A bit is the smallest unit of storage in computers. ‘bit’ is the short form of binary digit.

A bit stores two numbers. One at a time. That is 0 or 1. A bit is like a switch. A switch can be on or off. Right?

Since the bit is the smallest unit to represent data, it has been grouped together to represent large data easier.

For example, a group of 4 bits is called a nibble. For 8 bits, we call it a byte.

So, 4 bits = 1 nibble.

8 bits = 2 nibble = 1 byte.

Just like that.!

One byte is still tiny. Therefore, bytes are grouped as well.

It is not a good idea to group just 8 bytes or 10 bytes to represent large-sized data. Right?

So 1024 bytes are grouped and called a KiloByte (KB).

It doesn’t stop there.

1024 KB = 1 MegaByte (MB).

1024 MB = 1 GigaByte (GB).

1024 GB = 1 TeraByte (TB).

1024 TB = 1 PetaByte (PB).

The list goes a little more. But you got the idea. Right?

You don’t have to think about KiloBytes or MegaBytes. You just need to understand bits and bytes for now.

I have mentioned above that a bit can store two values, 0 or 1.

So how many values 2 bits can hold?

1 bit = 2 values.

Then 2 bits = 2 * 2 = 4 values. Four values mean 4 different combinations (binary representation) of 0s and 1s.

 

Using these four combinations of 1s and 0s, 2 bits can represent 4 unique values. The values can be anything like numbers, characters, etc.

So what about 3 bits?

It is 2*2*2 or 23 = 8 unique binary representations = 8 unique values.

 

Well, then how about 1 byte (8 bits)?

It is 2= 256. Which means 1 byte can represent 256 different values.

Ok then.!

Now, let me give you an overview of the various categories of Java Data Types.

There are two major categories of Java data types. They are Primitive Data Types and Non-Primitive Data Types (Reference Types).

Let’s look into both of them in-depth.

First, let’s look into the primitive Java data types.

Primitive Java Data Types

Primitive data types have the most basic characteristics in Java.

Primitive data types have no object-oriented features attached to them, even though Java is all about objects.

Maybe that’s why they named it ‘primitive‘.

Primitive data types specify two thingsType of the data and its size.

Size means how much memory-space a data type takes.

There are 8 primitive data types in Java.

They are byte, short, int, long, float, double, boolean, and char. These are the keywords to declare primitive Java data types.

Primitive data types are categorized into two types. Numeric data types and Non-numeric data types.

boolean and char fall under Non-numeric data types.

Numeric data types are divided into two. Integer type data types and Floating-Point type data types.

Integer types values, as the name suggests, is to contain integers. Integers are numerical values, without a decimal/fractional part.

Floating-Point type values are the straight opposite to Integer values. Floating-Point type values contain the decimal/fractional part. The decimal point can be anywhere within the number, i.e., the decimal point floats within the number. Hence why it is called Floating-Point.

byte, short, int, and long are the Integer type data types.

float and double are the Floating-Point type data types.

Check out the below picture to understand it more clearly.

Now, it’s time to check out the Primitive Java data types one-by-one.

I would like to start with the Numeric data types. Let’s proceed from the smallest to the largest numeric data type.

Byte

The byte data type stores the numbers range from -128 to +127 in Java. The byte data type is the smallest numeric data type in Java in terms of size.

The size of the byte data type equals its name. i.e., one byte (8 bits). So, it can store 2 = 256 numbers that include 128 negative numbers, 127 positive numbers, and zero.

Note: Java numeric data types store negative numbers and positive numbers. With integers, it is half negative numbers and half -1 positive numbers. The count of positive numbers is 1 less than the count of negative numbers (This is to include zero).

Now let’s declare some byte variables.

A simple byte variable declaration looks like below.

byte geeky;
  • First, you enter the data type ‘byte‘.
  • Second, you enter the variable name. Here it is ‘geeky‘.
  • At last, put a semicolon, as it is a must after every Java program statement.

If you wish to assign a value to the variable, put an equal symbol after the variable name and enter the value.

That’s it.?

No. Wait.! Don’t forget to put the semicolon at the end.

Some valid examples would be as below.

 

 

byte number = 10 + 20; You can use mathematical operations on the right-hand side of the equal symbol instead of assigning a value. This example will store the sum ’30’  in the byte variable ‘number. This is the same for all the numerical Java data types.
byte number = +100; You can add a plus sign to denote positive numbers, even though it’s unnecessary in Java.

 

Now let’s see some invalid byte declaration and initialization examples.

 

Invalid declarations

 

byte byte; Why is this invalid? This is because ‘byte‘ is a Java keyword. You cannot use Java keywords as an identifier name.
Byte number Actually, this is not an invalid Java statement. But it’s definitely not a ‘byte‘ (primitive data type) variable declaration. Since Java is case-sensitive, Byte and byte are not the same. This statement has a different meaning which you will learn in the upcoming tutorials.

 

Invalid Initializations

 

byte number = -129; This is invalid because -129 is an out of range value for the byte data type.
byte number = 128; This is also invalid because 128 is also an out of range value for the byte.
byte number = 127 + 1; Here the sum is 128, So again, this is also invalid.

 

Below given is a small sample program that declares the byte variable ‘number‘, assigns the max byte value ‘127’, and prints it in the console.

 

class GeekyByte {
     public static void main(String[] args) {
         byte number = 127;
         System.out.println(number);
     }
 }

 

Let’s move on to the next primitive data type.

 

Short

Everything you read about the byte data type applies to the short data type too. The only difference is that the size of the short data type is 2 bytes (16 bits). This means short can store 216, i.e., 65536 numbers. Yes.! The range of values of short is much larger than the byte.

 

You can store numbers range from -32768 to +32767 to a short field. So, if you assign out-of-range numbers like -32769, +32768, you will get an error.

You can see some valid short variable declarations & initializations below.

Also, check out the invalid examples given below.

 

short short;  You can’t use Java keywords as identifier names.
Short number;  Short means something different from short in Java.
short number = 32767 + 1; This results in an out of range value.

short sample program is given below.

 

class GeekyShort {
     public static void main(String[] args) {
         short number = 32767;
         System.out.println(number);
     }
 }

 

Int

 

The int data type is one of the most commonly used numeric Java data types. The size of int is 4 bytes (32 bits).

 

You can store numbers ranges from -2147483648 to 2147483647 in the int data type fields.

 

The range of numbers of the int data type is considerably larger than the byte and the short.

 

Int falls into that sweet spot where you can use small numbers as well as really huge numbers. This makes int the most preferable data type to programmers.

 

But if the numbers you use fall under the range of byte data type, you must use byte. This applies to all the numeric Java data types.

 

This is because to store the number 127 or -128 you don’t have to use short or int. The byte data type is enough in this case.

 

If you use short to store the number 127, it will take 2 bytes of memory. If you use int, it will take 4 bytes of memory. Byte only takes 1 byte.

 

So it’s recommended using the appropriate data types. Never use a data type just because it is available. Use it only if you need it.

 

All the valid and invalid declarations you saw above in the short and the byte data types apply to the int data type too (except the range of values).

 

Check out the program below that prints the maximum number of int data type in the console.

 

class GeekyInt {
     public static void main(String[] args) {
         int number = 2147483647;
         System.out.println(number);
     }
 }

 

Let’s move on.!

 

Long

 

The long data type can store much larger numbers than int. The size of long is 8 bytes (64 bits). Long numbers start from -9223372036854775808 to 9223372036854775807.

 

You can use the long data type if the int data type is not sufficient for your requirements. If you deal with really large numbers, long could be absolutely useful for you.

 

An important point to note here is that when you assign a number to a long variable/constant, you might have to enter the letter ‘L‘ at the end of the number. You do that to inform the Java compiler that the number is a long value.

 

If you don’t put the ‘L‘ suffix, it will consider as an int value by default.

 

Example: long number = 2147483648L;

 

Since int is smaller compared to long, you can assign int values to the long data type.

 

Example: long number = 2147483647;

 

In the above example, 2147483647 is considered as int value and it is converted to long. Here, it is possible to skip adding the ‘L‘ suffix.

 

But When you assign a number to a long variable outside the range of the int data type, the Java compiler will throw you an error saying that the number of type int is out of range.

 

Example: long number = 2147483648; // int type out-of-range error

 

To fix this error, you must put the ‘L‘ suffix to inform the compiler it is a long value.

 

If you don’t put the ‘L‘ suffix and if the code works fine, that means you assign an int value to the long data type. You don’t have to do that. If a number fits within the int data type, then declare it as int. Never use long in such scenarios.

 

Use long data type only when the numbers you use are outside the limit of the int data type. And add the ‘L’ suffix, as mentioned.

 

You can enter the ‘L’ suffix in both lowercase and uppercase letters. Java permits both.

 

Now, let’s create a program that prints both the minimum and maximum long numbers in the console. See below.

 

class GeekyLong {
     public static void main(String[] args) {
         long longMin = -9223372036854775808L;
         long longMax = 9223372036854775807L;
         System.out.println(longMin);
         System.out.println(longMax);
     }
 }

 

I have covered all the Integer type Java data types. One more important thing to note is that the default value of all the integer types is 0.

 

Now let’s check out the floating-point Java data types. As I mentioned earlier, floating-point data types are there to store numbers with the decimal part.

 

There are 2 floating-point data types in Java. The float data type and the double data type.

 

Float

 

The float data type stores numbers range from ±1.4E-45 to ±3.4028235E38. The size of the float data type is 4 bytes (32 bits).

 

The float data type represents single-precision (32 bit) IEEE 754 standard floating-point numbers.

 

You must add the letter ‘F‘ (uppercase or lowercase) as the suffix to inform the compiler it is a float value. By default, Java considers floating-point numbers as double.

 

Example: float number = 369.12f;

 

The float data type can store 6 or 7 digits after the decimal point.

 

Example: float number = 3.1234567F;

 

You can add as many numbers after the decimal point as you can see below.

 

float number = 1.1234567891234567891234567891239876542135669874566211452236589f;

 

But the float data type takes only the first 6 or 7 fractional digits, and the last fractional digit may round-up or round-down depends on the later numbers.

 

Have a quick look at the below program that assigns the float number ‘3.2567’ to the float variable ‘number‘ and displays it in the console.

 

class GeekyFloat {
     public static void main(String[] args) {
         float number = 3.2567F;
         System.out.println(number);
     }
 }

 

Next, we have the double data type.

 

Double

 

The double data type stores numbers from ±4.9E-324 to ±1.7976931348623157E308. The double data type’s size is 8 bytes (64 bits).

 

The double data type represents double-precision (64 bit) IEEE 754 standard floating-point numbers.

 

The double data type can store 15 or 16 digits after the decimal point. So when compared to the float data type, double values are more precise.

 

Example: double number = 66.284;

 

You can use the letter ‘D‘ as the suffix with double values to inform it is a double type value to the Java compiler. This is optional as Java considers the floating-point numbers as double by default.

 

Example 1: double number = 66.24D;

 

Example 2: double number = 42.84d;

 

Even though the double values and float values are precise to a certain extent, In Java, it is not recommended to use float and double data types to deal with currency values.

 

This is because the float and the double could cause a loss of precision, which of course no one wants to happen in terms of money. To avoid this, you can use the Java BigDecimal class that you can learn here later.

 

The float and the double data type represents larger numbers using scientific notation.

 

So you can also make scientific numbers using the letter ‘E‘ (stands for the Base-10 exponent i.e., E6 = 106) in lowercase or uppercase format. For example: 10.24E2 = 1024.

 

Example 1: float number = 662.8E4f;

 

Example 2: double number = 662.8e4D;

 

It’s worth checking out the Java program below that declares four double variables, assign them values, and displays it in the console.

 

class GeekyDouble {
     public static void main(String[] args) {
         double numberOne = 3.2567891023456;
         double numberTwo = 66.284D;
         double numberThree = 26.426d;
         double numberFour = 32.66E2d;
         System.out.println(numberOne);
         System.out.println(numberTwo);
         System.out.println(numberThree);
         System.out.println(numberFour);
     }
 }

 

The default value of float and double is 0.0;

 

Use of Underscore in Numeric Java Data Types

 

Java allows using underscores within all the numeric Java data types since Java 7.

 

The purpose of this is to improve the code readability. There aren’t any other technical aspects of this.

 

You can split large numbers into small groups using underscore to make it look less complex and more readable.

 

Example: long number = 92233_7203_6854_775_807L;

 

There are some rules to use underscores with numeric types. Let’s have a look at them now.

 

byte number = _120; You can’t add an underscore at the beginning of the number.
short number = 120_; You can’t add an underscore at the end of the number.
int number = -_120; You can’t add an underscore in between the minus/plus sign and the number.
long number = 120_L; You can’t add an underscore before the suffix (L, F, D).
float number = 120._12f; You can’t add an underscore after the decimal point.
double number = 120_.12; You can’t add an underscore before the decimal point.
float number = 120.1_E2f; You can’t add an underscore before the exponent (E).
double number = 120.1E_2; You can’t add an underscore after the exponent (E).

 

All of this means just one thing. Use the underscores “between digits“. That’s it.

You can add an underscore multiple times like this 1______2_________3, even though it isn’t a good practise.

 

Now let’s look into the Non-numeric Java data types.

 

As I mentioned earlier, boolean and char are the two Non-numeric Java data types.

 

Boolean

 

The boolean data type is the smallest of all the Java data types in terms of the range of values. It can have only two values: true and false. Each value represents 1 bit of information.

 

So you could assume 1 bit as the size of boolean. But the exact boolean size isn’t properly defined anywhere (This is stated as per the Java documentation).

 

The boolean data type is used to set flags to execute program statements based on true or false conditions. The default value of boolean is false.

 

Note: Flags are variables we use in programming to notify the program that certain conditions are met.

 

Example: boolean flag= true;

 

class GeekyBoolean {
     public static void main(String[] args) {
         boolean booleanFlag = true;
         System.out.println(booleanFlag);
     }
 }

 

Char

 

The char data type is used to store single characters. The size of the char data type in Java is 2 bytes (16 bit). Therefore char can store 216 = 65536 unique characters.

 

Use single quotes to represent a char type value. Java does not allow multiple characters in the char data type other than escape characters.

 

Example: char character = ‘C’;

 

In Java, escape characters are pre-defined characters that contain one or more characters with the backslash ‘\’ as a prefix that gives another definition or functionality to the characters.

 

Example: char escapeChar = ‘\n’; // This is used to put a new line when displaying on the console.  

 

Hold on. You have something more to learn about the char data type.

 

Have you heard about ASCII?

 

ASCII

 

ASCII (American Standard Code for Information Interchange) is a character encoding standard that represents characters in computer systems and other telecommunication devices. ASCII has a 7-bit character set. That means it has 27 = 128 characters.

 

ASCII character set includes alphabets (both uppercase and lowercase), digits, white space, control characters, etc. Each character has a unique number associated with it. It is called the ASCII code/ASCII value.

 

The ASCII code starts ranges 0 to 127. i.e., the first character in the ASCII character set has the ASCII code 0 and the last character has 127. For example, the ASCII code of the letter ‘A‘ is 65 and ‘a‘ is 97.

 

Every programming language uses a standard character-set that defines which characters you can use in the programming language.

 

For example, the C programming language uses the Extended ASCII.

 

Extended ASCII

 

Extended ASCII as the name suggests is the extended version of ASCII. This means extended ASCII has all the characters in the ASCII plus additional characters.

 

Extended ASCII has an 8-Bit character-set. So it has 28 = 256 characters which is the double of ASCII. So its ASCII code ranges from 0 to 255.

 

Well then, which of these character-encoding standards does Java use?

 

Java doesn’t use these. Java uses something bigger called Unicode.

 

Java Unicode System

 

Unicode is a widespread character encoding system that encodes the characters in almost all the written languages in the entire world.

 

Unicode was initially a 16-bit character-encoding system, and since they thought it’s enough, Java accepted Unicode as the character-encoding system.

 

This is why the size of the char data type is 16 bit (2 bytes) in Java (To accommodate all the characters in the Unicode).

 

Unicode uses hexadecimal values to represent characters. The range of the char data type is 0x0000 to 0xFFFF in the hexadecimal form or u0000 to uFFFF in the Unicode form.

 

The hexadecimal value of the letter ‘A‘ is 0x0041 and of ‘a‘ is 0x0061.

 

You can use the ASCII code, the hexadecimal value, and the Unicode representation in Java to represent a character.

 

Example 1: char character = ‘A’;

 

Example 2: char charInASCII = 65; // ASCII code of the letter ‘A’.

 

Example 3: char charInHexa = 0x0041; // Hexadecimal value of the letter ‘A’.

 

Example 4: char charInUnicode = ‘\u0041’; // Unicode representation of the letter ‘A’. Put this in single quotes and use the backslash ‘\‘ prefix as this works only as an escape sequence.

 

If you print any of the above char variables, you will see the letter ‘A’ in the console.

 

Don’t think so? Try it out yourself.!

 

Unicode is extended to encode more characters. Unicode now supports over 1 million characters.

 

But the char data type is still 16-bit. It can only store the characters within the 16-bit range, i.e. 65536 characters.

 

The Unicode characters within the 16-bit range are called Basic Multilingual Plane(BMP), and the characters outside the 16-bit range are called supplementary characters.

 

Since it is out of range, pairs of char type values are used to represent the supplementary characters.

 

The Default Value of Char in Java

 

The default value of the char data type in Java is ‘\u0000‘ in the Unicode form, 0 in the numerical form, and 0x0000 in the hexadecimal form.

 

So what character is this?

 

How does it look like in the character form?

 

This is called the null character. If you try to display it in the console, you will see a blank space only. This is a control character that does nothing, It just means no operation.

 

So there you go, that’s the default value of char in Java.

 

These are the most important points to know about the char data type. Also, try out the program below.

 

class GeekyChar {
     public static void main(String[] args) {
         char character = 'A';
         char charInASCII = 65;
         char charInHexa = 0x0041;
         char charInUnicode = '\u0041';
         System.out.println(character);
         System.out.println(charInASCII);
         System.out.println(charInHexa);
         System.out.println(charInUnicode);
     }
 }

 

I think you have read enough about the primitive Java data types so far.

 

Wait a second. I have said nothing about the String data type yet. Right?

 

That’s because the String is not one of the primitive Java data types. String is a Java class. Classes are Non-primitives.

 

Well, since all the primitive data types are covered, let’s check out the Java Non-primitive data types next.

 

Non-primitive Java Data Types

 

Unlike primitives, Non-primitive Java data types stay on the object-oriented side of Java. Non-primitives refer to objects. Hence why they are also known as Reference Types.

 

The Non-primitive Java data types are Classes, Interfaces, and Arrays. An object in Java can either be a class instance or an array.

 

You can learn more about these three types in-depth in the upcoming tutorials. 

 

Let’s understand more about the Non-primitives by comparing them with the primitive Java data types.

 

Difference Between Java Primitive Data Types and Non-Primitive Data Types

 

Primitive Java Data Types Non-Primitive Java Data Types
Primitive data types are not object-oriented. Primitives point to values. Non-primitive data types are object-oriented. Non-primitives point to objects.
Primitive data types are pre-defined. You can’t define a new primitive type. Non-primitive data types are user-defined. You can define your own classes or interfaces in Java.
Primitive data types store the value within the variable’s memory.

For example, with int i = 6;

The value 6 is stored in the associated memory location where the variable ‘i‘ is stored. Here the variable does a direct-reference to the value.

A non-primitive variable stores the address/reference of the object’s memory location, not the object itself. Hence, it is called ‘reference variable‘.

For example, with String str =”sample string”;

The variable ‘str‘ is the reference variable because it holds the address of the memory location where the string object “sample string” is stored.

Here the variable does an indirect-reference to the object.

This is like holding the address of a hotel. You can’t keep the hotel in your pocket. Right? You keep the address and using the address you will reach the hotel. Just like that.!

Each primitive data type has a default value depending on its type. 0 for integers, false for boolean, etc. The default value of Non-primitive data types is null. Null means no object.

These are some important differences between the primitive and non-primitive Java data types.

 

 

The below image comprises the major points of Java data types.

 

 

Now let’s look into an interesting update Java has brought into the data types region.

 

As I mentioned at the beginning of this guide, Java Data Types are indispensable. But Java has made the use of data types much easier by introducing the var type.

 

The Revolutionary VAR in Java

 

Java SE 10 introduced the var type to initialize local variables (not class level variables) that eliminate the need for specifying the data type at declaration. Therefore, improves code readability.

 

The programming languages JavaScript, C#, and many other languages already have the var type in them. But Java didn’t seem interested in including it before.

 

The var is a reserved type name in Java. it is not a keyword. This is because the existing Java program that uses var as the variable names, method names, etc should not get affected.

 

Using the var type name, you can initialize the values of all the Java data types.

 

I have given some examples below.

 

var number = 10;

 

var character = ‘G’;

 

var floatNumber = 66.24F;

 

var booleanFlag = true;

 

var stringObject = “sample string created using var”;

 

There are two rules you must know while using the var type.

 

1. You cannot use var with un-initialized variables.

 

var variable; // not allowed

 

2. You cannot use var with null initialized variables.

 

var variable = null; // not allowed

Again, remember that the var type is not for class-level variables.

 

Install and setup Java SE 10 or later versions and create a simple program like below to see for yourself the benefits of var type.

 

class GeekyVar {
     public static void main(String[] args) {
         var number = 10;
         var character = 'A';
         var doubleValue = 24.86D;
         var booleanFlag = true;
         var stringObject = "sample string";
         System.out.println(number);
         System.out.println(character);
         System.out.println(doubleValue);
         System.out.println(booleanFlag);
         System.out.println(stringObject);
     }
 }

 

Now It’s Time To Hear From You

 

So these are the essential basics of the Java Data Types that every Java beginner must learn and understand. I hope you find this guide useful.

 

Spend some time trying out the sample Java programs given in this guide or try creating your own programs.

 

Let me know your thoughts about this guide by leaving a comment below.

Leave a Reply

Your email address will not be published. Required fields are marked *