AP Computer Science A : Constant Declarations

Study concepts, example questions & explanations for AP Computer Science A

varsity tutors app store varsity tutors android store

Example Questions

Example Question #1 : Programming Constructs

Which of the following code samples adequately uses constants?

Possible Answers:

final int rows = 4;

for(int i = 0,l = rows; i < l; i++) {

    rows += 2;

}

final String s = "Hello, "

int intVal;

// Variable intVal read in during this code.... Excerpted...

if(intVal < 0) {

    s += "World!";

} else if(intVal == 0) {

    s += "People!";

} else {

    s += "Folks!";

}

for(final int i = 0, rows = 5; i < rows; i++) {

    System.out.println(i);

}

const int rows = 4;

for(int i = 0; i < rows; i++) {

    System.out.println(i);

}

 

final int rows;

int intVal;

// Variable intVal read in during this code.... Excerpted...

rows = intVal;

for(int i = 0; i < rows; i++) {

    System.out.println(i);

}

 

Correct answer:

final int rows;

int intVal;

// Variable intVal read in during this code.... Excerpted...

rows = intVal;

for(int i = 0; i < rows; i++) {

    System.out.println(i);

}

 

Explanation:

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.

Example Question #1 : Programming Constructs

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;

Possible Answers:

k = 50 + 20 * j;

l = m * i + j;

j = m + i;

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

l += l;

Correct answer:

j = m + i;

Explanation:

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.

Learning Tools by Varsity Tutors