How can a variable be created.
0
How can a variable be created.
Variable is a named memory location used to store data temporarily. During program execution we can modify that data. A Variable can be created by using Datatype. As we have two types of datatypes we can create two types of variables
1. Primitive Variables:- These variables are created by using primitive datatypes.
2. Referenced Variables:- These variables are created bt using referenced datatypes.
The Difference between primitive and referenced variables is "primitive variables stores data directly, where as referenced variables stores reference of the object, not direct values".
Note: As per compiler and JVM we do not have a separate name called "referenced variable". It means, the variables created by using referenced datatype are also considered as like normal variables only.
Below program shows creating primitive and referenced variables
// Example.java
class Example
{
int x=10;
int y=10;
}
//Test.java
class Test{
public static void main(String args[]){
//primitive variables
int p=50;
int q=m1();
//referenced variables
String s1="a";
String s2=new String("a");
Example e=new Example();
//Referenced variables are initialized with object reference that is created and returned by "new" keyword, as shown in the abobe program.
}
static int m1(){
return 60;
}
}
Limitation of variable:
It can only store single value at a time. If we assign new value, old value is replaced with new value. It means, always it returns latest modified value.
- If we modify primitive value previous value is replaced with new value.
- If we modify referenced variable previous object's reference is replaced with new object's reference and now this referenced variable is referencing to this new object.
Show memory structure from the below program and also output.
class Sample{
public static void main(String args[]){
int a=50;
System.out.println("a: "+a);
a=70;
System.out.println("a: "+a);
Example e1=new Example();
System.out.println("e1: "+e1);
e1=new Example();
System.out.println("e1: "+e1);
}
}
Output:
a: 50
a: 70
e1: Example@f4a24a
e1: Example@cac268
Conclusion:
The value of primitive variable is mathematical data based on its data type.
The value of referenced variable is its class object's reference.
0 comments: