209k views
1 vote
*please help*

AP Computer Science A

Consider the following code segment:

String str = "hello";
System.out.println(str.charAt(4));

1. What will be printed as a result of this program? Why?
2. What will be printed if we add the command System.out.println(str.length()); Why?
3. What will be printed if we add the command System.out.println(str.substring(0,2);? Why?

1 Answer

6 votes
Answer:
1. Prints “o”
This is because charAt returns with the character(a,b,c,etc) at the index. In this case it’s 4. It’s important to remember that the charAt searches for the character at the index and not literal place. The string starts at 0 instead of 1. So h = 0, e = 1, l = 2, l = 3, o = 4.
2. Prints “5”
The str.length() method prints out the literal count of characters in a string. Starting from 1 instead of 0. “hello” has 5 characters(the word letters can’t be used as the method also counts spaces and other symbols).
3. Prints “he”
The substring method prints out the characters from the first index parameter, in this case “h” since it’s in the 0 index, to the last character before the last index parameter. This would be “e”. If it were a longer length then those letters in between would be printed as well.
User Tamil
by
5.5k points