Java Data Types (with examples)

Read Time:11 Minute, 49 Second

Table of Contents

Java has many data types and operations, making it suited for various programming tasks. These are pretty helpful in all aspects of Java, whether you’re writing a simple program or developing a complex application or software. In Java, data the two core categories of types include primitive data and data types that aren’t primitive.

Java’s Data Types

Java’s variables must be of a specific data type. There are two groups of data types:

  • Byte
  • short
  • int
  • long
  • float
  • double
  • boolean, and
  • char

The list above are examples of primitive data types. On the other hand, Strings, Arrays, and Classes are examples of non-primitive data types.

Types of Primitive Data

A primitive data type determines both types of variable values and size, which has no extra functions. In Java, primitive data types make up a count of eight:

Data Type Size of Data Explanation
byte 1 byte has whole numbers from -128 to 127
short 2 bytes has entire numbers from -32,768 to 32,767
int 4 bytes has whole numbers from -2,147,483,648 to 2,147,483,647
long 8 bytes has whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float 4 bytes has numbers that are fractions. Enough to store between 6 and 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
boolean 1 bit Stores true or false values
char 2 bytes Stores a single character/letter or ASCII values


There are two sorts of primitive number types:


  • Integer types store whole integers, which are either positive or negative such as 123 or -456.
  • Byte, short, int, and long are all valid types.

The numeric value determines which type you should choose. Floating-point types represent numbers with a fractional portion and one or more decimals. Float and double are the two types.

Even though Java has multiple numeric types, the most commonly used for numbers are int (for whole numbers) and double for floating-point numbers. However, we’ll go through each one in detail as you read on.

Integer Types


From -128 to 127, the byte data type can hold entire values. When you know the value will be between -128 and 127, you can use this instead of int or other integer types to conserve memory:


The full numbers -32768 to 32767 can be stored in the short data type:


Whole numbers between -2147483648 and 2147483647 can be stored in the int data type. Therefore, when creating variables with a numeric value, the int data type is the ideal data type in general.



From -9223372036854775808 to 9223372036854775807, the long data type can store entire numbers. When int is insufficient to store the value, this is utilized. It’s important to note that the value should conclude with an “L”:

Types of Floating Points

It would be best to use a floating-point type when you need a decimal number, such as 9.99 or 3.14515.


Fractional numbers between 3.4e-038 and 3.4e+038 can be stored using the float data type. It’s important to note that the value should conclude with an “f”:


Fractional numbers between 1.7e-308 and 1.7e+308 can be stored in the double data type. It’s important to note that the value should conclude with a “d”:

Is it better to use float or double?

The precision of a floating-point value is the number of digits following the decimal point that the value can have. The precision of float variables is just six or seven decimal digits, but the accuracy of double variables is around 15 digits.
As a result, it is safer to utilize double for most calculations.


Numbers in Science

A scientific number with a “e” to represent the power of ten can also be a floating point number:


The boolean keyword is used to specify a boolean data type, which can only take the values true or false:

Conditional testing uses Boolean values extensively, which you’ll learn more about later.


A single character is stored in the char data type.
Single quotes, such as ‘Z’ or ‘b,’ must surround the character:

You can also use ASCII values to display specific characters:


The ASCII Table Reference contains a complete list of all ASCII values.


A sequence of characters is stored using the String data type (text). In addition, use double quotes to surround string values:

Because the String type is so widely utilized and integrated with Java, it is sometimes referred to as “the special ninth type.”

Don’t worry if you’re not familiar with the term “object.” It relates to an object, a String in Java is a non-primitive data type. Methods on the String object are used to execute various operations on strings.

Types of Non-Primitive Data

Because they refer to things, non-primitive data types are termed reference types. The following are the fundamental distinctions between primitive and non-primitive data types:


  • In Java, primitive types are predefined (that is, they have already been declared). Java does not specify non-primitive types, which the programmer constructs except for string.
  • Non-primitive types, on the other hand, can be used to call methods that perform specific actions, whereas primitive types cannot.
  • Non-primitive types can be null, whereas primitive types always have a value.
  • A lowercase letter begins with a primitive type, while an uppercase letter begins with a non-primitive one.
  • The size of a primitive type is determined by the data type, whereas non-primitive types are all the same size.

