Common Data Structures - AP Computer Science A
Card 0 of 308
Write a program that iterates through this data structure and prints the data (choose the best answer):
List<List<String>> listOflistOfStrings = new ArrayList<ArrayList<String>>();
Write a program that iterates through this data structure and prints the data (choose the best answer):
List<List<String>> listOflistOfStrings = new ArrayList<ArrayList<String>>();
The correct answer uses a ForEach loop. A ForEach loop is recommended for iterating through Lists because Lists contain iterators. ForEach loops use the iterator to iterate through the List. One of the answers used a regular For loop, while the answer was correct, it was not the best choice.
The correct answer uses a ForEach loop. A ForEach loop is recommended for iterating through Lists because Lists contain iterators. ForEach loops use the iterator to iterate through the List. One of the answers used a regular For loop, while the answer was correct, it was not the best choice.
Compare your answer with the correct one above
Consider the code below:
String\[\] db = {"Harvey","Plutarch","Frege","Radulphus"};
ArrayList names = new ArrayList();
for(int i = 0; i < 12; i++) {
names.add(db\[i % db.length\]);
}
for(int i = 0; i < 12; i++) {
if(names.get(i).equals("Frege")) {
names.remove(i);
}
}
What is the bug in the code above?
Consider the code below:
String\[\] db = {"Harvey","Plutarch","Frege","Radulphus"};
ArrayList
for(int i = 0; i < 12; i++) {
names.add(db\[i % db.length\]);
}
for(int i = 0; i < 12; i++) {
if(names.get(i).equals("Frege")) {
names.remove(i);
}
}
What is the bug in the code above?
In the second loop, when you remove one of the items, you thus make the ArrayList one element shorter. This means that if you attempt to go through to index 11, you will receive an error at some point, for the list will have "shrunk". This is like an array out of bounds error, though it will be an IndexOutOfBoundsException exception.
In the second loop, when you remove one of the items, you thus make the ArrayList one element shorter. This means that if you attempt to go through to index 11, you will receive an error at some point, for the list will have "shrunk". This is like an array out of bounds error, though it will be an IndexOutOfBoundsException exception.
Compare your answer with the correct one above
Consider the following code:
public static class Circle {
private double radius;
public Circle(double r) {
radius = r;
}
public double getArea() {
return radius * radius * Math.PI;
}
}
public static void main(String\[\] args) {
ArrayList circles = new ArrayList();
for(int i = 0; i < 10; i++) {
circles.add(new Circle(i + 4 * 2));
}
}
Which of the following represents code for iterating through the list circles in order to output the areas of the circles contained therein?
Consider the following code:
public static class Circle {
private double radius;
public Circle(double r) {
radius = r;
}
public double getArea() {
return radius * radius * Math.PI;
}
}
public static void main(String\[\] args) {
ArrayList
for(int i = 0; i < 10; i++) {
circles.add(new Circle(i + 4 * 2));
}
}
Which of the following represents code for iterating through the list circles in order to output the areas of the circles contained therein?
In the answers, there are only two issues to consider. On the one hand, look at the loop control statement. It is some variant on:
circle.size()
and
circles.length
For the List types, you need to use the method size(), not length (which you use for arrays). Likewise, one way to extract elements from the ArrayList type is to use the .get method. You must use this and not the brackets \[\] that you use for arrays.
In the answers, there are only two issues to consider. On the one hand, look at the loop control statement. It is some variant on:
circle.size()
and
circles.length
For the List types, you need to use the method size(), not length (which you use for arrays). Likewise, one way to extract elements from the ArrayList type is to use the .get method. You must use this and not the brackets \[\] that you use for arrays.
Compare your answer with the correct one above
Consider the code below:
ArrayList myPhilosophers = new ArrayList();
myPhilosophers.add("Frege");
myPhilosophers.add("Husserl");
myPhilosophers.add("Hegel");
myPhilosophers.add("Bill");
myPhilosophers.add("Frederick");
for(int i = 0; i < myPhilosophers.size(); i++) {
String s = myPhilosophers.get(i);
if(s.charAt(0) >= 'H' || s.charAt(3) < 'd') {
myPhilosophers.set(i, s.toUpperCase());
}
}
System.out.println(myPhilosophers);
What is the output for the code above?
Consider the code below:
ArrayList
myPhilosophers.add("Frege");
myPhilosophers.add("Husserl");
myPhilosophers.add("Hegel");
myPhilosophers.add("Bill");
myPhilosophers.add("Frederick");
for(int i = 0; i < myPhilosophers.size(); i++) {
String s = myPhilosophers.get(i);
if(s.charAt(0) >= 'H' || s.charAt(3) < 'd') {
myPhilosophers.set(i, s.toUpperCase());
}
}
System.out.println(myPhilosophers);
What is the output for the code above?
Consider the logic that is in the loop. The if statement will be reached either if you:
- Have a first character that is H or later in the alphabet (in capital letters).
- Have a fourth character that is less than d.
The first case applies to "Husserl" and "Hegel." However, the second does not apply to any—not even to "Frederick", for d is equal to d, not less than it!
Consider the logic that is in the loop. The if statement will be reached either if you:
- Have a first character that is H or later in the alphabet (in capital letters).
- Have a fourth character that is less than d.
The first case applies to "Husserl" and "Hegel." However, the second does not apply to any—not even to "Frederick", for d is equal to d, not less than it!
Compare your answer with the correct one above
Which of the following is NOT a valid declaration for an ArrayList?
Which of the following is NOT a valid declaration for an ArrayList?
ArrayLists are lists of objects, and thus cannot store primitive types. If you wish to store primitive types in an ArrayList, container objects such as Double or Integer must instead be used. The object reference type List is a valid reference type for an ArrayList object.
ArrayLists are lists of objects, and thus cannot store primitive types. If you wish to store primitive types in an ArrayList, container objects such as Double or Integer must instead be used. The object reference type List is a valid reference type for an ArrayList object.
Compare your answer with the correct one above
Which of the following is NOT a difference between the Array class and the ArrayList class in Java?
Which of the following is NOT a difference between the Array class and the ArrayList class in Java?
In Java, Array is a fixed length data structure, while ArrayList is a variable length Collection Class (other Collection class members include HashMap and HashSet). This means that an Array cannot change its size once it's made; a whole new Array must be made. ArrayLists can change size at will.
Arrays can reference both primitives (like int
) and types (like Integer
). ArrayLists can only reference types, not primitives. Through a method called "Autoboxing", it can appear that an ArrayList stores a primitive, but what it really is doing is automatically masking the primitive with the type it's like so that it works with the ArrayList.
During the creation of an Array, the .length
value is assigned, so whenever you append .length
to the end of an array, you get the length (which will never change for the given Array). For ArrayLists, you use the .size()
function, which returns the length of the ArrayList. Because the ArrayList size is variable, it is a function (which is why the parenthesis are there at the end).
Java provides the add() function for ArrayLists, which, as the name implies, adds the argument to the ArrayList. Arrays, on the other hand, do not have functions to add elements. To add something to an Array, you'd call something similar to this:
int[] my_array = new int[10];
my_array[0] = 5;
In Java, Array is a fixed length data structure, while ArrayList is a variable length Collection Class (other Collection class members include HashMap and HashSet). This means that an Array cannot change its size once it's made; a whole new Array must be made. ArrayLists can change size at will.
Arrays can reference both primitives (like int
) and types (like Integer
). ArrayLists can only reference types, not primitives. Through a method called "Autoboxing", it can appear that an ArrayList stores a primitive, but what it really is doing is automatically masking the primitive with the type it's like so that it works with the ArrayList.
During the creation of an Array, the .length
value is assigned, so whenever you append .length
to the end of an array, you get the length (which will never change for the given Array). For ArrayLists, you use the .size()
function, which returns the length of the ArrayList. Because the ArrayList size is variable, it is a function (which is why the parenthesis are there at the end).
Java provides the add() function for ArrayLists, which, as the name implies, adds the argument to the ArrayList. Arrays, on the other hand, do not have functions to add elements. To add something to an Array, you'd call something similar to this:
int[] my_array = new int[10];
my_array[0] = 5;
Compare your answer with the correct one above
On a standard binary tree, what would the data structure look like if we inserted the following names into the tree, supposing that names are compared in a standard lexicographic order:
Isaac, Henrietta, Nigel, Buford, Jethro, Cletus
On a standard binary tree, what would the data structure look like if we inserted the following names into the tree, supposing that names are compared in a standard lexicographic order:
Isaac, Henrietta, Nigel, Buford, Jethro, Cletus
A standard Binary Tree inserts into the root first. It then tries to insert to the "left" for values that are smaller and to the "right" for values that are larger. Therefore, for the data given, we have the first step:

