Posts Tagged Java

Data Types in Java

Sunday, May 15th, 2011

Data Types in Java

By: Pankaj Yadav

It is a classification in programming languages which indicates the type of value a variable can store. Different types of values are there & different operations are there for every data type. e.g.

Following statements declares 2 variables of datatypes int and char & also initializes

int  _iVar = 4;       //'_iVar' can store only numbers
char  _cVar = 'c';   //'_cVar' can store both numbers & characters

There are 2 groups of data types in Java Primitive and Non- Primitive.

Primitive Data Types

Variables of these data types store the actual data or the primitive value. They are passed by value. There are 8 primitive datatypes in Java:- int, char, byte, short, long, float, double and boolean.

Data Type Size Range
int 32-bit -2,147,483,648 to 2,147,483,647
short 16-bit -32,768 to 32,767
long 64-bit -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
byte 8-bit -128 to 127
float 32-bit 1.40129846432481707e-45 to 3.40282346638528860e+38
double 64-bit 4.94065645841246544e-324d to 1.79769313486231570e+308d
char 16-bit 0 to 65,535
boolean 1-bit True or False only

To get minimum & maximum values of a datatype:

Datatype_Name.MIN_VALUE				// lower limit
Datatype_Name.MAX_VALUE				// upper limit

Primitive datatypes have a limit of values (range) & also they have a default values till programmer assigns which are described in the following table along with their size & format.

Example of Primitive Dat Type


int a = 8;                      //a contains value 3
int b = a;                      //b contains copy of a
    b = 5;                      // Changing b

                                // Now, b = 5 and a = 8
                                // no change in a

Non-Primitive Data Types

Variables of non-primitive datatypes or object references stores reference to the actual value stored in the primitive variable.

Objects (Classes & Interfaces) and Arrays are the reference or non-primitive data types in Java. They are so called because they are handled “by reference” i.e. variables of their type store the address of the object or array is stored in a variable. They are passed by reference. For Ex:

char[]  arr = { 'a', 'b', 'c', 'd' };		//'arr' stores the references for the 4 values

Example of Non-Primitive Dat Type


Button a, b;                  //Objects of type Button
a = new Button();              //a object created
b = a;                         //b object created
                               //& filled with a
a.var = 8;
b.var = 5;                //Assign values
                          // Now, b = a = 5
                         //a is changed