Sunday, May 1, 2011

Java Primitive Data Types

In this part of my blog, I will try to give some information about java primitive data types, their range and default value of the types.

The Java programming language is statically-typed, which means that all variables must first be declared before they can be used. Before using any variable in your program, you must declare the variable with its type and name.

For example:

int data = 1;

This declaration tells your program that there is a field named “data”, holds numerical data, and has an initial value of "1".

Primitive data types and their range:

boolean :1 bit

range - May take on the values “true” and “false” only.

byte :1 byte

range - form -128 to 127

short :2 bytes

range – from -32,768 to 32,767

int :4 bytes

range – from -2,147,483,648 to 2,147,483,647

long :8 bytes

range – from -9,223,372,036,854,775,808

to 9,223,372,036,854,775,807

float :4 bytes

range – from 1.40129846432481707e-48

to 3.40282346638528860e+38

(positive or negative)

double :8 bytes

range – from 4.94065645841246544e-324d

to 1.79769313486231570e+308d

(positive or negative)

char :2 bytes, unsigned, unicode

range – from 0 to 65,535

String :a sequence of characters

We must know the range of the types to use them effectively in our programs. For example we have a counter, it starts with the value of 0 and it increases continuously. Initially for this counter as primitive type “int” will be sufficient. But in the future, the value of the counter will increase and it will be outside the range of int. so the program will not work correctly.

As developer if you do not assign a value to a variable you declare, it will be assigned will its default value.

Default values for the data types:

Data Type Default Value

byte :0

short :0

int :0

long :0L

float :0.0f

double :0.0d

char :’\u0000’

boolean :false

String :null

I wish to be useful.