← Back to course

Method Calls

You’ll be able to

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.

substring(from, to)
s.substring(a, b) → characters at indices a through b − 1
The start index is included, the end index is excluded, so the result has length b − a. `s.substring(a)` alone returns from index a to the end.
Worked example

Trace this code: String s = " Java "; then System.out.println(s.trim().length());

  1. 1.Evaluate the left call first: s.trim() removes the leading and trailing spaces from " Java ", producing the string "Java".
  2. 2.Now call .length() on that result: "Java" has four characters — J, a, v, a.
  3. 3.length() returns 4, which is printed.
Answer: It prints 4. The spaces are trimmed away first, leaving "Java", whose length is 4.
Checkpoint

What does this print? `String s = "Hello";` then `String t = s.substring(1, 3);` then `System.out.println(t);`

Watch out

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.

Checkpoint

What does this print? `String s = " Java ";` then `System.out.println(s.trim().length());`

On the exam

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