PROGRAMMING FUNDAMENTALS › JAVA FUNDAMENTALS
Start with the complete Java statement before separating its parts:
int score = 10;The word int occupies the required type position. It tells Java what kind of value this variable is meant to hold. The word score is the variable name, so it gives the storage location a way to be referred to later. The literal 10 is the initial value, the value placed there when score is created. Together, this Java statement declares score and initializes it to 10.
In int score = 10;, which option correctly identifies the parts?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
After score exists, you can give that same variable a different value:
int score = 10;
score = 15;The first statement performs initialization, which means placing the first stored value into a newly declared variable. The second statement performs reassignment, which means replacing the value already stored in score. It does not need int because score already has a declaration. The name score on the second line refers to the existing storage location.
Writing int again would change the second line into another declaration:
int score = 10;
int score = 15;The two statements execute in order. Immediately after int score = 10;, the variable score holds 10. When score = 15; executes, Java stores 15 in that same variable and replaces the 10. After both statements, reading score produces 15.
The variable does not retain both values as its current contents. The earlier 10 was the value held at an earlier moment, not a second value waiting beside 15. Reassignment also does not create a new variable, because no new declaration occurs.
Fix the second line so it reassigns the existing variable score.
int score = 10;
int score = 15;Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
score is a legal Java identifier, so it can be used as the variable name in the declaration and in the reassignment. Java is case-sensitive: score and Score are different names. Writing Score later does not refer to the variable named score, even though the two names differ by only one capital letter.
An identifier can start with a Java letter, underscore, or dollar sign. After the first character, it can also contain digits. Therefore score2 and _score follow the character rules, while 2score does not because it starts with a digit. A hyphen is not part of an identifier. A reserved Java keyword cannot be used as a variable name either.
int score = 10;
score = 15;
Score = 15;