Java Variables

Outside Resources:

 


A variable is a named memory location where information is stored.

Example:

int x
x = 5;
x = x + 2;

in the first line, the variable x is declared. That means it is given its name.

Java won’t let you use a variable until you declare it. So the following wouldn’t work:

total = 50;

Java would tell you that no variable named total exists. You need to say “int total;” first.

You have to tell Java what type of data the variable will hold. The variable x is an int (integer) variable.

The next line assigns a value to the variable x.

When you assign a value, the variable is on the left and the value to store is on the right. If you do it backwards (ex: “5 = x;”), it won’t work.

The line “x = x + 2;” adds 2 to the previous value of x. The new value is, of course, 7.

Variables can be printed:

System.out.println(x);

Notice that there are no quotes around the variable x. If we wanted to literally print the letter “x” we would put quotes around it. Since we don’t, and we want Java to print the contents of the variable x, no quotes are used.

By the way, if you wanted to print the word “potato” and you forgot the quotes, Java would think you’re talking about a variable named potato and give you an error when that variable doesn’t exist.

You can declare and assign a variable in the same line of code:

int age = 15;
age = 16;

After the first time you declare your variable, you don’t have to list the type anymore. That’s why the second line above is “age = 16;” instead of “int age = 16;”