Constant Declarations - Computer Science

Card 0 of 2

Question

Which of the following code samples adequately uses constants?

Answer

Remember that a constant variable cannot be changed once it has been assigned. Normally, you assign the variable immediately on the same line as the declaration. However, if you were to create the constant and wait to assign a value, that would be find syntactically as well. Thus, the correct answer does not have a problem, though it might appear so at first if you did not know this. Now, remember that the way to declare a constant is to use the keyword "final". (The keyword "const" works in some other languages like C++.) All of the incorrect answers (other than the one using "const") alter the constant after it has been defined.

Compare your answer with the correct one above

Question

In the following block of code, which of the following lines contains an error?

final int i = 20, j, k;

int l,m=50,n = 2;

j = n + m;

l = m * i + j;

for(int a = 0; a < m; a++) {

l += l;

}

m = 20 + j + n * i + m;

j = m + i;

k = 50 + 20 * j;

Answer

The line

j = m + i;

has an error because it contains a reassignment to a constant (final) variable. You are permitted to assign a constant on a line that is not the line of declaration. However, once you do this, you cannot reassign a value. The variable j was assigned a value on the line:

j = n + m;

Thus, the line above (j = m + i;) represents a re-assignment, hence causing an error.

Compare your answer with the correct one above

Tap the card to reveal the answer