Remember where you put it....?

The previous lesson introduced Primitive types, and before that, the general concept of objects. This lesson teaches about variables.

A variable is like a special named box. You can keep information in it, to look at again when you want. Or, you can use it to pass the information to objects for them to look at.
Sometimes, you might even want them to fill a box for you.

Variables can also be useful for remembering a special value. This can be especially useful if you don't know the value at the time you write your program.

Variables in java need to be defined before you can use them. The reason for this, is that you need to first tell java what type of data it will hold. A variable can be a primitive type, or an object type.

Variables can know things that you don't

Here, we define a variable of type 'int', which is the name given to the Primitive number type. Then we give it a value to remember. Lastly, we print out the value.
class my_object {
	public static void main(String arguments[]){
		// The stuff on the right, picks a number between 1-1000.
		// Don't worry about how, for now.
		int my_var;
		my_var= (new java.util.Random()).nextInt(1000);
		
		System.out.println("The number that was generated, is: "+ my_var);
	}
}

// As with prior examples, if you copy this code into a file named
// my_object.java and then compile it, it should actually be runnable!

Variable operations

Anything that you can do with a primitive type directly, you can also do with a variable.
Just as you can tell the computer to do "1 + 1", you can also tell it do do, "variable1 + variable2", or mix them, like "1 + variable", and so on.

You can also combine the initial definition, and setting a value, into one line.

class my_object {
	public static void main(String arguments[]){
		int my_var = (new java.util.Random()).nextInt(1000);
		int my_double = my_var *2;
		System.out.println("The number that was generated, is: "+ my_var);
		System.out.println("Twice that number, is "+my_double);
	}
}

Prev Lesson: Primative types --
Next Lesson: Using objects --