Variable is a memory location which stores data. In Java, we have to define what type of variable (integer, text, string, etc.), we are storing. After it a fixed memory is assign to each variable. For example, normal integer is assign 4 bytes. We can not assign other type of values to defined variables. For example, if we have defined a variable as integer then we can not assign a text string to that variable. We can modify that variable with different value of same type (say another integer). In java, there are 8 types of primitive variables.
- Run below examples by writing in main method. To print them in console use System.print.out("variable");
- We can give variables any name other than reserved keywords starting with letter, $ or underscore (_).
Integer is a 32-bit data type which stores integer values from range - 2,147,483,648 ( -2^31 ) to 2,147,483,647(inclusive) ( 2^31 -1 ).
- int a = 8;
- a = 10;
It is 8-bit data type used to store integer value from -128 to 127 (inclusive).
- byte a = 23;
- a = -24;
It is 16-bit unicode character which stores any character.
- char a = 'a';
- a = 'z';
NOTE: Character is written inside single colons '' but string is written in double colons "".
It is one bit boolean data type which has only two values: true or false.
- boolean a = true;
- a = false;
Double data type is a double-precision 64-bit IEEE 754 floating point. This should not be used for precise values such as currency.
- double a = 56;
- a = 45.98;
Short data type is a 16-bit signed two's complement integer. Its range is from -32,768 to 32,767 (inclusive).
Long data type is a 64-bit signed two's complement integer. Its range is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (inclusive). It is used when we need wider range for integers.
- int a = 200000L;
- a = -300000L;
Float data type is a single-precision 32-bit IEEE 754 floating point. Float data type is also never used for precise values such as currency.
String is an array of characters. We will read about array in detail later. At this moment you may assume string is a collection of characters. It is simple text.