Data Types in Java Programming with Implementation Examples
The data-types are the most important basis of any programming language. It is the most important concept for every beginner. The data type is essential to represent the type, nature and set of operations for the value which it stores.
Java data types are the most basic and initial thing you should know before moving towards other concepts of Java. These are very useful in every aspect of Java, either to create a simple program or to develop any application or software.
In this tutorial, we will discuss everything that is essential for learning data types in Java. And, I bet after completing this article, you will not face any difficulty in the topic.
Before starting with Java data types, let’s first learn about data types in general.
What is a Data Type in Java?
In computer science, a data type is an attribute of data that tells the compiler or interpreter how the programmer aims to use the data.
A data type restricts the values that expression, such as a variable or a function, might take. It defines how the values of that data type are stored in memory and what operations can be performed on the data.
Data types incorporate storage categories like integers, floating-point values, strings, characters, etc.
For example, if a variable is of “int” data type, then it can hold only integer values.
Before moving towards the Java Data types, you must know the types of languages.
There are majorly two types of languages:
The first is statically typed language in which the data type of each variable has to be defined during the compile time. That is, we have to declare the type of the variable before we can use it.
Once we declare a variable of a specific data type, then we cannot change its data type again. However, they can be converted to other types by using explicit type casting in Java, except boolean. Some statically typed languages are C, C++, C#, Java, and Scala.
For example, if we write int num = 5;
Then it means the variable num is of integer type and holds a numerical value and its type will always be the same.
The other is dynamically typed language. In this type of language, the data types can change with respect to time and the variables are checked during run-time.
Some dynamically typed languages are Ruby, Python, Erlang, Perl, VB, and PHP.
Java Data Types
Java is a statically typed language. The base of any programming language is its data types and operators. Java comes with a rich set of both data types and operators, which makes it suitable for any type of programming.
There are two categories of data types in Java:
- Primitive Data Types
- Non-Primitive DataTypes
1. Primitive Data Types in Java
As the name suggests, the programming language pre-defines the primitive data types. Primitive types are the most basic data types available in Java. There are 8 primitive data types in Java: byte, char, short, int, long, float, double and boolean.
These data types act as the basic building blocks of data manipulation in Java. Primitive data types have a constraint that they can hold data of the same type and have a fixed size. Primitive data types are also called intrinsic data types. We can also perform operations on primitive data types.
All other types of data are derived from primitive data types.
Below diagram shows the complete chart of primitive data types –
Here is the classification of primitive data types in Java:
1.1 Java Characters
A character is used to store a ‘single’ character. A single quote must surround a character. The valid Character type is char. In Java, a character is not an 8-bit quantity but here character is represented by a 16-bit Unicode.
Syntax:
char myChar = ’A’ ;
Size:
2 bytes(16 bits)
Values:
A single character representing a digit, letter, or symbol.
Default Value:
‘\u0000’ (0)
Range:
‘\u0000’ (0) to ‘\uffff’ (65535)
Code:
public class CharDataType { public static void main(String args[]) { char marks,grade; marks = '8'; grade = 'B'; System.out.println("Marks: "+marks); System.out.println("Grade: "+grade); } }
Output:
Marks: 8
Grade: B
We can also perform arithmetic operations on it since it is an unsigned 16-bit type. For example, consider the following program:
// char can be handled like integers public class CharClass { public static void main(String args[]) { char myChar1 = 'A'; char myChar2 = 'B'; System.out.println("myChar1: " +myChar1); System.out.println("myChar2: " +myChar2); myChar2++; // valid increment operation System.out.println("The Incremented value of myChar2: " +myChar2); } }
Output:
myChar1: A
myChar2: B
The incremented value of myChar2: C
1.2 Java Integers
Integer type stores whole numbers that may be positive or negative and should not contain any decimal places. Valid Integer types are – byte, short, int, and long. What type will be taken depends on the value or range of the variable.
1.2.1 byte
The byte data type is mostly used in the large arrays which need memory savings. It saves memory as it is 4 times smaller than an int (integer). Sometimes, it can also be used in place of the “int” data type, when the value is very small.
The byte data type is an 8-bit signed 2’s complement integers.
Syntax:
byte myByte1 = -100 ;
byte myByte2 = 25 ;
Size:
1 byte(8 bits)
Values:
Positive or negative whole numbers.
Default Value:
0
Range:
-128 to 127
Code:
public class ByteDataType { public static void main(String args[]) { byte myByte1,myByte2; myByte1 = 127; myByte2 = -48; System.out.println("Byte 1: " +myByte1); System.out.println("Byte 2: " +myByte2); myByte1++; // Looping back within the range System.out.println("Incremented Value of myByte1: " +myByte1); } }
Output:
Byte 1: 127
Byte 2: -48
Incremented Value of myByte1: -128
1.2.2 short
Similar to the byte data type, a short data type is also used to save memory in large arrays. The short data type is a 16-bit signed 2’s complement integer. It is half of an int (integer).
Syntax:
short myShort = 6000 ;
Size:
2 bytes (16 bits)
Values:
Positive or negative whole numbers.
Default Value:
0
Range:
-32768 to 32767
Code:
public class ShortDataType { public static void main(String args[]) { short myShort = 6000; System.out.println("myShort: " + myShort); } }
Output:
myShort: 6000
1.2.3. int
Generally, we prefer to use int data type for integral values unless if there is no issue with memory. The int data type is a 32-bit signed 2’s complement integer.
Syntax:
int myNum = 700000 ;
Size:
4 bytes (32 bits)
Values:
Positive or negative whole numbers.
Default Value:
0
Range:
– 2,147,483,648 (-231) to 2,147,483,647 (231 -1)
Note: In Java Standard Edition (SE) 8 version and later, we can use the int data type to represent an unsigned 32-bit integer, which has value in the range [0, 232-1]. We Use the Integer class to use the unsigned int data type of integer.
Code:
public class IntDataType { public static void main(String args[]) { int myNum1, myNum2, result; myNum1 = -7000; myNum2 = 90000; result = myNum1 + myNum2; System.out.println("Number 1: " +myNum1); System.out.println("Number 2: " +myNum2); System.out.println("Number 1 + Number 2: " +result); } }
Output:
Number 1: -7000
Number 2: 90000
Number 1 + Number 2: 83000
1.2.4. long
The long data type is a 64-bit signed 2’s complement integers. It is used when int data type cannot hold a value. It is 2 times larger than int(integer). We must use L at the end of the value.
Syntax:
long myLong = 11000000000L ;
Size:
8 bytes (64 bits)
Values:
Positive or negative whole numbers.
Default Value:
0
Range:
-9,223,372,036,854,775,808(-263) to 9,223,372,036,854,775,807(263 -1)
Note: In Java Standard Edition (SE) 8 version and later, we can use the long data type to represent an unsigned 64-bit long, which has value in the range [0, 264-1]. We use the Long class to use the unsigned long data type.
Code:
public class LongDataType { public static void main(String args[]) { long myLong1, myLong2, result; myLong1 = 100000000L; myLong2 = 200L; result = myLong1 * myLong2; System.out.println("Number 1: " +myLong1); System.out.println("Number 2: " +myLong2); System.out.println("Number 1 * Number 2: " +result); } }
Output:
Number 1: 100000000
Number 2: 200
Number 1 * Number 2: 20000000000
1.3 Java Floating-Point Types
These are the types that store the floating-point values or real numbers, which have floating decimal places. For example, it can store fractional numbers like 5.5, 100.78, 2090.985, etc. Valid floating-point types are float and double.
We will discuss both of them in detail.
1.3.1. float
The float data type is a single-precision 32-bit floating-point, based on the IEEE 754 format (single-precision floating-point numbers). We use a float instead of double to store values in a large array of floating-point numbers so as to save memory.
Remember, we should always end the float type value with f or F, otherwise, the compiler considers it as a double value.
Syntax:
float myFloat = 256.8f ;
Size:
4 bytes (32 bits)
Values:
Real numbers up to 7 decimal digits.
Default Value:
0.0f
Range:
1.40239846 x 10-45 to 3.40282347 x 1038
Code:
public class FloatDataType { public static void main(String args[]) { float myFloat1,myFloat2,result; myFloat1=1000.666f; myFloat2=110.77f; result=myFloat1-myFloat2; System.out.println("Number1: "+myFloat1); System.out.println("Number2: "+myFloat2); System.out.println("Number1-Number2: "+result); } }
Output:
Number1: 1000.666
Number2: 110.77
Number1-Number2: 889.896
1.3.2. double
Generally, we prefer to use the float data type for decimal values unless if there is no issue with memory. As it has a precision up to 15 decimals, it is safe to use double for large calculations. We can optionally use the suffix d or D to end the floating type value.
That is, both 19.67 and 19.67d are the same. The double data type is a double-precision 64-bit floating-point, based on the IEEE 754 format (double-precision floating-point numbers).
Syntax:
double myDouble = 256.7879837 ;
Size:
8 bytes (64 bits)
Values:
Real numbers up to 15 decimal digits.
Default Value:
0.0
Range:
4.9406564584124654 x 10-324 to 1.7976931348623157 x 10308
Code:
public class DoubleDataType { public static void main(String args[]) { double myDouble1, myDouble2, result; myDouble1 = 48976.8987; myDouble2 = 29513.7812d; result = myDouble1 + myDouble2; System.out.println("Number 1: " +myDouble1); System.out.println("Number 2: " +myDouble2); System.out.println("Number 1 + Number 2: " +result); } }
Output:
Number 1: 48976.8987
Number 2: 29513.7812
Number 1 + Number 2: 78490.6799
1.4 Boolean Types
A boolean data type is a 2-valued data type that is declared with the boolean keyword. It is capable of storing only two possible values i.e., true and false.
This data type is used for flag generations, to check the true or false conditions. Boolean data type stores only 1-bit information and size is not precisely defined.
Syntax:
boolean myBool = false ;
Size:
Machine-dependent
Values:
true, false
Default Value:
false
Range:
true or false
Code:
public class BooleanDataType { public static void main(String args[]) { boolean myBool = true; if(myBool == true) System.out.println("I am using a Boolean data type"); System.out.println(myBool); } }
Output:
I am using a Boolean data type
true
2. Non-Primitive Data Types in Java
The term non-primitive data type means that these types contain “a memory address of the variable”.
In contrast to primitive data types, which are defined by Java, non-primitive data types are not defined or created by Java but they are created by the programmers.
They are also called Reference data types because they cannot store the value of a variable directly in memory.Non-primitive data types do not store the value itself but they store a reference or address (memory location) of that value.
They can call methods to perform a particular function. They can also be null.
For example:
long modelNumber = 62548723468;
Instead of storing the value of modelNumber directly, reference data types in Java will store the address of this variable. So reference data type will store 1003 rather than the actual value. The below diagram explains how the value is stored in a memory area.
There are many non-primitive data types in Java.
Let us now understand these.
2.1. Java Strings
The String data type is used to store a sequence or array of characters (text). But in Java, a string is an object that represents an array or sequence of characters. The java.lang.String is the class is used for creating a string object.
String literals should be enclosed within double-quotes. The difference between a character array and a string is that in the string a special character ‘\0’ is present.
Basic Syntax for declaring a string in Java:
String <String_variable_name> = “<sequence_Of_Strings>” ;
Example:
String myString = “Hello World” ;
Ways to create a string object:
There are 2 ways of creating a String object:
- By using a string literal: Java String literal can be created just by using double-quotes. For
Example:
String myLine = “Welcome to TechVidvan Java Tutorial”;
- By using a “new” keyword: Java String can also be created by using a new keyword. For example:
String myLine = new String(“Welcome to TechVidvan Java Tutorial”);
Code:
public class stringTutorial { public static void main(String args[]) { String string1 = "Hello World"; // declaring string using string literals String string2 = new String("This is TechVidvan Java Tutorial "); //declaring string using new operator System.out.println(string1); System.out.println(string2); } }
Output:
Hello World
This is TechVidvan Java Tutorial
2.2. Java Arrays
An Array in Java is a single object which can store multiple values of the same data type. Arrays are homogeneous data structures that store one or more values of a specific data type and provide indexes to access them. A particular element in an array can be accessed by its index.
The below diagram shows the illustration of arrays.
A two-step process of creating an array:
Creating an array involves two steps which are:
- Array Declaration
- Array Initialization
Array Declaration
This is the first step in which we declare an array variable of the desired data type.
The valid syntax for array declaration can be:
data-type array_name [ ]; data-type [ ] array_name;
Example:
int daysInMonth [ ]; char [ ] lettersInSentence; double salaryOfEmployees [ ]; String progLanguages[ ];
Array Initialization
In the second step, we allocate the memory to the array with the help of a new operator and assign the memory to the array variable. So, let us see how can we declare arrays in different ways.
The valid syntax for array initialization can be:
array_name = new data-type [size of array]; array_name = new data-type {elements of array using commas};
Example:
daysInMonth = new int [100]; lettersInSentence = new char[5]; salaryOfEmployees = new double[ ] {10000, 50000, 30000, 25000, 40000}; progLanguages = { “C”, “Java”, “Ruby”, “Python”, “PHP” };
Combining two steps, we can create an array as follows:
data-type array_name [ ] = new data-type [size of array]; data-type [ ] array_name = new data-type [size of array]; data-type array_name [ ] = new data-type {elements of array using commas};
Note: If the elements of an array are not given then Java stores the value of each element with 0.
Code:
public class arrayTutorial { public static void main(String args[]) { int [ ] marksOfStudents = new int[ ] {65, 90, 78, 60, 84 }; System.out.println("Marks of first student: " +marksOfStudents[0]); System.out.println("Marks of second student: " +marksOfStudents[1]); System.out.println("Marks of third student: " +marksOfStudents[2]); System.out.println("Marks of fourth student: " +marksOfStudents[3]); System.out.println("Marks of fifth student: " +marksOfStudents[4]); } }
Output:
Marks of first student: 65
Marks of second student: 90
Marks of third student: 78
Marks of fourth student: 60
Marks of fifth student: 84
2.3. Java Classes
A class is a collection of objects of the same type. It is a user-defined blueprint or prototype which defines the behavior or state of objects. Class and objects are the basic elements of Object-Oriented Programming that represent the real-world entities.
A class consists of a set of properties (fields or variables) or methods/operations to define the behavior of an object. We create a class using a class keyword.
A class can be declared using the following components in the order-
1. Access modifiers: Access modifiers define the access privileges of a class. A class can be public or it has default access.
2. Class name: The name of a class should represent a noun and must start with a capital letter. These are the best practices to be kept in mind while declaring any class.
3. Body: The class body contains properties and methods. The body is always enclosed by curly braces { }.
Syntax of writing a class:
AccessModifier class class_name { Class body - variables and methods(); }
Example:
public class MyClass { int x = 5; void display() { // methodBody; } }
2.4. Java Objects
It is a basic unit of Object-Oriented Programming which represents the real-world entities. An object is an instance of a class. It defines the state and behavior of real-life entities.
- State: It represents the attributes and properties of an object.
- Behavior: Methods define the behavior of an object. It also reflects the communication of one object with the other objects.
- Identity: It gives a unique name to an object which allows one object to interact with other objects.
For example, An object ‘Dog’ has states like name, breed, color, size, age, and functions like bark, eat, run, sit.
Syntax of creating an object of a class:
To create an object of a class, specify the class name, followed by the object name, by using the new keyword-
class_name object_Name = new class_name();
Example:
MyClass object1 = new MyClass();
Code:
public class Student { int marks = 76; public static void main(String[] args) { Student student1 = new Student(); // creating object of the class by using new operator System.out.println("Marks of student: " +student1.marks); Accessing the property “marks” of the class with the help of an object. } }
Output:
Marks of student: 76
2.5. Java Interfaces
An interface is another reference type in Java.
It is similar to a class. It can also have methods and variables, but the methods are declared implicitly as “public” and “abstract” in interfaces. However, since Java 9, we can include private methods in an interface.
The abstract methods have only a method signature but they can not have a method body. An interface behaves like a blueprint of a class, which specifies “what a class has to do and not how it will do”.
In the real-world, one user defines an interface, but different user provides its implementation. Moreover, it is finally used by some other user.
Syntax of writing interfaces:
To declare an interface, we just write the keyword “interface” followed by the interface name:
interface interface_name
To use an interface in a class, we have to append the keyword “implements” after the class name followed by the interface name.
class class_name implements interface_name
Example:
interface Serializable { // Abstract methods } class MyClass implements Serializable { //class body }
Code:
//creating an interface interface Runnable { public void run(); //an abstract method } // implementing the interface public class Person implements Runnable { public void run() { System.out.println("This person can run"); } public static void main(String args[]) { Person person1 = new Person(); person1.run(); } }
Output:
This person can run
An Interface is all about capabilities – like an interface is Runnable. Any class (class Person in this case) implementing Runnable must implement run(). So, an interface specifies a set of methods that the class has to implement.
Summary
By this tutorial, you understood the data types in Java and also its major classification of Primitive and Non-Primitive data types. We also discussed how to implement these data types in our Java programs and in real-world applications.
Did we miss anything in Java data types article? Do share with us in the comments. TechVidvan will be glad to add it.