Program Implementation - AP Computer Science A
Card 0 of 693
Class Person {
int height;
float weight;
``
public:
int getHeight();
void setHeight(int);
float getWeight();
void setWeight(float);
};
What is the access level of height
and weight
?
Class Person {
int height;
float weight;
``
public:
int getHeight();
void setHeight(int);
float getWeight();
void setWeight(float);
};
What is the access level of height
and weight
?
Until an access specifier is given, all class members are implicitly private. All members defined after an access specifier is used will will have that access level until another access specifier is explicitly invoked. Since no access specifier was used, weight
and height
are automatically private.
Note that virtual
is not an access keyword.
Until an access specifier is given, all class members are implicitly private. All members defined after an access specifier is used will will have that access level until another access specifier is explicitly invoked. Since no access specifier was used, weight
and height
are automatically private.
Note that virtual
is not an access keyword.
Compare your answer with the correct one above
Consider the following code:
public static class Clock {
private int seconds;
``
public Clock(int s) {
seconds = s;
}
``
public void setTime(int s) {
seconds = s;
}
``
public void setSeconds(int s) {
int hoursMinutes = seconds - seconds % 60;
seconds = hoursMinutes + s;
}
``
public void setMinutes(int min) {
int hours = seconds / 3600;
int currentSeconds = seconds % 60;
seconds = hours + min * 60 + currentSeconds;
}
}
Which of the following represents a method that returns the minute value of the clock?
Consider the following code:
public static class Clock {
private int seconds;
``
public Clock(int s) {
seconds = s;
}
``
public void setTime(int s) {
seconds = s;
}
``
public void setSeconds(int s) {
int hoursMinutes = seconds - seconds % 60;
seconds = hoursMinutes + s;
}
``
public void setMinutes(int min) {
int hours = seconds / 3600;
int currentSeconds = seconds % 60;
seconds = hours + min * 60 + currentSeconds;
}
}
Which of the following represents a method that returns the minute value of the clock?
This clock class is defined as having only seconds in its fields, so you have to convert this value for any of the accessors and mutators. Therefore, you need to perform careful (though simple) mathematics for this conversion. To calculate the number of minutes in a given number of seconds, you first need to remove the hours from total count. First, compute the hours using integer division (which will drop the fractional portion of the decimal). This is:
int hours = seconds / 3600;
Next, you need to figure out how many seconds are in that value of hours. This is helpful precisely because integer division drops the decimal portion. Thus, you will subtract off:
hours * 3600
from the total seconds.
This gives you the seconds that apply to the minutes and seconds of the time. Therefore, you will finally need to divide by 60 to isolate the minutes.
This clock class is defined as having only seconds in its fields, so you have to convert this value for any of the accessors and mutators. Therefore, you need to perform careful (though simple) mathematics for this conversion. To calculate the number of minutes in a given number of seconds, you first need to remove the hours from total count. First, compute the hours using integer division (which will drop the fractional portion of the decimal). This is:
int hours = seconds / 3600;
Next, you need to figure out how many seconds are in that value of hours. This is helpful precisely because integer division drops the decimal portion. Thus, you will subtract off:
hours * 3600
from the total seconds.
This gives you the seconds that apply to the minutes and seconds of the time. Therefore, you will finally need to divide by 60 to isolate the minutes.
Compare your answer with the correct one above
Consider the following code :
public class Clock {
private int seconds;
``
public Clock(int s) {
seconds = s;
}
``
public void setTime(int s) {
seconds = s;
}
``
public void setSeconds(int s) {
int hoursMinutes = seconds - seconds % 60;
seconds = hoursMinutes + s;
}
``
public void setMinutes(int min) {
int hours = seconds / 3600;
int currentSeconds = seconds % 60;
seconds = hours + min * 60 + currentSeconds;
}
}
Which of the following defines a toString method that will output the time in 24-hour format in the following form:
1:51:03
(Notice that you need to pad the minutes and seconds. You can call 12 midnight "0".)
Consider the following code :
public class Clock {
private int seconds;
``
public Clock(int s) {
seconds = s;
}
``
public void setTime(int s) {
seconds = s;
}
``
public void setSeconds(int s) {
int hoursMinutes = seconds - seconds % 60;
seconds = hoursMinutes + s;
}
``
public void setMinutes(int min) {
int hours = seconds / 3600;
int currentSeconds = seconds % 60;
seconds = hours + min * 60 + currentSeconds;
}
}
Which of the following defines a toString method that will output the time in 24-hour format in the following form:
1:51:03
(Notice that you need to pad the minutes and seconds. You can call 12 midnight "0".)
There are several points to be noted in this code. First, you need to calculate each of the constituent parts from the seconds stored in the class. The "display value" of seconds is relatively easy. This is just the remainder of a division by 60. Consider:
61 seconds => This is really 1 minute and 1 second.
155 seconds => This is really 2 minutes and 35 seconds.
So, you know that the display seconds are:
seconds % 60
You must compute the hours using integer division (which will drop the fractional portion of the decimal). This is:
int hours = seconds / 3600;
Next, you need to figure out how many seconds are in that value of hours. This is helpful precisely because integer division drops the decimal portion. Thus, you will subtract off:
hours * 3600
from the total seconds.
This gives you the seconds that apply to the minutes and seconds of the time. Therefore, you will finally need to divide by 60 to isolate the minutes.
Then, you must pad the values. This is not done using +=
, which would add the "0" character to the end of the string. Instead, it is done by the form:
secString = "0" + secString;
There are several points to be noted in this code. First, you need to calculate each of the constituent parts from the seconds stored in the class. The "display value" of seconds is relatively easy. This is just the remainder of a division by 60. Consider:
61 seconds => This is really 1 minute and 1 second.
155 seconds => This is really 2 minutes and 35 seconds.
So, you know that the display seconds are:
seconds % 60
You must compute the hours using integer division (which will drop the fractional portion of the decimal). This is:
int hours = seconds / 3600;
Next, you need to figure out how many seconds are in that value of hours. This is helpful precisely because integer division drops the decimal portion. Thus, you will subtract off:
hours * 3600
from the total seconds.
This gives you the seconds that apply to the minutes and seconds of the time. Therefore, you will finally need to divide by 60 to isolate the minutes.
Then, you must pad the values. This is not done using +=
, which would add the "0" character to the end of the string. Instead, it is done by the form:
secString = "0" + secString;
Compare your answer with the correct one above
Given a vector of ints called "intVec", write a "ranged for" loop, also sometimes known as a "for each" loop, to double the values fof all elements in a vector. (In C++)
Given a vector of ints called "intVec", write a "ranged for" loop, also sometimes known as a "for each" loop, to double the values fof all elements in a vector. (In C++)
A "for each" loop was introduced in C++ 11 which allows the user to loops through a container of items without writing a traditional loop. Let's take a look at all the choices.
for( int i : intVec(){
i * = 2;
}
Although this looks like the correct answer, it's not. The int i in the first part of the for loop is passed in "by value", which means that a copy of intVec will be made and the integers inside the copy will be doubled. The integers inside the original intVec vector will be unaffected. To fix this problem, int i needs to be passed into the for loop "by reference", which is done by adding a "&" symbol after "int".
The correct loop is:
for( int& i : intVec(){
i * = 2;
}
Let's take a look at the other choices:
for( int& i : intVec(){
i = 2;
}
This one will not work because it is setting all items in intVec to 2, not doubling them.
All the other for loops are not "for each" loops so they are incorrect even if they accomplish the same output.
A "for each" loop was introduced in C++ 11 which allows the user to loops through a container of items without writing a traditional loop. Let's take a look at all the choices.
for( int i : intVec(){
i * = 2;
}
Although this looks like the correct answer, it's not. The int i in the first part of the for loop is passed in "by value", which means that a copy of intVec will be made and the integers inside the copy will be doubled. The integers inside the original intVec vector will be unaffected. To fix this problem, int i needs to be passed into the for loop "by reference", which is done by adding a "&" symbol after "int".
The correct loop is:
for( int& i : intVec(){
i * = 2;
}
Let's take a look at the other choices:
for( int& i : intVec(){
i = 2;
}
This one will not work because it is setting all items in intVec to 2, not doubling them.
All the other for loops are not "for each" loops so they are incorrect even if they accomplish the same output.
Compare your answer with the correct one above
Consider the following code:
int\[\] vals = {6,1,41,5,1};
int\[\]\[\] newVals = new int\[vals.length\]\[\];
for(int i = 0; i < vals.length; i++) {
newVals\[i\] = new int\[vals\[i\]\];
for(int j = 0; j < vals\[i\];j++) {
newVals\[i\]\[j\] = vals\[i\] * (j+1);
}
}
What does the code above do?
Consider the following code:
int\[\] vals = {6,1,41,5,1};
int\[\]\[\] newVals = new int\[vals.length\]\[\];
for(int i = 0; i < vals.length; i++) {
newVals\[i\] = new int\[vals\[i\]\];
for(int j = 0; j < vals\[i\];j++) {
newVals\[i\]\[j\] = vals\[i\] * (j+1);
}
}
What does the code above do?
Let's look at the main loop in this program:
for(int i = 0; i < vals.length; i++) {
newVals\[i\] = new int\[vals\[i\]\];
for(int j = 0; j < vals\[i\];j++) {
newVals\[i\]\[j\] = vals\[i\] * (j+1);
}
}
The first loop clearly runs through the vals array for the number of items in that array. After this, it creates in the newVals 2D array a second dimension that is as long as the value in the input array vals. Thus, for 41, it creates a 3rd row in newVals that is 41 columns wide.
Then, we go to the second loop. This one iterates from 0 to the value stored in the current location in vals. It places in the given 2D array location the multiple of the value. Think of j + 1. This will go from 1 to 41 for the case of 41 (and likewise for all the values). Thus, you create a 2D array with all the multiples of the initial vals array.
Let's look at the main loop in this program:
for(int i = 0; i < vals.length; i++) {
newVals\[i\] = new int\[vals\[i\]\];
for(int j = 0; j < vals\[i\];j++) {
newVals\[i\]\[j\] = vals\[i\] * (j+1);
}
}
The first loop clearly runs through the vals array for the number of items in that array. After this, it creates in the newVals 2D array a second dimension that is as long as the value in the input array vals. Thus, for 41, it creates a 3rd row in newVals that is 41 columns wide.
Then, we go to the second loop. This one iterates from 0 to the value stored in the current location in vals. It places in the given 2D array location the multiple of the value. Think of j + 1. This will go from 1 to 41 for the case of 41 (and likewise for all the values). Thus, you create a 2D array with all the multiples of the initial vals array.
Compare your answer with the correct one above
Which of the following blocks of code will output an evenly-spaced 2D array (i.e. an evenly-spaced matrix)? For example, a simple evenly-spaced matrix is:
1 2 3
4 5 6
7 8 9
Which of the following blocks of code will output an evenly-spaced 2D array (i.e. an evenly-spaced matrix)? For example, a simple evenly-spaced matrix is:
1 2 3
4 5 6
7 8 9
There are several critical points to look at in the code given as possible answers above.
First, you need to make sure that the main output is not a new line. Thus, the following is incorrect:
System.out.println(matrix\[i\]\[j\]);
This would create a new line for every single value!
Next, you need to make sure that a new line is output after every row of the matrix. This is the final output statement. Thus, it cannot be:
System.out.print(" ");
This would only output a character with no new line.
Finally, for everything except for the first element of each row, you will need to output sufficient padding before the given element element (so as to make the matrix to be evenly-spaced). We are not going to be too particular here about the problem of very big numbers—the values are given to us as is. Note that it is insufficient to use a mere space for this. You should use a tab character (defined as '\t'). A space will not guarantee enough spacing (no pun intended)!
The correct answer has the following logic:
if(j != 0) {
System.out.print("\t\t");
}
This means "when the column is not the first column" (i.e. j != 0), "then output tabs to space sufficiently."
There are several critical points to look at in the code given as possible answers above.
First, you need to make sure that the main output is not a new line. Thus, the following is incorrect:
System.out.println(matrix\[i\]\[j\]);
This would create a new line for every single value!
Next, you need to make sure that a new line is output after every row of the matrix. This is the final output statement. Thus, it cannot be:
System.out.print(" ");
This would only output a character with no new line.
Finally, for everything except for the first element of each row, you will need to output sufficient padding before the given element element (so as to make the matrix to be evenly-spaced). We are not going to be too particular here about the problem of very big numbers—the values are given to us as is. Note that it is insufficient to use a mere space for this. You should use a tab character (defined as '\t'). A space will not guarantee enough spacing (no pun intended)!
The correct answer has the following logic:
if(j != 0) {
System.out.print("\t\t");
}
This means "when the column is not the first column" (i.e. j != 0), "then output tabs to space sufficiently."
Compare your answer with the correct one above
Consider the following code:
for(int i = 1; i <= 10; i++) {
for(int j = 0; j < (20 - i * 2) / 2; j++) {
System.out.print(" ");
}
for(int j = 0; j < i * 2; j++) {
System.out.print("*");
}
for(int j = 0; j < (20 - i * 2) / 2; j++) {
System.out.print(" ");
}
System.out.println();
}
Describe the output of the code above.
Consider the following code:
for(int i = 1; i <= 10; i++) {
for(int j = 0; j < (20 - i * 2) / 2; j++) {
System.out.print(" ");
}
for(int j = 0; j < i * 2; j++) {
System.out.print("*");
}
for(int j = 0; j < (20 - i * 2) / 2; j++) {
System.out.print(" ");
}
System.out.println();
}
Describe the output of the code above.
This code is best explained by analyzing it directly. Comments will be provided in bold below:
// The loop runs from 1 to 10
for(int i = 1; i <= 10; i++) {
// First, you run through 0 to some number
// That number is computed by taking the current value of i, doubling it,
// subtracting that from 20, then dividing by 2.
// So, consider the following values for i:
// 0: 20 - 0 = 20; Divided by 2: 10
// 1: 20 - 2 = 18; Divided by 2: 9
// 2: 20 - 2 = 16; Divided by 2: 8
// etc...
// Thus, you will output single spaces that number of times (10, 9, 8...)
for(int j = 0; j < (20 - i * 2) / 2; j++) {
System.out.print(" ");
}
// Next, you will output an asterix i * 2 number of times. Thus, your
// smallest value is 2 and your largest 20.
for(int j = 0; j < i * 2; j++) {
System.out.print("*");
}
// This is just a repeat of the same loop from above
for(int j = 0; j < (20 - i * 2) / 2; j++) {
System.out.print(" ");
}
// This bumps us down to the next line
System.out.println();
}
Thus, you have output that basically has even padding on the left and right, with an increasing number of asterix characters (2, 4, 6, etc). This is an upward-facing arrow, having a point of width 2 and a base of width 20.
This code is best explained by analyzing it directly. Comments will be provided in bold below:
// The loop runs from 1 to 10
for(int i = 1; i <= 10; i++) {
// First, you run through 0 to some number
// That number is computed by taking the current value of i, doubling it,
// subtracting that from 20, then dividing by 2.
// So, consider the following values for i:
// 0: 20 - 0 = 20; Divided by 2: 10
// 1: 20 - 2 = 18; Divided by 2: 9
// 2: 20 - 2 = 16; Divided by 2: 8
// etc...
// Thus, you will output single spaces that number of times (10, 9, 8...)
for(int j = 0; j < (20 - i * 2) / 2; j++) {
System.out.print(" ");
}
// Next, you will output an asterix i * 2 number of times. Thus, your
// smallest value is 2 and your largest 20.
for(int j = 0; j < i * 2; j++) {
System.out.print("*");
}
// This is just a repeat of the same loop from above
for(int j = 0; j < (20 - i * 2) / 2; j++) {
System.out.print(" ");
}
// This bumps us down to the next line
System.out.println();
}
Thus, you have output that basically has even padding on the left and right, with an increasing number of asterix characters (2, 4, 6, etc). This is an upward-facing arrow, having a point of width 2 and a base of width 20.
Compare your answer with the correct one above
Consider the following code:

What is the output of the method call mystery("Green eggs and ham")
Consider the following code:
What is the output of the method call mystery("Green eggs and ham")
The method String.split() splits a String into an array of Strings separated according to the expression within the method argument. The expression String.split("") splits the String at every character. The "for" loop concatenates the elements of the String array together, separated by a comma.
The method String.split() splits a String into an array of Strings separated according to the expression within the method argument. The expression String.split("") splits the String at every character. The "for" loop concatenates the elements of the String array together, separated by a comma.
Compare your answer with the correct one above
public static void main(String[] args) {
int[][] x = {{4,5,6,7},{91,15,14,13}};
int[][] y = {{-13,4,41,14},{14,5,13,3}};
int[][] z = doWork(x,y);
for(int i = 0; i < z.length; i++) {
for(int j = 0; j < z[0].length;j++) {
System.out.print(z[i][j] + " ");
}
System.out.println();
}
}
``
public static int[][] doWork(int[][] a, int[][] b) {
int[][] ret = new int[a.length][a[0].length];
for(int i = 0; i < a.length; i++) {
for(int j = 0; j < a[i].length; j++) {
ret[i][j] = a[i][j] + b[i][j];
}
}
return ret;
}
What is the console output for the code above?
public static void main(String[] args) {
int[][] x = {{4,5,6,7},{91,15,14,13}};
int[][] y = {{-13,4,41,14},{14,5,13,3}};
int[][] z = doWork(x,y);
for(int i = 0; i < z.length; i++) {
for(int j = 0; j < z[0].length;j++) {
System.out.print(z[i][j] + " ");
}
System.out.println();
}
}
``
public static int[][] doWork(int[][] a, int[][] b) {
int[][] ret = new int[a.length][a[0].length];
for(int i = 0; i < a.length; i++) {
for(int j = 0; j < a[i].length; j++) {
ret[i][j] = a[i][j] + b[i][j];
}
}
return ret;
}
What is the console output for the code above?
The doWork
method implements a relatively standard type of 2D array iteration, one that goes through each element. The outer loop goes through the first dimension of the array. Then, the inner loop provides index for the second dimension. From this, you get the total 2D index [i][j]
. The line ret[i][j] = a[i][j] + b[i][j];
actually performs the operation at the given index. Here, it performs an addition, combining the values at [i][j]
found in the two arrays. This gives you the sum at each index of ret
. The main method outputs each of these values, following the same standard algorithm for 2D array traversal.
The doWork
method implements a relatively standard type of 2D array iteration, one that goes through each element. The outer loop goes through the first dimension of the array. Then, the inner loop provides index for the second dimension. From this, you get the total 2D index [i][j]
. The line ret[i][j] = a[i][j] + b[i][j];
actually performs the operation at the given index. Here, it performs an addition, combining the values at [i][j]
found in the two arrays. This gives you the sum at each index of ret
. The main method outputs each of these values, following the same standard algorithm for 2D array traversal.
Compare your answer with the correct one above
LOGIC WITH 2-D ARRAYS
Given:
int\[\]\[\] myArray = { {1, 2},
{3, 4} };
What would the following statement print out to the console?
System.out.print(myArray\[1\]\[1\] + 10);
LOGIC WITH 2-D ARRAYS
Given:
int\[\]\[\] myArray = { {1, 2},
{3, 4} };
What would the following statement print out to the console?
System.out.print(myArray\[1\]\[1\] + 10);
Before anything is printed out into the console, the following is first evaluated:
myArray\[1\]\[1\] + 10
myArray\[1\]\[1\] is referring to the item that is in row=1 and column=1 of myArray. Taking note that arrays start with row 0 and column 0, we see that the item in row 1 column 1 is the number 4. Now we have the following: 4+10. This evaluates to 14. Therefore, the Java print statement will print out the number 14 on the console.
Before anything is printed out into the console, the following is first evaluated:
myArray\[1\]\[1\] + 10
myArray\[1\]\[1\] is referring to the item that is in row=1 and column=1 of myArray. Taking note that arrays start with row 0 and column 0, we see that the item in row 1 column 1 is the number 4. Now we have the following: 4+10. This evaluates to 14. Therefore, the Java print statement will print out the number 14 on the console.
Compare your answer with the correct one above
int a = 10, b = 5;
for(int i = 0; i < a; i+=2) {
for(int j = 0; j < i % b; j++) {
System.out.print("* ");
}
System.out.println();
}
What will be the console output for the code above?
int a = 10, b = 5;
for(int i = 0; i < a; i+=2) {
for(int j = 0; j < i % b; j++) {
System.out.print("* ");
}
System.out.println();
}
What will be the console output for the code above?
All this problem requires is careful attention to the loop control variables. Notice that the first loop adds 2 to i every looping. This means that it will run for 0,2,4,6, and 8. Thus, a total of five lines will be printed.
Now, the second loop dictates the number of * characters that will be output per line. This is going to be based upon the result of the modulus i % b. Remember, modulus is a remainder calculation. Thus, you will have:
0 % 5 = 0
2 % 5 = 2
4 % 5 = 4
6 % 5 = 1
8 % 5 = 3
Hence, you will have the following (note the first line is empty, given the result of 0 % 5):
* *
* * * *
*
* * *
All this problem requires is careful attention to the loop control variables. Notice that the first loop adds 2 to i every looping. This means that it will run for 0,2,4,6, and 8. Thus, a total of five lines will be printed.
Now, the second loop dictates the number of * characters that will be output per line. This is going to be based upon the result of the modulus i % b. Remember, modulus is a remainder calculation. Thus, you will have:
0 % 5 = 0
2 % 5 = 2
4 % 5 = 4
6 % 5 = 1
8 % 5 = 3
Hence, you will have the following (note the first line is empty, given the result of 0 % 5):
* *
* * * *
*
* * *
Compare your answer with the correct one above
class Base{
public:
void foo(int n) { cout << "Base::foo(int)
"; }
};
class Derive: public Base{
public:
void foo(double n) { cout << "Derived::foo(double)
";}
};
int main(){
Derived der;
der.foo(42);
}
The above code is written in C++, what is the output of the program?
class Base{
public:
void foo(int n) { cout << "Base::foo(int) "; }
};
class Derive: public Base{
public:
void foo(double n) { cout << "Derived::foo(double) ";}
};
int main(){
Derived der;
der.foo(42);
}
The above code is written in C++, what is the output of the program?
This is an example of inheritance. The child class (Derived) is an inherited class of the parent class (Base). When the Derived object is created and the "foo" method is called, foo in the Derived class will be called. If there is the same method in the parent class and child class, the child's method will be called.
This is an example of inheritance. The child class (Derived) is an inherited class of the parent class (Base). When the Derived object is created and the "foo" method is called, foo in the Derived class will be called. If there is the same method in the parent class and child class, the child's method will be called.
Compare your answer with the correct one above
What will the following code result in?
int main(){
int i = 7;
const int * ip = &i;
cout<< *ip << endl;
}
What will the following code result in?
int main(){
int i = 7;
const int * ip = &i;
cout<< *ip << endl;
}
Let's take a look at the code.
int i = 7;
This line assigns 7 to the variable "i".
const int * ip = &i;
This line creates a constant int pointer and assigns the address of "i" to the pointer.
cout << *ip << endl;
This line prints the dereference of the pointer, which holds the value 7.
Let's take a look at the code.
int i = 7;
This line assigns 7 to the variable "i".
const int * ip = &i;
This line creates a constant int pointer and assigns the address of "i" to the pointer.
cout << *ip << endl;
This line prints the dereference of the pointer, which holds the value 7.
Compare your answer with the correct one above
What is the output of this program?
arr = \["hello", "my", "name", "is"\]
for (int i = 0; i < arr.length - 1; i++) {
System.out.println(arr\[i\]);
}
System.out.println("Sandra");
What is the output of this program?
arr = \["hello", "my", "name", "is"\]
for (int i = 0; i < arr.length - 1; i++) {
System.out.println(arr\[i\]);
}
System.out.println("Sandra");
The words are printed on separate lines due to the System.out.println() call and then whatever is inside of the parentheses is printed on the next line. This call is different from System.out.print() which prints words on the same lines.
Therefore, the Sysytem.out.printIn gives("Sandra"):
hello
my
name
is
Sandra
The words are printed on separate lines due to the System.out.println() call and then whatever is inside of the parentheses is printed on the next line. This call is different from System.out.print() which prints words on the same lines.
Therefore, the Sysytem.out.printIn gives("Sandra"):
hello
my
name
is
Sandra
Compare your answer with the correct one above
Which of the following code samples adequately uses constants?
Which of the following code samples adequately uses constants?
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.
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
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;
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;
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.
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
Which of the following represents an acceptable definition of an interface?
Which of the following represents an acceptable definition of an interface?
An interface cannot have any member data or implementations for its methods. It only defines a set of methods that are required by anything that implements that interface. Therefore, the only option that is valid is the interface defined as Shape2D
.
An interface cannot have any member data or implementations for its methods. It only defines a set of methods that are required by anything that implements that interface. Therefore, the only option that is valid is the interface defined as Shape2D
.
Compare your answer with the correct one above
Which of the following represents a valid declaration of an interface and a class that implements that interface?
Which of the following represents a valid declaration of an interface and a class that implements that interface?
In order to implement an interface, you must use the syntax "implements ". Therefore, for this question, you must choose an option that has implements Shape2D
. Also, you must make sure that all of your methods are defined in your class just as they are defined in the interface declaration. You will notice that a variety of the incorrect answers do not do this but instead have wrong types or names in various places.
In order to implement an interface, you must use the syntax "implements implements Shape2D
. Also, you must make sure that all of your methods are defined in your class just as they are defined in the interface declaration. You will notice that a variety of the incorrect answers do not do this but instead have wrong types or names in various places.
Compare your answer with the correct one above
Consider the following code:
public static interface Shape2D {
public double getArea();
}
``
public static class Ellipse implements Shape2D {
private double r1,r2;
public Ellipse(double r1,double r2) {
this.r1 = r1;
this.r2 = r2;
}
public double getArea() {
return Math.PI * r1 * r2;
}
}
public static class Circle extends Ellipse {
private double radius;
public Circle(double r) {
super(r,r);
}
public double getArea() {
return super.getArea();
}
public double getCircumference() {
return Math.PI * 2 * radius;
}
}
``
public static void main(String[] args) {
Shape2D[] vals = {new Circle(5),new Ellipse(8,5)};
for(int i = 0; i < vals.length; i++) {
System.out.println("Area " + (i+1) + ": " + vals[i].getArea());
}
}
What is the output for this code?
Consider the following code:
public static interface Shape2D {
public double getArea();
}
``
public static class Ellipse implements Shape2D {
private double r1,r2;
public Ellipse(double r1,double r2) {
this.r1 = r1;
this.r2 = r2;
}
public double getArea() {
return Math.PI * r1 * r2;
}
}
public static class Circle extends Ellipse {
private double radius;
public Circle(double r) {
super(r,r);
}
public double getArea() {
return super.getArea();
}
public double getCircumference() {
return Math.PI * 2 * radius;
}
}
``
public static void main(String[] args) {
Shape2D[] vals = {new Circle(5),new Ellipse(8,5)};
for(int i = 0; i < vals.length; i++) {
System.out.println("Area " + (i+1) + ": " + vals[i].getArea());
}
}
What is the output for this code?
We are dealing here both with the implementation of an interface as well as inheritance. Notice that the Circle
class has a getArea
method that uses the superclass's getArea
method. This equation is
, but for the Circle
, so the equation is the same as the standard
. This loop will iterate through the objects, using the appropriate method in each case. Thus, you will get two values:
, which is relatively close to
or
.
, which is relatively close to
or
.
Those are close enough to help you estimate for the output.
(Notice that the line numbers need to be "1" and "2".)
We are dealing here both with the implementation of an interface as well as inheritance. Notice that the Circle
class has a getArea
method that uses the superclass's getArea
method. This equation is , but for the Circle
, so the equation is the same as the standard
. This loop will iterate through the objects, using the appropriate method in each case. Thus, you will get two values:
, which is relatively close to
or
.
, which is relatively close to
or
.
Those are close enough to help you estimate for the output.
(Notice that the line numbers need to be "1" and "2".)
Compare your answer with the correct one above
Which of the following declares an interface to be used for anything that can implement the actions of a sink?
Which of the following declares an interface to be used for anything that can implement the actions of a sink?
First of all, the question does ask for an interface. This is a type of declaration in Java, so you should use that for your answer. This allows you to eliminate two of the incorrect options. Granting this, you then know that you need to look at the options that use the interface keyword. Recall that for interfaces, you provide no implementation whatsoever. Thus, the other two wrong answers are the ones that provide method bodies. This cannot be done for interfaces, which merely define what something should do but do not actually implement it.
First of all, the question does ask for an interface. This is a type of declaration in Java, so you should use that for your answer. This allows you to eliminate two of the incorrect options. Granting this, you then know that you need to look at the options that use the interface keyword. Recall that for interfaces, you provide no implementation whatsoever. Thus, the other two wrong answers are the ones that provide method bodies. This cannot be done for interfaces, which merely define what something should do but do not actually implement it.
Compare your answer with the correct one above