In the previous lesson you learnt how to declare a variable. The general format was:

DataType variableName ;

We are going to discuss about different Data Types in java.

int
The int data type is used to store integers from -2147483648 to 2147483647. This will be our most commonly used data type. We learnt about int data type in the previous lesson.

String
As we learnt previously, a String is a sequence of characters enclosed in double quotation marks. Use of String is shown:


boolean
A booloean data type can store either true or false.

short
It can store integers from -32768 to 32767 just like int

long
It can store integers from -9223372036854775808 to 9223372036854775807

* Note that int , short and long are nearly same. The different is just that they can store different ranges of values and consume different amount of memory. For example, short will consume 16 bits while int will consume 32 bits and long will consume 64 bits.

char
This data type can store a single character. As strings are enclosed in double quotation marks, characters are enclosed in single quotation marks. For example
char c = 'a' ;

double
It can store decimal values from 4.9E-324 to 1.7976931348623157E308

float
It can store decimal values from 1.4E-45 to 3.4028235E38

*Please note that double has more precision than float

Example showing float and double is shown below:

byte
This is somehow related to int, short and long. It can store values from -128 to 127. It is called a byte because it consumes exactly 8 bits in the memory which is equal to one byte.

An example of above data types is given below:


How much memory does each type of variable consume?

boolean: 1 bit
byte: 8 bits
char: 16 bits
short: 16 bits
int: 32 bits
long: 64 bits
float: 32 bits
double: 64 bits

String: Depends on the size of String

Variables and memory consumption:
You just read above about how much memory a variable consume. Normally if we have to store integer values, we use int because its memory consumption is also moderate and the range of values it can store is also pretty high. Moreover by using int at all places, it also becomes easier for us to manage our code. Similarly among double and float, double is more commonly used. A question is: "Why we don't just leave short and int and use long all the times as it can hold bigger values and will not cause us a problem?" It is not Ok to use long every time just because it can hold any bigger values and will not cause a problem. It will actually consume more memory. The more memory your program consumes, the more inefficient it is. So choose data types wisely.

Useful Links: Oracle Docs , Tutorials Point

The concept of variables and data types has not ended yet. We will study more about it in the upcoming lessons.