Variable and Data Type
Variable is a space in memory where we can store data. It helps to access the data easily.
Data Type
A data type defines the size and type of information stored in a variable. Data types help in memory management. It helps to assign the memory depending upon the type of data type.
Most importantly Java has numerous datatypes and all data types are predefined, which is used to store a large amount of information.
There are two main categories of datatype primitive and non-primitive which classified the various datatypes. The following diagram classified the primitive data types and non-primitive data types:
Primitive type includes:
Integer type
It is further divided into subcategories of datatypes.
- byte
- boolean
- short
- int
- long
byte
The byte data type holds an 8-bit signed two’s complement integer. It is also one of the reserved words in Java. byte stores whole numbers ranges in between -128 to 127. As it is allocated limited memory space, it can be used as a replacement of int datatype.
boolean
This datatype is used to store two possible values: either True or False. boolean type values are not converted implicitly or explicitly to any other type (means typecasting is not possible).
short
It stores whole numbers and the range lies in between -32768 to 32767.
int
When creating variables consisting of numeric values, Java gives preference to int datatype as it has a higher precedence order. So in a program, if you have not defined the datatype, by default java assumes it as int. It stores whole numbers from -2147483648 to 2147483647. Negative numbers are also permissible here. It has a wider range compared to short and byte.
long
This datatype can store whole numbers from -9223372036854775808 to 9223372036854775807. For storing a large amount of data, long datatype is preferred over int. In Java, the value of long datatype must end with literal “L”. Otherwise, Java considers it as int type.
Floating-point type
Floating-point datatypes are used for calculating simple to complex fractional data. It is further subcategorized into two parts:
- float
- double
float
For storing fractional numbers, float datatype is used. It has a 7-decimal digit precision in memory. Float datatype should be avoided when calculating financial figures or numbers. The value being used here is an approximate value and therefore, not suitable for calculations involving precise values such as currency. By default, Java assumes floating-point datatype as double, so you need to add a literal at the end, denoted by the letter “f”.
double
Another floating-point datatype used to store a huge amount of data in memory. It has a 15-decimal digit precision in memory. Storing decimal values this data type is generally the default choice.
Non-Primitive types include:
- String: A collection of characters stored in memory is called a String.
- Array: Collection of a homogenous datatype is known as Array.
Contributed by: Poonam Tomar