Answer: Java variable is a storage container which can hold value or any type of supported input by java. Variable must be declared with specific data types.
Answer: The main components of java variable are:
1.Data type
2.Variable Name
3. Value
Answer: To declare a variable in java, we need to take care of two things which are:
1.Data type: In java,data type define the type of data which a variable can hold.
2.Variable Name: Variable Name must follow the java naming convention.
eg: int sum;
double salary;
String name;
where int, double,String are data type & sum,salary,name are variable name.
Answer: To assign a value to variable, assignment operator which is the single equal sign(=) is used.
Assignment to variable can be done, during variable declaration or after the declaration has done.
1. Declaring and initializing value to variable in one line:
It is the most common way to assign a value to variable at the time of declaration.
Example:
int sum=121;
double size=88.9;
String name=”Joy”;
Where int,double,String are data types.
sum,size,name are variable name.
121,88.9,Joy are assigning value to the variable.
2. Assignment after Declaration of variable:
First you can declare a variabe and then in the subsequent line , you can assign a value to it.
dataType variableName;
variableName=value;
Example:
int count; // Declares the integer variable ‘count’
count=99; // Assigns the value 99 to ‘count’
NOTE:
While assigning a value to a variabe, you must remember these important points:
Data Type Matching:
The value you assign to the variable must be compatible with the data type of the declared variable.
For example, you can’t assign int value to String variable directly.
Final Variables:
If a variable is declared as final, its value can assigned only once. After assigning a value to the variable it cannot be changed.
Example:
final int value=99;
//value=56; // This cause compilation error
Reassignment:
You can change the value of a variable after its initial assignment by simply using the assignment operator again.
Example:
int num=9;
num=17; // ‘num’ now holds the value 17
Answer: When a value is assigned to a variable for the first time, it is called variable initialization.
Example: int count=55; //This variable ‘count’ is initialized for the first time with value 55 which is called initialization
The difference between variable initialization and variable assignment is that
In variable initialization, value is assign to a variable for the first time.
However, in variable assignment, value can be assign to the same variable again,after first initialization,after which the variable
hold the new value.