In this tutorial, we will look at the different data types available in java and some information around them.
In java, typically data-types are associated with variables. A variable has three properties:
a) A memory location to hold the value
b) The type of the data stored at the memory location
c) A name (also called identifier) to refer to the memory location
The second property is called data type. The data type of the variable determines the range of the values that the memory location can hold. Therefore, the amount of memory allocated for a variable depends on its data type. For example, 32 bits of memory is allocated for a variable of the int data type.
Java supports two kinds of data types:
i) Primitive data type
ii) Non-primitive or Reference data type
A variable of the primitive data type holds a value whereas a variable of the reference data type holds the reference to an object in memory.
For example, String (non-primitive data type) is a class defined in the Java library and you can use it to manipulate text (sequence of characters). You declare a reference “
variable str of type String” as:
String str = new String("Hi");
What happens when this code is executed? First, memory is allocated and the name of the variable
str is associated with that memory location. This process is the same as declaring a primitive data type variable. The second piece of code creates a
String object in memory with text “Hi” and stores the reference (or memory address) of the String object into the variable
You can also assign the reference of an object stored in one reference variable to another reference variable. In such cases, both reference variables refer to the same object in memory. This can be achieved as follows:
// Declares String reference variable str1 and str2 String str1; String str2; // Assigns the reference of a String object "Hello" to str1 str1 = new String("Hello"); // Assigns the reference stored in str1 to str2 str2 = str1;
In another tutorial, we will learn more about primitive data types.
Happy Learning !!