Method Calls
- Differentiate methods that return a value from `void` methods that do not
- Pass arguments to a method and predict the returned result
- Chain method calls, evaluating them left to right
Return values vs. void
A method either returns a value or is declared void and returns nothing. "cat".length() returns the int 3, so you can store or print it. System.out.println(...) is void: it performs an action (printing) but hands back no usable value. Whether a method returns something tells you whether its call can appear inside a larger expression.
Arguments flow into parameters
The values you place in the parentheses of a call are arguments; inside the method they fill the parameters. In s.substring(1, 3), the arguments 1 and 3 become the start and end positions the method works with. The method computes a result from those arguments and returns it, without changing the original object — String methods always produce a new result rather than editing the string in place.
Chaining calls left to right
Because a method call can return an object, you can immediately call another method on that result — this is chaining. In s.trim().length(), Java first evaluates s.trim() to get a trimmed String, then calls .length() on that string. Always read a chain from left to right, resolving one call before the next.
Trace this code: String s = " Java "; then System.out.println(s.trim().length());
- 1.Evaluate the left call first:
s.trim()removes the leading and trailing spaces from" Java ", producing the string"Java". - 2.Now call
.length()on that result:"Java"has four characters — J, a, v, a. - 3.
length()returns4, which is printed.
4. The spaces are trimmed away first, leaving "Java", whose length is 4.What does this print? `String s = "Hello";` then `String t = s.substring(1, 3);` then `System.out.println(t);`
A void method’s call cannot be used as a value. Writing int n = System.out.println("hi"); does not compile because println returns nothing to assign.
What does this print? `String s = " Java ";` then `System.out.println(s.trim().length());`
When you see chained calls, rewrite them as separate steps on scratch paper: compute the leftmost call, replace it with its result, and repeat. This prevents mis-reading s.trim().length() as calling length() on the original spaced string.
Answer the 2 checkpoints as you read.
Sign in to save your progress