Sub topic 16
Calls, Object Creation, and Expression Statements
An expression can do more than calculate a number. In Java, an expression can call a method or create an object. You can use the result in another expression, store it in a variable, or sometimes ignore it.
This chapter assumes you can write and run a simple Java program and know how variables and basic data types work.
Calling a Method
A method is a named set of instructions that can be run when needed. A method call tells Java to run those instructions.
For example, total(10, 2) calls a method named total. The values 10 and 2 are arguments: values supplied to a method when it is called. The method can use them to produce a result.
A parameter is a variable in the method definition that receives an argument. Here, price and fee are parameters:
public class MethodExample {
public static int total(int price, int fee) {
return price + fee;
}
public static void main(String[] args) {
int amount = total(10, 2);
System.out.println(amount);
}
}Save this code as MethodExample.java, then run it:
javac MethodExample.java
java MethodExampleThe program prints 12. The return statement sends the result back to the caller. The call total(10, 2) produces the value 12, which is then stored in amount.
The int before total is its return type: the type of value the method sends back. A call that returns a value can be used where a value of a suitable type is expected. For example, total(10, 2) + 3 produces 15.
The word static means this method belongs to the class rather than to a particular object. Code in the same class can call it as total(10, 2). Code in another class can use the class name, as in MethodExample.total(10, 2).
Methods That Return Nothing
Some methods do a task without returning a value. Their return type is void. For example, System.out.println(amount) prints the value of amount but returns no value.
Printing is a side effect: a change a method makes beyond returning a value. Other methods might change an object or save data.
A void call can be a complete statement, such as System.out.println(amount);. It cannot supply a value for an assignment. For example, int result = System.out.println(amount); will not compile because println does not return an int.
Creating an Object
An object is a value that can hold data and provide methods that work with that data. A class is a definition used to create objects. Java’s String class, for example, represents text.
The new keyword creates an object. A constructor is the part of a class that sets up a new object. The expression new Ticket("Garden") creates a Ticket object and passes "Garden" to its constructor.
The result is a reference, which is a value that lets the program access the object. You can store that reference in a variable:
Ticket ticket = new Ticket("Garden");
You can then use the variable to call a method on that object. In ticket.label(), the dot connects the object reference to the method call.
A Complete Example
Save the following program as ExpressionDemo.java. It combines a method call, object creation, and calls on an object.
public class ExpressionDemo {
public static int total(int price, int fee) {
return price + fee;
}
public static void showTotal(int amount) {
System.out.println("Total: " + amount);
}
public static void main(String[] args) {
int amount = total(10, 2);
showTotal(amount);
Ticket ticket = new Ticket("Garden");
String label = ticket.label();
System.out.println(label);
ticket.rename("Museum");
System.out.println(ticket.label());
System.out.println(new Ticket("Park").label());
total(4, 1);
}
}
class Ticket {
String place;
Ticket(String initialPlace) {
place = initialPlace;
}
String label() {
return "Ticket: " + place;
}
void rename(String newPlace) {
place = newPlace;
}
}Run it with:
javac ExpressionDemo.java
java ExpressionDemoThe output is:
Total: 12Ticket: GardenTicket: MuseumTicket: Park
Follow the expressions in main:
total(10, 2)returns12. The declaration stores that value inamount.showTotal(amount)prints the total. It returns nothing.new Ticket("Garden")creates a ticket. The constructor stores"Garden"inplace, a field. A field is a variable that holds data for an object.ticket.label()returns text based on that ticket’splace. The first call stores the returned text inlabel.ticket.rename("Museum")changes the ticket’s field. The next call tolabel()uses the new place.new Ticket("Park").label()creates a ticket and callslabel()on it immediately. The returned text is passed toprintln.total(4, 1)returns5, but the program does not use or print that value.
The Ticket constructor has the same name as the class and has no declared return type. The new Ticket(...) expression, not the constructor itself, produces the reference used by the program.
Using Results or Ignoring Them
Calls and object creation can be combined with other expressions. In System.out.println(ticket.label()), the inner call produces a string, which becomes the argument to println. In new Ticket("Park").label(), the result of object creation is used for a method call without first being stored in a variable.
When a method call has several arguments, Java evaluates those arguments from left to right before running the method. Each argument must have a suitable type for its parameter. For example, total("10", 2) will not compile: total expects an int for its first parameter, not text.
A method call that returns a value can also appear by itself, as total(4, 1); does in the example. Java runs the method, then discards its result. That is legal, but this particular call has no useful effect because total only calculates a value.
Expression Statements
A statement is an instruction in a program. An expression statement is an expression used as a statement, followed by a semicolon.
Java permits certain expressions as expression statements:
| Kind | Example | What it does |
|---|---|---|
| Assignment | `amount = 20;` | Stores a value. |
| Increment or decrement | `amount++;` | Changes a variable. |
| Method call | `showTotal(amount);` | Runs a method. |
| Object creation | `new Ticket("Garden");` | Creates an object. |
These examples assume the variables and methods from the complete example are in scope.
Not every expression can stand alone as a statement. For example, amount + 1; and 42; are not legal Java statements. To use the calculated value, you could write amount = amount + 1; or pass it to a method, as in showTotal(amount + 1);.
A declaration such as int amount = total(10, 2); is a variable declaration statement, not an expression statement. Its right side contains an expression whose result initializes the variable.
Common Errors
- Using a result of the wrong type:
ticket.label()returns aString, so it cannot be stored directly in anint. - Expecting a
voidmethod to return a value: call it for its task, not as the right side of an assignment. - Calling a method on
null:nullmeans a reference does not refer to an object. Calling an object method through it causes aNullPointerExceptionwhile the program runs. - Supplying the wrong constructor arguments: this
Ticketclass requires one string, sonew Ticket()does not compile. - Creating an object and losing its reference:
new Ticket("Garden");is legal, but the program cannot later use that ticket through a variable. Its constructor still runs.
Practice
Exercise
What value does total(3, 4) produce in the complete example? Does calling total(3, 4); print it?
Show answer
It produces 7. The standalone call does not print it; it discards the result.
Exercise
Why can ticket.rename("Lake"); be a statement, but int x = ticket.rename("Lake"); cannot compile?
Show answer
A method call can be an expression statement. The assignment fails because rename returns void, not a value.
Exercise
After Ticket t = new Ticket("Hill");, what does t.label() return? What must you do to show it on screen?
Show answer
It returns the string "Ticket: Hill". Pass it to System.out.println, as in System.out.println(t.label());.