Next, you will insert "Henrietta" to the left, for that is less than "Isaac":

Next, "Nigel" is greater than "Isaac":

Then, "Buford" is less than "Isaac" and then less than "Henrietta":

This continues through the following stages:


Thus, the last image is your final tree!
A standard Binary Tree inserts into the root first. It then tries to insert to the "left" for values that are smaller and to the "right" for values that are larger. Therefore, for the data given, we have the first step:
Next, you will insert "Henrietta" to the left, for that is less than "Isaac":
Next, "Nigel" is greater than "Isaac":
Then, "Buford" is less than "Isaac" and then less than "Henrietta":
This continues through the following stages:
Thus, the last image is your final tree!
Compare your answer with the correct one above
POST-ORDER TRAVERSAL
GIVEN THE FOLLOWING TREE:

WHAT IS THE RESULT OF A POST ORDER TRAVERSAL?
POST-ORDER TRAVERSAL
GIVEN THE FOLLOWING TREE:
WHAT IS THE RESULT OF A POST ORDER TRAVERSAL?
When doing a post-order traversal we go in the following order:
left, right, root.
This means that we are doing any left nodes first, then the right nodes, and LASTLY, the root nodes. If a node is a parent, then we must go throught the left and right children first. Since we're doing post-order traversal, the main root is going to be LAST.
In our example, 1 is a parent so we go to it's left child who is also a parent to node 4. This means that 4 is our first number in the traversal.
POST ORDER TRAVERSAL: 4
Since node 2 doesn't have a right child, we then make that node our next number in the traversal since node 2 it's the left child of node 1.
POST ORDER TRAVERSAL: 4, 2
By now, we have traversed the left nodes of the root. Now we move on to the right subtrees of node 1. Since node 3 is a parent node, we go to it's left child first (node 6). Since node 6 is also a parent, we move on to its children. Node 6 doesn't have a left child. Therefore our next number in the traversal is its right child (node 8) and then the subtree's root (node 6).
POST ORDER TRAVERSAL: 4, 2, 8, 6
Now, we've traversed the left children of node 3 we need to traverse the right child (node 7) who doesn't have any children of its own.
POST ORDER TRAVERSAL: 4, 2, 8, 6, 7
Lastly since we traversed it's right child, we move to the parent and traverse node 3 and our main root (node 1).
POST ORDER TRAVERSAL: 4, 2, 8, 6, 7, 3, 1
When doing a post-order traversal we go in the following order:
left, right, root.
This means that we are doing any left nodes first, then the right nodes, and LASTLY, the root nodes. If a node is a parent, then we must go throught the left and right children first. Since we're doing post-order traversal, the main root is going to be LAST.
In our example, 1 is a parent so we go to it's left child who is also a parent to node 4. This means that 4 is our first number in the traversal.
POST ORDER TRAVERSAL: 4
Since node 2 doesn't have a right child, we then make that node our next number in the traversal since node 2 it's the left child of node 1.
POST ORDER TRAVERSAL: 4, 2
By now, we have traversed the left nodes of the root. Now we move on to the right subtrees of node 1. Since node 3 is a parent node, we go to it's left child first (node 6). Since node 6 is also a parent, we move on to its children. Node 6 doesn't have a left child. Therefore our next number in the traversal is its right child (node 8) and then the subtree's root (node 6).
POST ORDER TRAVERSAL: 4, 2, 8, 6
Now, we've traversed the left children of node 3 we need to traverse the right child (node 7) who doesn't have any children of its own.
POST ORDER TRAVERSAL: 4, 2, 8, 6, 7
Lastly since we traversed it's right child, we move to the parent and traverse node 3 and our main root (node 1).
POST ORDER TRAVERSAL: 4, 2, 8, 6, 7, 3, 1
Compare your answer with the correct one above
On a standard binary tree, what would the data structure look like if we inserted the following names into the tree, supposing that names are compared in a standard lexicographic order:
Isaac, Henrietta, Nigel, Buford, Jethro, Cletus
On a standard binary tree, what would the data structure look like if we inserted the following names into the tree, supposing that names are compared in a standard lexicographic order:
Isaac, Henrietta, Nigel, Buford, Jethro, Cletus
A standard Binary Tree inserts into the root first. It then tries to insert to the "left" for values that are smaller and to the "right" for values that are larger. Therefore, for the data given, we have the first step:

Next, you will insert "Henrietta" to the left, for that is less than "Isaac":

Next, "Nigel" is greater than "Isaac":

Then, "Buford" is less than "Isaac" and then less than "Henrietta":

This continues through the following stages:


Thus, the last image is your final tree!
A standard Binary Tree inserts into the root first. It then tries to insert to the "left" for values that are smaller and to the "right" for values that are larger. Therefore, for the data given, we have the first step:
Next, you will insert "Henrietta" to the left, for that is less than "Isaac":
Next, "Nigel" is greater than "Isaac":
Then, "Buford" is less than "Isaac" and then less than "Henrietta":
This continues through the following stages:
Thus, the last image is your final tree!
Compare your answer with the correct one above
POST-ORDER TRAVERSAL
GIVEN THE FOLLOWING TREE:

WHAT IS THE RESULT OF A POST ORDER TRAVERSAL?
POST-ORDER TRAVERSAL
GIVEN THE FOLLOWING TREE:
WHAT IS THE RESULT OF A POST ORDER TRAVERSAL?
When doing a post-order traversal we go in the following order:
left, right, root.
This means that we are doing any left nodes first, then the right nodes, and LASTLY, the root nodes. If a node is a parent, then we must go throught the left and right children first. Since we're doing post-order traversal, the main root is going to be LAST.
In our example, 1 is a parent so we go to it's left child who is also a parent to node 4. This means that 4 is our first number in the traversal.
POST ORDER TRAVERSAL: 4
Since node 2 doesn't have a right child, we then make that node our next number in the traversal since node 2 it's the left child of node 1.
POST ORDER TRAVERSAL: 4, 2
By now, we have traversed the left nodes of the root. Now we move on to the right subtrees of node 1. Since node 3 is a parent node, we go to it's left child first (node 6). Since node 6 is also a parent, we move on to its children. Node 6 doesn't have a left child. Therefore our next number in the traversal is its right child (node 8) and then the subtree's root (node 6).
POST ORDER TRAVERSAL: 4, 2, 8, 6
Now, we've traversed the left children of node 3 we need to traverse the right child (node 7) who doesn't have any children of its own.
POST ORDER TRAVERSAL: 4, 2, 8, 6, 7
Lastly since we traversed it's right child, we move to the parent and traverse node 3 and our main root (node 1).
POST ORDER TRAVERSAL: 4, 2, 8, 6, 7, 3, 1
When doing a post-order traversal we go in the following order:
left, right, root.
This means that we are doing any left nodes first, then the right nodes, and LASTLY, the root nodes. If a node is a parent, then we must go throught the left and right children first. Since we're doing post-order traversal, the main root is going to be LAST.
In our example, 1 is a parent so we go to it's left child who is also a parent to node 4. This means that 4 is our first number in the traversal.
POST ORDER TRAVERSAL: 4
Since node 2 doesn't have a right child, we then make that node our next number in the traversal since node 2 it's the left child of node 1.
POST ORDER TRAVERSAL: 4, 2
By now, we have traversed the left nodes of the root. Now we move on to the right subtrees of node 1. Since node 3 is a parent node, we go to it's left child first (node 6). Since node 6 is also a parent, we move on to its children. Node 6 doesn't have a left child. Therefore our next number in the traversal is its right child (node 8) and then the subtree's root (node 6).
POST ORDER TRAVERSAL: 4, 2, 8, 6
Now, we've traversed the left children of node 3 we need to traverse the right child (node 7) who doesn't have any children of its own.
POST ORDER TRAVERSAL: 4, 2, 8, 6, 7
Lastly since we traversed it's right child, we move to the parent and traverse node 3 and our main root (node 1).
POST ORDER TRAVERSAL: 4, 2, 8, 6, 7, 3, 1
Compare your answer with the correct one above
On a standard binary tree, what would the data structure look like if we inserted the following names into the tree, supposing that names are compared in a standard lexicographic order:
Isaac, Henrietta, Nigel, Buford, Jethro, Cletus
On a standard binary tree, what would the data structure look like if we inserted the following names into the tree, supposing that names are compared in a standard lexicographic order:
Isaac, Henrietta, Nigel, Buford, Jethro, Cletus
A standard Binary Tree inserts into the root first. It then tries to insert to the "left" for values that are smaller and to the "right" for values that are larger. Therefore, for the data given, we have the first step:

