← all problems

String Objects, Concatenation, and Indexes 🌶️

A String in Java is not a primitive type like int or double, it is an object, an instance of the String class. Almost everything else about how Strings behave follows from that one fact, so it is worth getting solid before anything else.

Four ideas this worksheet checks:

1. In Java, what kind of type is String?

2. Which of these actually creates a String object?

3. What is the value of s after this code runs?

String s = "hello";s.substring(0, 2);

4. You want s to actually end up holding just the first two characters. Which line does that?

5. What does 1 + 2 + "3" evaluate to? Write just the resulting characters, with no quotation marks around them.

6. What does "1" + 2 + 3 evaluate to? Write just the resulting characters, with no quotation marks around them. (Compare your answer carefully with the previous question: the same three values, in the same order, with only the quotation marks moved.)

7. What does "Total: " + 5 + 10 evaluate to?



Concatenating an object: toString

So far the right-hand side of a + has been a number. But you can concatenate a String with any object, because every class is guaranteed to have a toString method — a method that returns a String representing that object. When you concatenate an object, Java implicitly calls its toString for you.

Most classes replace the default toString with one that actually describes the object usefully. Point2D — the reference class you have already used — does exactly that:

public String toString() {    return "(" + x + ", " + y + ")";}


Notice that toString itself is built with concatenation, using the same overloaded + from the questions above. The next two questions use this method.

8. The String "chocolate" has 9 characters. What are its valid indexes?

9. What happens when this line runs?

String s = "chocolate";String c = s.substring(9, 10);

10. Put these steps in the order needed to get the LAST character of a String s, as a one-character String. (Two items below do not belong at all.)

Click a placed item to send it back. With drag-and-drop enabled, you can also drag items to reorder them — indent arrows always stay click-only.

Click these, in order, if they belong in the answer
Your answer, in order

11. What does "banana".indexOf("na") return?

12. What does "banana".indexOf("z") return?

13. You have two String variables and want to know whether they hold the same sequence of characters. Which should you use?

Your score for your class is recorded when you click Submit all — checking individual questions doesn't save it. You can submit again to improve your score; your best one counts.