Java Variables and Data Types with EXAMPLE
What is a Variable?
A variable can be thought of as a container which holds value for you, during the life of a Java program. Every variable is assigned a data type which designates the type and quantity of value it can hold.
In order to use a variable in a program you to need to perform 2 steps
Java Variable Type Conversion & Type Casting
A variable of one type can receive the value of another type. Here there are 2 cases –
Case 1) Variable of smaller capacity is be assigned to another variable of bigger capacity.
This process is Automatic, and non-explicit is known as Conversion
Case 2) Variable of larger capacity is be assigned to another variable of smaller capacity
In such cases, you have to explicitly specify the type cast operator. This process is known as Type Casting.
In case, you do not specify a type cast operator; the compiler gives an error. Since this rule is enforced by the compiler, it makes the programmer aware that the conversion he is about to do may cause some loss in data and prevents accidental losses.
Example: To Understand Type Casting
Step 1) Copy the following code into an editor.