Next, you will insert "Henrietta" to the left, for that is less than "Isaac":

Next, "Nigel" is greater than "Isaac":

Then, "Buford" is less than "Isaac" and then less than "Henrietta":

This continues through the following stages:


Thus, the last image is your final tree!
A standard Binary Tree inserts into the root first. It then tries to insert to the "left" for values that are smaller and to the "right" for values that are larger. Therefore, for the data given, we have the first step:
Next, you will insert "Henrietta" to the left, for that is less than "Isaac":
Next, "Nigel" is greater than "Isaac":
Then, "Buford" is less than "Isaac" and then less than "Henrietta":
This continues through the following stages:
Thus, the last image is your final tree!
Compare your answer with the correct one above
POST-ORDER TRAVERSAL
GIVEN THE FOLLOWING TREE:

WHAT IS THE RESULT OF A POST ORDER TRAVERSAL?
POST-ORDER TRAVERSAL
GIVEN THE FOLLOWING TREE:
WHAT IS THE RESULT OF A POST ORDER TRAVERSAL?
When doing a post-order traversal we go in the following order:
left, right, root.
This means that we are doing any left nodes first, then the right nodes, and LASTLY, the root nodes. If a node is a parent, then we must go throught the left and right children first. Since we're doing post-order traversal, the main root is going to be LAST.
In our example, 1 is a parent so we go to it's left child who is also a parent to node 4. This means that 4 is our first number in the traversal.
POST ORDER TRAVERSAL: 4
Since node 2 doesn't have a right child, we then make that node our next number in the traversal since node 2 it's the left child of node 1.
POST ORDER TRAVERSAL: 4, 2
By now, we have traversed the left nodes of the root. Now we move on to the right subtrees of node 1. Since node 3 is a parent node, we go to it's left child first (node 6). Since node 6 is also a parent, we move on to its children. Node 6 doesn't have a left child. Therefore our next number in the traversal is its right child (node 8) and then the subtree's root (node 6).
POST ORDER TRAVERSAL: 4, 2, 8, 6
Now, we've traversed the left children of node 3 we need to traverse the right child (node 7) who doesn't have any children of its own.
POST ORDER TRAVERSAL: 4, 2, 8, 6, 7
Lastly since we traversed it's right child, we move to the parent and traverse node 3 and our main root (node 1).
POST ORDER TRAVERSAL: 4, 2, 8, 6, 7, 3, 1
When doing a post-order traversal we go in the following order:
left, right, root.
This means that we are doing any left nodes first, then the right nodes, and LASTLY, the root nodes. If a node is a parent, then we must go throught the left and right children first. Since we're doing post-order traversal, the main root is going to be LAST.
In our example, 1 is a parent so we go to it's left child who is also a parent to node 4. This means that 4 is our first number in the traversal.
POST ORDER TRAVERSAL: 4
Since node 2 doesn't have a right child, we then make that node our next number in the traversal since node 2 it's the left child of node 1.
POST ORDER TRAVERSAL: 4, 2
By now, we have traversed the left nodes of the root. Now we move on to the right subtrees of node 1. Since node 3 is a parent node, we go to it's left child first (node 6). Since node 6 is also a parent, we move on to its children. Node 6 doesn't have a left child. Therefore our next number in the traversal is its right child (node 8) and then the subtree's root (node 6).
POST ORDER TRAVERSAL: 4, 2, 8, 6
Now, we've traversed the left children of node 3 we need to traverse the right child (node 7) who doesn't have any children of its own.
POST ORDER TRAVERSAL: 4, 2, 8, 6, 7
Lastly since we traversed it's right child, we move to the parent and traverse node 3 and our main root (node 1).
POST ORDER TRAVERSAL: 4, 2, 8, 6, 7, 3, 1
Compare your answer with the correct one above
Which of the following blocks of code converts an array of characters into a string?
Which of the following blocks of code converts an array of characters into a string?
The easiest way to consider this is by commenting on the correct answer. You must begin by defining the character array:
char\[\] vals = {'A','t', ' ', '6',' ','a','m','!'};
Next, you must initialize the string value s to be an empty string. This is critical. Otherwise, you can't build your string!
String s = "";
Next, you have the loop. This goes through the characters and concatenates the values to the variable s. The operation to concatenate the characters is the "+=". This will give you the string value of the array of characters.
The easiest way to consider this is by commenting on the correct answer. You must begin by defining the character array:
char\[\] vals = {'A','t', ' ', '6',' ','a','m','!'};
Next, you must initialize the string value s to be an empty string. This is critical. Otherwise, you can't build your string!
String s = "";
Next, you have the loop. This goes through the characters and concatenates the values to the variable s. The operation to concatenate the characters is the "+=". This will give you the string value of the array of characters.
Compare your answer with the correct one above
String greet = "Hello ";
String sub;
int len = greet.length();
sub = greet.substring(0, (len/2));
System.out.println (sub);
What is printed?
String greet = "Hello ";
String sub;
int len = greet.length();
sub = greet.substring(0, (len/2));
System.out.println (sub);
What is printed?
The length of greet is 6 characters including the space at the end.
greet.substring(0, (len/2)) is equal to greet.substring(0, 3)
The substring of greet from the zeroth position to second position, not to the third position.
The length of greet is 6 characters including the space at the end.
greet.substring(0, (len/2)) is equal to greet.substring(0, 3)
The substring of greet from the zeroth position to second position, not to the third position.
Compare your answer with the correct one above
Consider the following code:
int\[\] vals = {5,4,2};
String s = "Hervaeus";
String s2 = "";
for(int i = 0; i < s.length(); i++) {
for(int j = 0; j < vals\[i % vals.length\]; j++) {
s2 += s.charAt(i);
}
}
System.out.println(s2);
What is the output for the code above?
Consider the following code:
int\[\] vals = {5,4,2};
String s = "Hervaeus";
String s2 = "";
for(int i = 0; i < s.length(); i++) {
for(int j = 0; j < vals\[i % vals.length\]; j++) {
s2 += s.charAt(i);
}
}
System.out.println(s2);
What is the output for the code above?
The main thing to look at for this question is the main loop for the code. This loop first goes through each of the characters in the String s:
int i = 0; i < s.length(); i++
Next, notice the condition on the inner loop:
vals\[i % vals.length\]
The modulus on i will yield values that are between 0 and 2 (given the length of vals). This means that you will loop in the inner loop the following sequence of times:
5,4,2,5,4,2,5,4
This will replicate the given letter at the index (i) in the initial string, using 5,4,2,5, etc as the replication count. Thus, you will replicate "H" 5 times, "e" 4, etc. This gives you an output:
HHHHHeeeerrvvvvvaaaaeeuuuuussss
The main thing to look at for this question is the main loop for the code. This loop first goes through each of the characters in the String s:
int i = 0; i < s.length(); i++
Next, notice the condition on the inner loop:
vals\[i % vals.length\]
The modulus on i will yield values that are between 0 and 2 (given the length of vals). This means that you will loop in the inner loop the following sequence of times:
5,4,2,5,4,2,5,4
This will replicate the given letter at the index (i) in the initial string, using 5,4,2,5, etc as the replication count. Thus, you will replicate "H" 5 times, "e" 4, etc. This gives you an output:
HHHHHeeeerrvvvvvaaaaeeuuuuussss
Compare your answer with the correct one above
Consider the following code:
char\[\] values = {'I',' ','l','o','v','e',' ','y','o','u','!','!'};
String s = "";
for(int i = 0; i < values.length / 2; i++) {
char temp = values\[i\];
values\[i\] = values\[values.length - i-1\];
values\[values.length - i-1\] = temp;
}
for(int i = 0; i < values.length; i++) {
s += values\[i\];
}
System.out.println(s);
What is the output for the code above?
Consider the following code:
char\[\] values = {'I',' ','l','o','v','e',' ','y','o','u','!','!'};
String s = "";
for(int i = 0; i < values.length / 2; i++) {
char temp = values\[i\];
values\[i\] = values\[values.length - i-1\];
values\[values.length - i-1\] = temp;
}
for(int i = 0; i < values.length; i++) {
s += values\[i\];
}
System.out.println(s);
What is the output for the code above?
It is easiest to think of the values array as a String: "I love you!!".
Now, the loop is going to run for
or
times. Notice what it does on each iteration. It swaps the values at i and values.length - i -1. Thus, it will do the following swaps:
0 and 11
1 and 10
etc...
This sequence of swaps will eventually reverse the array. Thus, your output is:
!!uoy evol I
It is easiest to think of the values array as a String: "I love you!!".
Now, the loop is going to run for or
times. Notice what it does on each iteration. It swaps the values at i and values.length - i -1. Thus, it will do the following swaps:
0 and 11
1 and 10
etc...
This sequence of swaps will eventually reverse the array. Thus, your output is:
!!uoy evol I
Compare your answer with the correct one above
Which of the following blocks of code makes every other character in the string s to be upper case, starting with the second character?
Which of the following blocks of code makes every other character in the string s to be upper case, starting with the second character?
Given that strings cannot be internally modified, you will have to store your result in a new string, namely s2. Now, for each character in s, you will have to make that charater lower case to begin with:
char c = Character.toLowerCase(s.charAt(i));
Next, for the odd values of i, you will need to make your value to be upper case. The modulus operator is great for this! You can use % 2 to find the odd values. When the remainder of a division by 2 is equal to 1, you know you have an odd value. Hence, you have the condition:
if(i % 2 == 1) {...
Then, once you appropriately capitalize, you can place your character on s2.
Given that strings cannot be internally modified, you will have to store your result in a new string, namely s2. Now, for each character in s, you will have to make that charater lower case to begin with:
char c = Character.toLowerCase(s.charAt(i));
Next, for the odd values of i, you will need to make your value to be upper case. The modulus operator is great for this! You can use % 2 to find the odd values. When the remainder of a division by 2 is equal to 1, you know you have an odd value. Hence, you have the condition:
if(i % 2 == 1) {...
Then, once you appropriately capitalize, you can place your character on s2.
Compare your answer with the correct one above
See code below:
String\[\] books = {
"De Secundis Intentionibus",
"Leviathan",
"Averrois Commentaria Magna in Aristotelem De celo et mundo",
"Logica Docens for Idiots",
"Logica Utens for Tuba Players"
};
String userInput;
// In code excised from here, a person inputs the value "Logica Utens for Tuba Players" ...
for(int i = 0; i < books.length; i++) {
if(books\[i\] == userInput) {
System.out.println("This is a wonderful book!!");
}
}
What is the error in the code above?
See code below:
String\[\] books = {
"De Secundis Intentionibus",
"Leviathan",
"Averrois Commentaria Magna in Aristotelem De celo et mundo",
"Logica Docens for Idiots",
"Logica Utens for Tuba Players"
};
String userInput;
// In code excised from here, a person inputs the value "Logica Utens for Tuba Players" ...
for(int i = 0; i < books.length; i++) {
if(books\[i\] == userInput) {
System.out.println("This is a wonderful book!!");
}
}
What is the error in the code above?
The only major issue with this code is the use of the == operator to compare the two strings. Since the user has input this value, will not have an equality on this test. You must use the method .equals in order to check whether two strings are equal. The code should be:
if(books\[i\].equals(userInput)){
...
(There are some cases in which == will work for string comparison, namely when literals are involved. However, you should avoid relying on this and always use .equals().)
The only major issue with this code is the use of the == operator to compare the two strings. Since the user has input this value, will not have an equality on this test. You must use the method .equals in order to check whether two strings are equal. The code should be:
if(books\[i\].equals(userInput)){
...
(There are some cases in which == will work for string comparison, namely when literals are involved. However, you should avoid relying on this and always use .equals().)
Compare your answer with the correct one above
String\[\] books = {
"Logica sive Ars Rationalis",
"Kritik der reinen Vernunft",
"Cursus Philosophicus Thomisticus",
"Happy words for happy people",
"Insane words for an insane world"
};
String str = "Kittens in a cart";
ArrayList vals = new ArrayList();
for(int i = 0; i < books.length; i++) {
if(books\[i\].compareTo(str) > 0) {
vals.add(books\[i\]);
}
}
System.out.println(vals);
What is the output for this method?
String\[\] books = {
"Logica sive Ars Rationalis",
"Kritik der reinen Vernunft",
"Cursus Philosophicus Thomisticus",
"Happy words for happy people",
"Insane words for an insane world"
};
String str = "Kittens in a cart";
ArrayList
for(int i = 0; i < books.length; i++) {
if(books\[i\].compareTo(str) > 0) {
vals.add(books\[i\]);
}
}
System.out.println(vals);
What is the output for this method?
The compareTo method for strings compares to string objects and returns:
- 0 when they are equal
- Something positive when the given string is alphabetically (really, lexicographically) later than the argument to the method.
- Something negative when the given string is alphabetically (really, lexicographically) before the argument to the method.
Our strings could be put in this order:
"Cursus Philosophicus Thomisticus"
"Happy words for happy people"
"Insane words for an insane world"
"Kritik der reinen Vernunft"
"Logica sive Ars Rationalis"
For each of these, we are asking, "Is it later in order than 'Kittens in a cart'?" This is true for "Kritik der reinen Vernunft" and "Logica sive Ars Rationalis". Thus, our output is:
\[Logica sive Ars Rationalis, Kritik der reinen Vernunft\]
Notice the order—this is due to the order in the original array.
The compareTo method for strings compares to string objects and returns:
- 0 when they are equal
- Something positive when the given string is alphabetically (really, lexicographically) later than the argument to the method.
- Something negative when the given string is alphabetically (really, lexicographically) before the argument to the method.
Our strings could be put in this order:
"Cursus Philosophicus Thomisticus"
"Happy words for happy people"
"Insane words for an insane world"
"Kritik der reinen Vernunft"
"Logica sive Ars Rationalis"
For each of these, we are asking, "Is it later in order than 'Kittens in a cart'?" This is true for "Kritik der reinen Vernunft" and "Logica sive Ars Rationalis". Thus, our output is:
\[Logica sive Ars Rationalis, Kritik der reinen Vernunft\]
Notice the order—this is due to the order in the original array.
Compare your answer with the correct one above
Which of the following blocks of code converts an array of characters into a string?
Which of the following blocks of code converts an array of characters into a string?
The easiest way to consider this is by commenting on the correct answer. You must begin by defining the character array:
char\[\] vals = {'A','t', ' ', '6',' ','a','m','!'};
Next, you must initialize the string value s to be an empty string. This is critical. Otherwise, you can't build your string!
String s = "";
Next, you have the loop. This goes through the characters and concatenates the values to the variable s. The operation to concatenate the characters is the "+=". This will give you the string value of the array of characters.
The easiest way to consider this is by commenting on the correct answer. You must begin by defining the character array:
char\[\] vals = {'A','t', ' ', '6',' ','a','m','!'};
Next, you must initialize the string value s to be an empty string. This is critical. Otherwise, you can't build your string!
String s = "";
Next, you have the loop. This goes through the characters and concatenates the values to the variable s. The operation to concatenate the characters is the "+=". This will give you the string value of the array of characters.
Compare your answer with the correct one above