Strings, Arrays, Classes, Interfaces, and other non-primitive types are examples.


Interfaces are another approach to implement abstraction in Java. An interface is an “abstract class” that is used to put together related functions with empty bodies:

The interface must be “implemented” (kind of like inherited) by another class with the implements keyword to access the interface functions (instead of extends). The “implement” class provides the body of the interface method:

Interface Remarks

Interfaces, like abstract classes, cannot be used to construct objects. For instance, in the example above, it is not possible to create a “Human” object in the MyMainClass.

The “implement” class provides the body for interface methods that don’t have one. It would help override all of an interface’s methods when implementing it. By default, interface methods are abstract and public. Also, by default, interface attributes are public, static, and final. A constructor is also not allowed in an interface as it cannot create objects.


When Should You Use Interfaces?

1) To increase security, hide certain information and only display the most critical aspects of an object (interface).

2) “Multiple inheritance” is not supported in Java (a class can only inherit from one superclass).
However, because the class can implement many interfaces, it can be done with interfaces.
Note: To use several interfaces, use a comma to separate them (see example below).

Java Objects and Classes

Java’s primary focus as a computer language is on objects.

In Java, everything is linked to classes and objects and their characteristics and methods.
A computer, for example, is an object in real life. The computer has characteristics like weight and color and procedures like start and shutdown.

A class functions similarly to an object constructor or a “blueprint” for constructing things.


Creating a Class

Use the term class to create a class:

Remember from the Java Syntax concepts that a class should always begin with an uppercase letter and that the java file name should be the same as the class name.

Making a new object

A class in Java is used to build an object. We’ve already created the Main class, so we can now create objects. To create a Main object, type the class name, then the object name, followed by the keyword new:

Example: Create a “theObj” object and print the value of a:

Objects in Multiples

You can make numerous objects of the same type:


Example: Create two Main objects Using Several Classes

You can also build a class object and use it in a different class. It is frequently used to organize classes (one class contains all properties and methods, while the other has the main() function (code to be run)).

Keep in mind that the java file should have the same name as the class. We’ve created two files in the same directory/folder in this example:

When you’ve finished compiling both files, you’ll be able to tun the file as follows:

Arrays in Java

Arrays store many values in a single variable instead of defining distinct variables for each item. To declare an array, use square brackets to determine the variable type:


We’ve now declared a variable that will hold a string array. Further, we can use an array literal to add values to it by placing the items in a comma-separated list inside curly braces:

You may make an array of integers as follows.

Access to an Array’s Elements

The index number is used to access an array element. In the computer’s array above, this statement gets the value of the first element:

Note that array indexes begin at 0. As a result, the first element is [0]. The second element is [1], and so on.

Make a Change to an Array Element

Refer to the index number to change the value of a certain element:


Length of Array

Establishing the length of an array is an aspect of the length property in an array:

Iterate Over an Array

The for loop can be used to loop through the array elements, and the length property can be used to determine how many times the loop should execute. All elements in the computer’s array are output in the following example:

In addition, with For-Each, you may loop through an array. There’s also a “for-each” loop, which is only used to loop through array elements:


Using a “for-each” loop, the following example prints all members in the vehicles array:


You might understand the preceding example when we break it down as follows: print the value of i for each String element (called i – as in index) in computers. When comparing the for loop and the for-each loop, you’ll notice that the technique is easier to code, requires no counter (since it uses the length property), and is more readable.

Arrays with several dimensions

An array of arrays is a multidimensional array. Add each array within its own set of curly brackets to make a two-dimensional array:

numVals is now an array that contains two arrays as items. To get to the items in the numVals array, you’ll need two indexes: one for the array and one for each element within it. This example uses the third member (2) of numVals’ second array (1):

To acquire the items of a two-dimensional array, we can use a for loop inside another for loop though we still need to point to the two indexes:

Strings in Java

Text is stored using strings. A String variable is made up of a group of characters encased in double-quotes:


Example: Create a String variable with the following value:

Length of the String

A String in Java is an object which comprises methods that may perform specific actions on strings. For example, the length of a string may be obtained with the length() method:

Additional String Methods

There are numerous string functions, such as toUpperCase() and toLowerCase():

Finding a Character in a String is a difficult task. The indexOf() method retrieves the first occurrence of a supplied text in a string (including whitespace):

Java starts counting at zero. 0 is the first place in a string, 1 is the second, and two is the third.


Concatenating strings

The + operator is responsible for joining two strings together. It is referred to as concatenation:

To make a space between firstName and lastName on print, we’ve placed an empty text (” “) between them. You can also concatenate two strings with the concat() method:

Characters with Unique Qualities

Because strings must be enclosed in quotes, Java will misinterpret this string and generate the following error:

The backslash escape character is an excellent way to avoid this problem. Special characters are converted to string characters using the backslash () escape character. In addition, In Java, there are more than six escape sequences that are valid as follows:

Escape character Result Description
Single quote
Double quote
\ Backslash
n New Line
r Carriage Return
t Tab
b Backspace
f Form Feed

In a string, the sequence ” inserts a double quote:


In a string, the sequence ’ inserts a single quote:

The following sequence adds a single backslash to a string:

Adding Strings and Numbers

The + operator is used in Java for both addition and concatenation.

  • Numbers are added to the equation.
  • Strings are joined together.

When two numbers are added together, the result is a number:

Combining two strings leads to a string concatenation:


Combining a number and a string, you get a string concatenation:


Any computer language’s most crucial foundation is its data types. It is the most vital notion for any newcomer. The data type is required to express the kind, nature, and set of operations associated with the value it stores.

Java data types are incredibly fundamental. It is the first thing you should learn before moving to other Java concepts.


CyberSEO Pro - OpenAI GPT-3 autoblogging and content curation plugin for WordPress

Tag Cloud

Java Java Logical Programs OTP Generation in Java python Recursion youtube video ASCII Upper and Lower Case blockchain javascript graph learn to code software development Successful Software Engineers breadth first search Java Array Programs Java Programs Uncategorized android ios programming kotlin web-development django data sql cybersecurity database swiftui serverless aws swift rust react background-position gradients loader mask grid nth-child pseudo elements indieweb WordPress Print Array without brackets C++ factorial Java String Programs Final Keyword Static Variable Axie Infinity Cryptokitties NFT games tool inserting MISC Tips Codes python code python projects python3 system info python project Bigginers How to Do Integrations Payment Gateways PHP checkout page in php Implement stripe payment gateway in Step by step in PHP integrate stripe gatway in php mysql payment gateway integration in php step by step payment gateway integration in php step by step with source code payment gateway integration in website PHP Integrate Stripe Payment Gateway Tutorial PHP shopping cart checkout code shopping cart in php stripe php checkout PHP/MySQL/JSON best international payment gateway does google pay accept international payments how to accept international payments in india paytm payment gateway razorpay codeigniter github razorpay custom checkout github razorpay get payment details razorpay integration in codeigniter github razorpay international payments Razorpay payment gateway integration in CodeIgniter razorpay payment gateway integration in php code Razorpay payment gateway integration with PHP and CodeIgniter Razorpay payment gateway setup in CodeIgniter Library & Frameworks Tips & Tricks UI/UX & Front-end coding birds online html code for google sign in login with google account in PHP login with google account using javascript login with google account using javascript codeigniter login with google account using php login with google account using php source code
My white whale: A use case for will-change Previous post My white whale: A use case for will-change
Manuel Matuzovic’s CSS Specificity Demo Next post Manuel Matuzovic’s CSS Specificity Demo

Leave a Reply

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

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