Answers 100% Pass
Consider the following code segment:
```java
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
```
What does the code segment do?
✔✔ The code segment calculates the sum of all the elements in the `numbers` array and stores
the result in the `sum` variable. The final value of `sum` will be 15.
Consider the following code segment:
```java
String str = "hello";
1
,str = str.toUpperCase();
```
What will be the value of `str` after this code executes?
✔✔ The value of `str` will be `"HELLO"` after the code executes because the `toUpperCase()`
method converts all characters in the string to uppercase.
Consider the following code segment:
```java
int x = 5;
while (x > 0) {
System.out.println(x);
x--;
}
```
What does this loop print?
✔✔ This loop prints the numbers 5, 4, 3, 2, and 1, each on a new line. The loop continues to
decrement `x` until `x` becomes 0, at which point the loop stops.
2
,Consider the following code segment:
```java
int[] arr = {1, 2, 3, 4, 5};
System.out.println(arr[5]);
```
What happens when this code is executed?
✔✔ The code throws an `ArrayIndexOutOfBoundsException` because the valid indices for the
array `arr` are 0 to 4, but the code is attempting to access index 5, which is out of bounds.
Consider the following code segment:
```java
String s1 = "abc";
String s2 = "abc";
System.out.println(s1 == s2);
```
What does this code print, and why?
3
, ✔✔ This code prints `true` because string literals in Java that have the same value are interned,
meaning that `s1` and `s2` refer to the same memory location.
Consider the following code segment:
```java
public class Animal {
public void sound() {
System.out.println("Animal sound");
}
}
public class Dog extends Animal {
public void sound() {
System.out.println("Bark");
}
}
4