5 Java Data Types
5 Java Data Types
Learn about various data types in Java. Learn the differences between primitive datatypes and non-
primitive datatypes (or reference datatype). We will also learn about the data types sizes and best
practices to use datatypes in Java.
In Java, typically data-types are associated with variables. A variable declaration has three parts:
The variable type stored at the memory location (it is called datatype)
The second property (marked in red) 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 is a statically-typed language. This means all variables MUST be declared before
they can be used.
The values stored in primitives are called literals. A literal is the source code
representation of a fixed value; literals are represented directly in your code without
requiring computation.
DATA DEFAULT
DESCRIPTION MEMORY SIZE
TYPE VALUE
A binary value of
boolean false 1 bit
either true or false
int values values from from -231 to 231-1 0 32 bits signed value
long values values from from -263 to 263-1 0 64 bit floating point
value
In Java SE 7 and later, any number of underscore characters ('_') can appear anywhere
between digits in a numerical literal. e.g. 10_000_000 is a valid number in Java.
Notice that when Java detects that type conversion may result in data loss (bigger data
type to smaller one), then gives type-mismatch error and explicitly asks for type
casting (e.g. ‘int’ to ‘short’ assignment). It helps in detecting and resolving accidental
data loss assignments.
For example, java.lang.String is a class defined in the Java library and you can use
it to manipulate text (sequence of characters). You declare a reference variable of
type String as:
String str = new String( "Hello World !!" );
What happens when this code is executed? First, a memory block 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 part of code creates a new String object in memory with text "Hi" and
stores the reference (or memory address) of the String object into the variable 'str'.
You can also assign the reference of an object stored in one reference variable to
another reference variable. In such cases, both reference variables will refer to the same
object in memory.