The short answer:
A variable is a named non-constant handler which points to an object or primitive.
The longer answer:
Say you have a class that looks like this:
- public class Example {
-
public String name;
-
}
Now you can create an instance of this class like so:
This instance is called an object. You may access the object, e.g. like this:
- (new Example()).name = "My Object";
This however is not useful in many situations, as you will want to access an object more than once. This is where variables can come into play.
Basically, this is a variable:
You have declared, that there is a variable called
myExample. You haven't declared it yet (meaning it does not yet point to an object).
To use them together, you normally do something like this:
- Example myExample;
-
myExample = new Example();
or shorter:
- Example myExample = new Example();
Now the variable and the object are bound; however the binding doesn't have to be exclusive. For example, look at this:
- Example myFirstExample = new Example();
-
Example mySecondExample = myFirstExample;
-
myFirstExample.name = "first example";
-
System.out.println(mySecondExample.name);
The output will be
"first example". The reason for this is, that
myFirstExample and
mySecondExample point to the same object.
This can be changed however; for example, look at this:
- // Create example and declare the variables to point to it
-
Example myFirstExample = new Example();
-
Example mySecondExample = myFirstExample;
-
// Set the name
-
myFirstExample.name = "first example";
-
// Reassign the first example and set its name
-
myFirstExample = new Example();
-
myFirstExample.name = "new first example";
-
// Print the names
-
System.out.println(myFirstExample.name);
-
System.out.println(mySecondExample.name);
The output will be:
- new first example
-
first example
This is because
mySecondExample is pointing to the original value of
myFirstExample which itself however is now pointing to a new value.
So, what about constant values?
Variables are so called fields; fields are generally things that can refer to objects or primitives. (A primitive is stuff like an integer or a boolean.) There is a second type of fields however: constants. Constants are marked with the
final modifier, declared once and can thereafter not be changed. Here, an example:
- final Example myConstant = new Example();
-
myConstant.name = "constant"; // This is fine as you're changing the object, not the constant
-
myConstant = new Example(); // This is not possible as you would be reassigning the constant
I hope that helps