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.
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.
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; }
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.
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.
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.
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.
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.
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.
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.
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.
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);
}
Methods belong to either the class or an object of the class.
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.
To call a class method from within the same class, simply use the method name and associated parameters.
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.
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.
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.
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); } }
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); } }
Read user input
Read a String (class method, no parameters) Using the keyword static, define this method.
Read a String (class method, Scanner passed as a parameter) Using the keyword static, define this method.
Read a String (instance method, no parameters) Without using the keyword static, define this method.
Read a String (instance method, Scanner passed as a parameter) Using the keyword static, define this method.
Sum of numbers
Sum of Integers
Sum of Floating Point Numbers
Get User Input
Even Number
Calculate Fibonacci Sequence
Is Prime
Reverse String
Is Palindrome
Get Address
Get Game Scores
Rectangle size