5. Methods
5.1. Learning Objectives
- Define the components of a method header
- Define and produce a method body
- Understand parameter passing and use. This will include both pass by value and pass by reference variables.
- Understand and use class methods.
- Understand and properly call methods, void and value returning
- Understand and use instance methods
- Understand and use the proper return syntax
- Understand how to use returned values in your calling code
5.2. Resources
5.2.1. Text
- Think Java, Chapters 4 and 6, 6.1 - 6.6: How to Think Like a Computer Scientist, Void Methods and How to Think Like a Computer Scientist, Value Methods by Allen Downey and Chris Mayfield. === Video
- Safari, Deitel Method Video
- Lynda.com: Java Essential Training: Syntax and Structure - Chapter 5. Manage Program Flow, Create reusable code with methods
- Lynda.com: Java Essential Training: Syntax and Structure - Chapter 5. Manage Program Flow, Create overloaded methods
- Lynda.com: Java Essential Training: Syntax and Structure - Chapter 5. Manage Program Flow, Pass arguments by reference vs. value
- Codecademy: Learn Java, Object-Oriented Java - Learn Java: Methods
- YouTube Java Programming 4 - Methods
- YouTube 8.1 Java Tutorial for Beginners: Methods and Functions Part 1
- YouTube 8.2 Java Tutorial for Beginners: Methods and Functions Part 2
5.3. Key Terms
5.3.1.Think Java Vocabulary Chapter 4
- argument: A value that you provide when you invoke a method. This value must have the same type as the corresponding parameter.
- invoke: To cause a method to execute. Also known as “calling” a method.
- parameter: A piece of information that a method requires before it can run. Parameters are variables: they contain values and have types.
- flow of execution: The order in which Java executes methods and statements. It may not necessarily be from top to bottom, left to right.
- parameter passing: The process of assigning an argument value to a parameter variable.
- local variable: A variable declared inside a method. Local variables cannot be accessed from outside their method.
- stack diagram: A graphical representation of the variables belonging to each method. The method calls are “stacked” from top to bottom, in the flow of execution.
- frame: In a stack diagram, a representation of the variables and parameters for a method, along with their current values.
- signature: The first line of a method that defines its name, return type, and parameters.
- Javadoc: A tool that reads Java source code and generates documentation in HTML format.
- documentation: Comments that describe the technical operation of a class or method.
5.3.2. Think Java Vocabulary Chapter 6
- void method: A method that does not return a value.
- value method: A method that returns a value.
- return type: The type of value a method returns.
- return value: The value provided as the result of a method invocation.
- temporary variable: A short-lived variable, often used for debugging.
- dead code: Part of a program that can never be executed, often because it appears after a return statement.
- incremental development: A process for creating programs by writing a few lines at a time, compiling, and testing.
- stub: A placeholder for an incomplete method so that the class will compile.
- scaffolding: Code that is used during program development but is not part of the final version.
- functional decomposition: A process for breaking down a complex computation into simple methods, then composing the methods to perform the computation.
- overload: To define more than one method with the same name but different parameters.
5.4. Overview
Methods are used for several key purposes in programming. First, they allow us to decompose our problems into smaller parts. When we solve complex problems, trying to grasp the entire problem at one time can easily overwhelm our ability to see the solution.
Second, by moving code into methods, we can use this same code in multiple places without having to re-write this code. This allows us to make changes in the way this code executes as requirements change or to correct defects in a single location.
Third, methods allow us to use member variables. A member variable is a variable that is declared in the class and not in a method. This variable will exist throughout the class and can be accessed by all of the methods in the class.
5.5. Method Basics
Methods can either return a value or not return anything. Think Java Chapter 4 discusses void methods, those that don’t return a value. Think Java Chapter 6 discusses value returning methods. A method that returns a value can only return a single item, this item can be an object of a class or some type of data structure that contains multiple values.
5.6. Example Method
Here is an example method in Java.
public void printString(String content) { System.out.println(content); }
The following is an example of a value returning method.
public String getString(String content) { Scanner input = new Scanner(System.in); System.out.println("Please enter your name"); String name = input.nextLine(); input.close(); return name; }
5.7. Java Provided Methods
Java provides many methods through the Java API. For example, the Math class, Java API, provides many useful methods including those to provide the absolute value of a number, the maximum of two numbers, the square root of a number, a number raised to the power of another number and so on. Other classes provide methods to read input from the user, Scanner, display output to an output device, PrintStream which we have seen in the System class. The String class provides many built-in methods for processing String data.
5.8. Create Your Own Methods
We can create our own methods to allow us to separate our code into manageable units. Keep in mind that your methods can either be value returning or return nothing. You cannot return more than one item from a method.
5.8.1. Parts of a Method
5.8.2. Method Header
public void printString(String content)
The method header is made up of several key components. First, is the access modifiers. These can be public, private, protected or default. These keywords control what parts of the program have visibility for the method.
- public - the entire program can use this method
- private - only this class can use this method
- protected - only classes in the same package and children of this class can use this method
- default - this is specified by not having a modifier as shown below. This allows items in the same package to use this method.
Note: a package is a container that holds multiple classes, a folder on your disk.
void printString(String content)
The other modifier determines the ownership of the method, either static or not. If we use the keyword static, this method belongs to the class. If we leave this blank, it belongs to an object of the class.
public static void printString(String content)
If we do not use the keyword static, the method belongs to an instance of the class.
public void printString(String content)
Please see Types of Methods below.
The next part of the method header is the return type. Methods must have an explicit return type even if they don’t return anything. A non-returning method is declared using the keyword void.
public void printString(String content)
In this example, the method printString does not return anything, notice the keyword void.
public String returnString(String content)
In this example, the method returnString, must return a String.
Next is the method name followed by parenthesis. In the parenthesis are the parameters, either none or as many as you would like to pass to the method. These are declared using the type name convention used by Java. For example, in our example method, we used String content. This tells the method that the first item being passed is of type String and throughout the entire method, its name is content.
public void printString(String content)
In this example, the method name is printString and the parameter passed is content which is of type String.
5.8.3. Parameter Types
5.8.4. Primitive Parameters
A primitive parameter is one of the 8 Java primitive types, byte, short, int, long, float, double, char, boolean. When passing a primitive type parameter, the parameter is passed by copy. This means changes made to it in the method are not reflected in the calling code unless this variable is returned.
5.8.5. Reference Parameters
A reference parameter is any object that we pass to a method. This includes any class type variable, an array or any other type of variable that is initialized using the new keyword. If the object type is mutable, can be changed, changes in the method are reflected in the calling code. String is immutable meaning that changes to a String object delete the original object and instantiate a new String with the changes. For an immutable type, no changes are made in the calling code.
Note: if you have a return type other than void declared in your method, it must return this type or your code will not compile.
5.8.6. Method Signature
The method signature is defined as the name and the types of parameters being passed to it. A method’s signature must be unique in a class. Below is the method signature for our example method.
printString(String content)
Note: You cannot use the return type or the modifiers to generate a different method signature.
5.8.7. Parameters
Parameters are the variables that are passed to the method.
public void printString(String content)
In this example, content is the parameter and must be of type String.
Variables declared in the method header are called formal parameters. These exist throughout the method and are used to pass information to the method. A common mistake made by beginning programmers is to reassign these variables in the method rather than use the information passed in. You can pass multiple parameters to a method by separating them with a comma. Remember, order does matter.
Variables in a method are passed in two different ways. First, if the variable is a primitive variable, a copy of the variable is passed to the method. Any changes made to this variable are kept in the method and the variable in the calling code is not changed. If the variable is a reference variable, an object of a class, the address is passed. Since the method has been passed the address of an object, changes made to the object in the method are made to the object in the calling code. Some reference variables are immutable, cannot be changed. These objects, like a String object, are destroyed and re-created when re-assigned. Therefore, it is working on a different object and changes are not reflected in the calling code.
5.8.8. Method Body
The method body contains the code that does the work in the method. Typically, we try to limit this to no more than 30 lines of code. More lines may be an indication that your method should be broken into multiple methods. The Method Body is surrounded by opening and closing curly braces. For example, the method body in our example method is:
{ System.out.println(content); }
5.9. Types of Methods
Methods belong to either the class or an object of the class.
5.9.1. Class methods
A class method belongs to the class and is called using the class name. For example, when we print a line to the screen, we use System.out.println. Since System is a class, the out variab le is static in hte System class. We use the System class name to call the println method in the PrintStream class. This variable belongs to the class and is called using the class name.
When a method is declared using the keyword static in its header. We do not have to instantiate an object of the class to use this method. The line System.out.println tells the JVM to use the System class. In this class is a PrintStream object, this object is declared as static in the System class. The PrintStream object named out contains a method println which writes a line to the standard output stream, in this case, the screen.
5.9.2. JavaTutor Example
To call a class method from within the same class, simply use the method name and associated parameters.
5.9.3. Instance methods
An instance method belongs to an object of the class. It is declared without using the static keyword in the method header. For example, when we use a Scanner to read user input, we must create an object of this class to allow us to use its methods. With the Scanner class, we must instantiate an object to allow us to use this object since a Scanner can be attached to many different objects. When we construct the Scanner using Scanner input = new Scanner(System.in); we are creating a Scanner and attaching it to the default input device, the keyboard. We will learn later that a Scanner can be attached to a file, a String, a socket and other input devices.
5.9.4. JavaTutor Example
To call an instance method from a class method, main is a class method due to the static modifier, we must create an object of this class and call the method through that object.
5.10. Overloaded Methods
You can have two methods that have the same name as long as they have different numbers or types of parameters. The method name and parameters, the signature, cannot be ambiguous, a method the compiler can confuse with another method. Keep in mind, the signature is the name and the type and number of the variables not the names of the variables. The following two methods are examples of overloaded methods.
5.10.1. JavaTutor Example
5.11. Calling Methods
When you call a method, you use the method name and the correct number and type of parameters to call the method. For example, the following code will call our example method.
printString("Hello World!!!");
If you are calling an instance method from a static context, the main method for example, you must call this method through an object of the class containing the method. For example, the following code will not compile if the printString method is an instance method.
public static void main(String[] args) { String content = "Hello World"; printString(content); }
To use this method from the static context, you need to create an object of the class to use to call the method.
public class Example { public static void main(String[] args) { String content = "Hello World"; Example exp = new Example(); exp.printString(content); } public void printString(String content) { System.out.println(content); } }
5.12. Member variables
5.12.1. Declaring member variables
Member variables are declared in the class but outside any method. By convention, these are declared at the top of the class to make it easy for programmers to know what they are. A member variable can take one of two forms. First, they can be class variables which means they are declared using the keyword static. This means they are created before your program begins execution in the Java Virtual Machine and that there is only one copy of this variable no matter how many instances of this class are created. The following code creates a class variable of type String named myString. This variable will exist throughout the class and can be accessed by any method in the class. By declaring it private, only the class that contains it can access this variable. Other alternatives include public, every class in your program has access to it; no access modifier which gives it default visibility, every class in the same package (a folder on your computer) can access it; or protected, similar to the default visibility but also allows classes that inherit from this class to access it. Inheritance will be discussed in future classes. The recommend visibility for variables is private. This allows us to encapsulate this information and prevents unwanted modifications.
public class Example { private static String myString; public static void main(String[] args) { myString = "Hello"; printString(); } private static void printString() { System.out.println(myString); } }
The second type of member variable is an instance variable. This is one that is declared without using the static keyword. Instance variables exist throughout the class but are only created when an object of the class is instantiated. The following code modifies the previous example to be an instance variable.
public class Example { private String myString; public static void main(String[] args) { Example examp = new Example(); examp.myString = "Hello"; examp.printString(); } private void printString() { System.out.println(myString); } }
Notice in the above code, we had to create an instance of the Example class and use that instance to set the value of myString in the main method. You cannot access an instance method from the main method without creating an instance of the object that contains it. This is the same reason we have to create an instance of the Scanner class to access the methods contained in it, these methods are instance methods. In the Math class, we simply call them through the class name, Math.pow(2,3) for example. Since the main method must be declared with the static modifier, it is considered to be a static context. To access an instance variable, we have to tell the main method which instance we want to access.
Caution: if you are working with instance variables and in your method create another instance of your class, you are not working on the same copy of the variable. For example, in the following code, two copies of the Example class are created and when the code is run, the output will be null instead of Hello.
public class Example { private String myString; public static void main(String[] args) { Example examp = new Example(); examp.myString = "Hello"; examp.printString(); } private void printString() { Example examp2 = new Example(); System.out.println(examp2.myString); } }
5.13. Exercises
5.13.1 Exercise 1
Read user input
- Create a method, getString, that allows the user to enter text from the keyboard and return the String entered by the user.
- Note: You can only have a single copy of the no parameter and one parameter methods defined in your class at a time. Start with the class methods and then comment them out when you write the instance methods.
5.13.2 Exercise 2
Read a String (class method, no parameters) Using the keyword static, define this method.
- Create an instance of the Scanner class.
- Prompt the user to enter a String
- Using the Scanner instance, read the String
- Return the String the user entered
- Call the method from the main method
5.13.3 Exercise 3
Read a String (class method, Scanner passed as a parameter) Using the keyword static, define this method.
- Prompt the user to enter a String
- Using the Scanner instance passed to the method, read the String
- Return the String the user entered
- Create an instance of the Scanner class in the main method
- Call the method from the main method passing the Scanner instance as a parameter
5.13.4 Exercise 4
Read a String (instance method, no parameters) Without using the keyword static, define this method.
- Create an instance of the Scanner class.
- Prompt the user to enter a String
- Using the Scanner instance, read the String
- Return the String the user entered
- Create an object of your class in the main method
- Using this object, call your method from the main method
5.13.5 Exercise 5
Read a String (instance method, Scanner passed as a parameter) Using the keyword static, define this method.
- Prompt the user to enter a String
- Using the Scanner instance passed to the method, read the String
- Return the String the user entered
- Create an object of your class in the main method
- Create an object of the Scanner class in the main method
- Using the object of your class, call the method passing the Scanner object as the parameter
5.13.6 Exercise 6
Sum of numbers
- Create a method named sum that takes two numbers and returns the sum of these two numbers.
Sum of Integers
- Create a method sum that takes two parameters, both integers. Do not use the keyword static in this method declaration. This method should return an integer. Create code in your main method that calls this method.
Sum of Floating Point Numbers
- Create a method sum that takes two parameters, both doubles. This method should return a double. Do not use the keyword static. Create code in the main method that calls the sum method with two doubles, with two ints and with one double and one int. Which method gets called in each case. Hint, you may want to put a print statement into each method to help determine which method is called. Why is the specific method called?
5.13.7 Exercise 7
Get User Input
- Write a method, getInput, that allows the user to enter a String and returns this value to be printed using your printString method defined above. Again, do not use the static keyword on your methods other than main.
5.13.8 Exercise 8
Even Number
- Create a class that asks the user to enter a number. Call a method isEven that returns true or false if the number is even. The return from isEven should be passed to printEven which will print "The number is even" if the number is even and "The number is odd" if the number is odd. Determination of what to print must be done based on the return from the isEven method.
5.13.9 Exercise 9
Calculate Fibonacci Sequence
- Write a method, printFib, that takes an integer argument. In this method, create the code required to generate A Fibonacci Sequence with that many numbers. Your main method should contain a loop allowing the user to print multiple sequences, ask them if they want to print another sequence.
5.13.10 Exercise 10
Is Prime
- Write a method, isPrime that takes an int as a parameter and returns true if the number is prime, false if it is not.
5.13.11 Exercise 11
Reverse String
- Create a method reverseString which takes a String as a parameter and returns a String with all of the characters reversed.
5.13.12 Exercise 12
Is Palindrome
- Create a method, isPalindrome, which returns true if the String passed to it is a palindrome and false if it is not.
5.13.13 Exercise 13
Get Address
- Create a class with instance variables to hold the name, street address, city, and state for a user. You should enter the name and address in the nameAddress method. You should enter the city and state in the cityState method. In the main method, print the complete address. You should not use the static keyword except for the main method.
5.13.14 Exercise 14
Get Game Scores
- Create a class that allows users to enter their name and their high score for the game. You should enter the name in a method which returns a String. You should pass the name to a method to allow the user to enter a String. Print the name and score from a method printScore. Allow the user to continue to enter users and scores until they do not enter a name.
5.13.15 Exercise 15
Rectangle size
- Create a method that allows the user to enter the height and width for a rectangle. You will need to use instance variables to hold the values entered. Once you obtain these measurements, call the calculateArea method passing these values to the method. This method should return the area of the rectangle. Once you have the area, call a method isLarge which takes as an int argument containing the area of the rectangle. This method should return true if the area of the rectangle is greater than 300, false if it is less than or equal to 300. Finally, create a method printSize which takes a boolean variable, the return of the isLarge method. If the boolean is true, print "This is a large rectangle." If it is false, print "This is a small rectangle." Create this program using the static keyword only for the main method.