A variable is like a box that can hold one value. In fact, a given variable can only hold one type of value.
To use a variable, you do two separate things.
First, you have to create the variable. That involves giving it a name and telling what type of thing you want to put in it. If you want a variable of type int called num, then you write
int num;The type comes first, then the name. Also, notice the semicolon. Remember that the syntax of Java is very strict.
After you have created a variable, you will want to put something in it. Think of a variable as like a shoe box. When you first get the box, it is empty. You want to put something into the box, so that you can remember that value.
To put a value into a variable, you write an assignment statement, such as
num = 0;Notice the semicolon. Every assignment statement ends on a semicolon.
You can compute any expression and put the value of that expression into a variable. Assignment statement
num = 51 + 2;makes variable num hold 53.
An assignment statement
v = E;first computes the value of expression E, then stores that value into variable v. For example, suppose that you do the following.
int num; num = 2; num = num + 1;The first line just creates variable num and says that it can hold an integer. There is no integer in it yet. The second line puts 2 into variable num. The third line first computes num + 1 (which yields 3, since num currently holds 2) and then puts 3 into num. Now num holds 3, not 2. A variable can only hold one value.
Question. What is the value of variable x after the following assignment statements have all been performed?
int x; x = 10; x = x - 2; x = x * 2;Answer[7]