In: Computer Science
1)
What's the result of calling method blitz passing strings "Aquamarine" as the first argument and "Heliotrope" as the second argument?
static int blitz(String v, String w) { if (v.length() != w.length()) return 0; int c = 0; for (int i = 0; i < v.length(); i++) if (v.charAt(i) == w.charAt(i)) c++; return c; }
a)0
b)1
c)2
d) 3
2)What is NOT an advantage of dynamic arrays compared to static arrays?
a)new elements can be added
b)elements can be inserted
c)elements can be individually indexed
d)elements can be removed
3)
Consider the following code segment:
ArrayList<Integer> scores = new ArrayList<>();
scores.add(5);
scores.add(8);
scores.add(1);
scores.add(1, 9);
scores.remove(2);
scores.add(0, 2);
What's the content of array scores after the code is executed?
a)[2, 5, 8, 1]
b)[2, 5, 9, 1]
c)[5, 2, 9, 1]
d) something else
4)
Consider the following code segment:
int mat[][] = new int[4][3]; for (int i = 0; i < mat.length; i++) for (int j = 0; j < mat[0].length; j++) if (i % 2 == 0) mat[i][j] = 2; else if (i % 3 == 0) mat[i][j] = 3; else mat[i][j] = 0;
What is the content of mat's 3rd row after the code segment is executed?
a)[3, 3, 3, 3]
b)[3, 3, 3]
c)[2, 2, 2, 2]
d)[2, 2, 2]
check out the solution.
------------------------------------------------------
1)
Answer - c) 2
Explanation:
A q u a m a r i n e
H e l i o t r o p e
A == H - false - c=0
q == e - false - c=0
u == l - false - c=0
a == i - false - c=0
m == o - false - c=0
a == t - false - c=0
r == r - true - c=1
i == o - false - c=0
n == p - false - c=0
e == e - true - c=2
therefore : c = 2
-------------------------------------------
2)
Answer - b) elements can be inserted
Explanation : Memory leak issue, in a scenario where memory is full and dynamic arrays try to insert elements then an error is raised and cause exception.So inserting elements in dynamic arrays is a disadvantage over static arrays.
-----------------------------------------------
3)
Answer - b) [2, 5, 9, 1]
Explanation:
scores.add(5); // [5] - added
scores.add(8); // [5, 8] - added
scores.add(1); // [5, 8, 1] - added
scores.add(1, 9); // [5, 9, 8, 1] - added 9 at index 1
scores.remove(2); // [5, 9, 1] - removed element at index 2 so
element 8 is removed
scores.add(0, 2); // [2, 5, 9, 1] - add 2 at index 0
Therefore answer is [2, 5, 9, 1]
---------------------------------------
4)
Answer - d) [2 2 2]
Explanation:
1st row - for i=0 - 0%2 == 0 - true - entire row is 2 - [2 2
2]
2nd row - for i=1 - 1%2 == 0 - false
- 1%3 == 0 - false
- else - entire row is 0 - [0 0 0]
3rd row - for i=2 - 2%2 == 0 - true - entire row is 2 - [2 2
2]
4th row - for i=3 - 3%2 == 0 - false
- 3%3 == 0 - true - entire row is 3 - [3 3 3]
therefore mat's 3rd row is - [2 2 2]
------------------------------------------------------
Test Programs in Java along with the output.
1.
---------------------------------
2.
------------------------------------------
3.
===========================================