JAVA / CHAPTER 02
Using objects
BeginnerCall object methods and reason about references and immutable strings.
By the end of this chapter
- Call methods on a String
- Interpret substring bounds
- Distinguish a returned value from mutation
The idea
An object supplies behavior through methods. A variable such as label can hold a reference to a String object, and label.length() asks that object for its length. Dot notation chooses a member; parentheses supply arguments. Read a method contract before calling it: substring uses a starting index that is included and an ending index that is excluded. String indices in this chapter use simple ASCII text.
String objects are immutable. Calling toUpperCase or substring produces a result without rewriting the original string. Assign that result when you need to retain it. Two variables can refer to the same object, but reassigning one variable does not reassign the other.
public class Main {
public static void main(String[] args) {
String label = "notebook";
String shortName = label.substring(0, 4);
System.out.println(shortName.toUpperCase());
System.out.println(label);
}
}NOTE notebook
The selected characters occupy indices zero through three. Uppercasing the selected value leaves label unchanged.
Try it yourself
Given an ASCII filename ending in .txt, return its name without the extension while preserving the original variable.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING