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.
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!
You can also combine the initial definition, and setting a value, into one line.
Prev Lesson: Primative types --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); } }