Saturday, May 7, 2011

5. Variable... or Not

As we saw in the previous chapter, Java stores all the data in different 'datatypes'. Now let's see how this is done.

Any kind of data can be stored within a program by using a 'variable' of the appropriate type, just like in Algebra.
For example, if you have 3 coconuts, you can use the following variable declaration:
int coconuts = 3;
That line should be self-explanatory, I think. We have declared a variable called 'coconuts' that holds the value 3. The same statement could be broken down into two lines in the following manner:
int coconuts;
coconuts = 3;
Let us do something similar with the other datatypes:
double money = 3.5;
char temporary = 'A';
boolean happy = true;
String str = "Hello!";
...and so on.

Now, all the above declarations are VARIABLE declarations, i.e., their values can VARY.
For example, if I eat one of the coconuts, i would now write:
coconuts = 2;
The value stored in 'coconuts' has now been OVERWRITTEN, and is now 2.

Java also supports CONSTANTS. Just like variables, constants can store values, but unlike them, these values CANNOT be changed. Example:
final int cookies = 3;
See the difference? The declaration is the same as that of a variable, except for the keyword 'final' having been added before it.
Now what if i try to change it's value?
cookies = 2;
This would give an error during compilation, and won't work.
You can use this property to store mathematical constants, such as:
final double pi = 3.1415;

This is all there is to this chapter. You can post any queries in the 'comments' section below...

No comments:

Post a Comment