Calling Methods
Methods of an object are called to make it do something.
Calling a method in an object also makes use of dot notation. The object whose method is being called is on the left side of the dot, and the name of the method and its arguments are on the right side:
customer.addToCart(itemNumber, price, quantity);
All method calls must have parentheses after them, even when the method takes no arguments, as in this example:
customer.cancelOrder();
In Listing 3.3, the StringChecker application shows an example of calling some methods defined in the String class. Strings include methods for string tests and modification. Create this program in NetBeans as an empty Java file with the class name StringChecker and package name com.java21days.
LISTING 3.3 The Full Text of StringChecker.java
1: package com.java21days;
2:
3: class StringChecker {
4:
5: public static void main(String[] arguments) {
6: String str = "A Lannister always pays his debts";
7: System.out.println("The string is: " + str);
8: System.out.println("Length of this string: "
9: + str.length());
10: System.out.println("The character at position 6: "
11: + str.charAt(6));
12: System.out.println("The substring from 12 to 18: "
13: + str.substring(12, 18));
14: System.out.println("The index of the first 't': "
15: + str.indexOf('t'));
16: System.out.println("The index of the beginning of the "
17: + "substring \"debts\": " + str.indexOf("debts"));
18: System.out.println("The string in uppercase: "
19: + str.toUpperCase());
20: }
21: }
Running the program produces the output shown in Figure 3.3.
FIGURE 3.3 Calling String methods to learn more about that string.
In line 6, you create a new instance of String by using the string literal “A Lannister always pays his debts”. The remainder of the program simply calls different string methods to do different operations on that string:
- Line 7 prints the value of the string.
- Line 9 calls the length() method in the new String object to find out how many characters it contains.
- Line 11 calls the charAt() method, which returns the character at the given position in the string. Note that string positions start at position 0 rather than 1, so the character at position 6 is ‘i’.
- Line 13 calls the substring() method, which takes two integers indicating a range and returns the substring with those starting and ending points. The substring() method also can be called with only one argument, which returns the substring from that position to the end of the string.
- Line 15 calls the indexOf() method, which returns the position of the first instance of the given character. Character literals are surrounded by single quotation marks, so the argument is ‘t’ (not “t”).
- Line 17 shows a different use of the indexOf() method, which takes a string argument and returns the index of the beginning of that string. String literals always are surrounded by double quotation marks.
- Line 19 uses the toUpperCase() method to return a copy of the string in all uppercase.
Formatting Strings
Numbers such as money often need to be displayed in a precise manner. There are only two places after the decimal for the number of cents, a dollar sign ($) preceding the value, and commas separating groups of three numbers—as in $22,453.70 (the amount the U.S. National Debt goes up in one second).
This kind of formatting when displaying strings can be accomplished with the System.out.format() method.
The method takes two arguments: the output format template and the string to display. Here’s an example that adds a dollar sign and commas to the display of an integer:
int accountBalance = 5005;
System.out.format("Balance: $%,d%n", accountBalance);
This code produces the output Balance: $5,005.
The formatting string begins with a percent sign % followed by one or more flags. The %,d code displays a decimal with commas dividing each group of three digits. The %n code displays a newline character.
The next example displays the value of pi to 11 decimal places:
double pi = Math.PI;
System.out.format("%.11f%n", pi);
The output is 3.14159265359.
Nesting Method Calls
A method can return a reference to an object, a primitive data type, or no value at all. In the StringChecker application, all the methods called on the String object str returned values that are displayed. The charAt() method returned a character at a specified position in the string.
The value returned by a method also can be stored in a variable:
String label = "From";
String upper = label.toUpperCase();
In this example, the String object upper contains the value returned by calling label.toUpperCase(), which is the text “FROM”.
If the method returns an object, you can call the methods of that object in the same statement. This makes it possible for you to nest methods as you would variables.
Earlier today, you saw an example of a method called with no arguments:
customer.cancelOrder();
If the cancelOrder() method returns an object, you can call methods of that object in the same statement:
customer.cancelOrder().fileComplaint();
This statement calls the fileComplaint() method, which is defined in the object returned by the cancelOrder() method of the customer object.
You can combine nested method calls and instance variable references as well. In the next example, the putOnLayaway() method is defined in the object stored by the orderTotal instance variable, which itself is part of the customer object:
customer.orderTotal.putOnLayaway(itemNumber, price, quantity);
This manner of nesting variables and methods is demonstrated in a method you’ve used frequently in the first three days of this book: System.out.println().
That method displays strings and other data to the computer’s standard output device.
The System class, part of the java.lang package, describes behavior specific to the computer system on which Java is running. System.out is a class variable that contains an instance of the class PrintStream representing the system’s standard output, which normally is the monitor but can be a printer or file. PrintStream objects have a println() method that sends a string to that output stream. The PrintStream class is in the java.io package.
Class Methods
Class methods, also called static methods, apply to the class as a whole and not to its instances just like class variables. Class methods commonly are used for general utility methods that might not operate directly on an object of that class but do fit with that class conceptually.
For example, the String class contains a class method called valueOf(), which can take one of many types of arguments (integers, Booleans, objects, and so on). The valueOf() method then returns a new instance of String containing the argument’s string value. This method doesn’t operate directly on an existing instance of String, but getting a string from another object or data type is behavior that makes sense to define in the String class.
Class methods also can be useful for gathering general methods in one place. For example, the Math class, defined in the java.lang package, contains a large set of mathematical operations as class methods. No objects can be created from the Math class, but you still can use its methods with numeric or Boolean arguments.
For example, the class method Math.max() takes two arguments and returns the larger of the two. You don’t need to create a new instance of Math; it can be called anywhere you need it, as in the following:
int firstPrice = 225;
int secondPrice = 217;
int higherPrice = Math.max(firstPrice, secondPrice);
Dot notation is used to call a class method. As with class variables, you can use either an instance of the class or the class itself on the left side of the dot. For the same reasons noted earlier about class variables, using the name of the class makes your code easier to read.
The last two lines in this example both produce strings equal to “550”:
String s, s2;
s = "potrzebie";
s2 = s.valueOf(550);
s2 = String.valueOf(550);