Java variable or simple variable is a small memory unit in RAM and also used to store values used in program source code. Variables values can be changed at the time of running applications. Variables have different data types and each data type have a different size in memory. All variables have four basic parts.
- Variable name
- Variable size
- Variable address
- Variable value
In this example a variable “Marks” have four-part. The variable name is Marks, the value in 786, the address is B27C1, and the variable size is 4 byte.
A variable must define before its usage in a program. When you define a variable the data type is specified and appropriate amount of memory reserved. This memory space is addressed by reference to the name of the variable in RAM. A simple declaration has the following syntax:
SYNTAX: data_type variable_name;
Data_type: It indicates types of data that can be stored in a variable.
Variable_name: It refers to the memory location of the variable.
Different types of variables are declared as follows:
int marks; float average; char grade; double salary;
A variable can be initialized, i.e. value can be assigned to the variable, during its definition. A simple initialization by placing the following immediately after the name of the variable.
type_name variable= value;
type_name: It indicates the data type of the variable to be initialized.
variable: It is the name of the variable to be initialized.
=: It is the assignment operator which used to initialize a variable value.
value: It is the value that initializes to a variable.
int n= 100; int x=50, y = 30; char grade = `A`; float average = 50.66;
- A variable must be declared before it assigns a value. A variable which declared in a method/function must be assigned a value before it can be used.
- If you have not put any value in a variable before using it then the variable has default garbage or any random value.
- A variable name cannot be changed at the time of compilation or running application.
- When you declare a variable then this time assigns its initial value in one step. This will make the program easy to read and understand the source code and also avoid programming errors.