Variables & Primitive Data Types

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

Variable Declaration:

To declare a variable, you must specify the data type & give the variable a unique name.
 

Java Variables and Data Types

Examples of other Valid Declarations are

Variable Initialization:

To initialize a variable, you must assign it a valid value.
 

Java Variables and Data Types

Example of other Valid Initializations are

Java Data Types

Primitive Data Types

Primitive Data Types are predefined and available within the Java language. Primitive values do not share state with other primitive values.

There are 8 primitive types: byte, short, int, long, char, float, double, and boolean Integer data types

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.
 

Java Variables and Data Types

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
 

Java Variables and Data Types

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.

top
X
Welcome to Our Website
Welcome to WPBot
wpChatIcon