Java Week 6
Java Week 6
Since the beginning of the course, we’ve been using the term method. You found out that a
method is a part of a class, and contains a particular set of instructions. So far, all the classes you
have written have contained just one method, the main method. In this chapter you will see how
a class can contain not just a main method, but many other methods as well.
A method is a block of code that, when called, performs specific actions mentioned in it.
➢ Reducing complexity: Complex programs can be broken down into smaller chunks of
code
➢ Code readability
Normally a method will perform a single well-defined task. Examples of the many sorts of task
that a method could perform are calculating the area of a circle, displaying a particular message
on the screen, converting a temperature from Fahrenheit to Celsius, and many more. In this
chapter you will see how we can collect the instructions for performing these sorts of tasks
together in a method. You will also see how, once we have written a method, we can get it to
perform its task within a program. When we do this we say that we are calling the method. When
we call a method, what we are actually doing is telling the program to jump to a new place
(where the method instructions are stored), carry out the set of instructions that it finds there,
and, when it has finished (that is, when the method has terminated), return and carry on where it
left off.
So in this chapter you will learn how to write a method within a program, how to call a method
from another part of the program and how to send information into a method and get information
back.
a method declaration. The components provide various information about the method. Below is
//method body
1) Access specifier
It is used to define the access type of the method. The above syntax sees the use of the
“public” access specifier. However, Java provides four different specifiers, which are:
package
➢ Default: It is the default access specifier used by the Java compiler if we don’t
mention any other specifiers. It is accessible only from the package where it is
declared
2) ReturnType
It defines the return type of the method. In the above syntax, “int” is the return type. We
can mention void as the return type if the method returns no value.
3) Method name
It is used to give a unique name to the method. In the above syntax, “addNumbers” is the
method name.
4) Parameter list
It is a list of arguments (data type and variable name) that will be used in the method. In
the above syntax, “int a, int b” mentioned within the parentheses are the parameter list.
You can also keep it blank if you don’t want to use any parameters in the method.
5) Method signature
The method signature is a combination of the method name and parameter list.
6) Method body
This is the set of instructions enclosed within curly brackets that the method will execute.
➢ Predefined
➢ User-defined
Predefined Methods
As the name gives it, predefined methods in Java are the ones that the Java class libraries already
define. This means that they can be called and used anywhere in our program without defining
them. There are numerous predefined methods, such as length(), sqrt(), max(), and print(), and
The example mentioned below uses three predefined methods, which are main(), print(), and
sqrt()
Java Program to Find the square root of a Number without using any in-built method
User-defined Methods
Custom methods defined by the user are known as user-defined methods. It is possible to modify
Calling a Method
Now that we have declared and defined our method, we can make use of it. The idea is that we
get the method to perform its instructions as and when we need it to do so. This process is
referred to as calling the method. To call a method in Java, we simply use its name, along with
the following brackets (in the case of a static method) or we create an object of the class first,
then call the method through the object, which is an instance of the class (this is in case of an
instance method).
Static Method
A method that has static keyword is known as static method. In other words, a method that
belongs to a class rather than an instance of a class is known as a static method. We can also
create a static method by using the keyword static before the method name.
The main advantage of a static method is that we can call it without creating an object. It can
access static data members and also change the value of it. It is used to create an instance
method. It is invoked by using the class name. The best example of a static method is the main()
method.
Instance Method
A method that does not have the static keyword is known as a non-static or instance method. It is
a non-static method defined in the class. Before calling or invoking the instance method, it is
It is possible to send some data into a method, and that method can also send data back to the
method that called it. Now we will look into this in more detail. Consider an example given
below:
import java.util.Scanner;
public class FindCost
{
public static void main(String[ ] args)
{
Scanner keyboard = new Scanner (System.in);
double price, tax;
System.out.print("Enter initial price:");
price = keyboard.nextDouble();
System.out.print("Enter tax rate: ");
tax = keyboard.nextDouble();
price = price * (1 + tax/100);
System.out.println("Cost after tax = " + price);
}
}
The above program prompts the user to input the initial price of a product and then calculate and
Let’s create another program with a different method to perform this calculation. In a real-life
application, this would be very useful, because we might need to call this method at various
points within the program, and, as you will see, each time we do so we could get it to carry out
the calculation for different values of the price and the tax. We will need a way to send in these
values to the method. But on top of that, we need to arrange for the method to tell us the result of
(datatype of the method). You can see that within these brackets we are declaring two variables,
both of type double. The variables declared in this way are known as the formal parameters of
the method. Formal parameters are variables that are created exclusively to hold values
sent in from the calling method. They are going to hold, respectively, the values of the price
and the tax that are going to be sent in from the calling method.
Now we can turn our attention to the body of the method, which as you can see, in this case,
The word return in a method serves two very important functions. First it ends the method: As
soon as the program encounters this word, the method terminates, and control of the program
jumps back to the calling method. The second function is that it sends back a value. In this case it
priceIn * (1 + taxIn/100)
The line in the main method that calls the method addTax is this one:
First, we will consider the items in brackets after the method name. As you might have expected,
there are two items in the brackets—these are the actual values that we are sending into our
method. They are therefore referred to as the actual parameters of the method. Their values are
copied onto the formal parameters in the called method. This process is referred to as passing
You should note that if the method is of type void, then there is no need to include a return
instruction: the method simply terminates once the last instruction is executed.
Now we can discuss how we actually call this method and use its return value. The whole
Method Overloading
The + operator is not only used for addition, but also for concatenating two strings. So the same
When two or more methods, distinguished by their parameter lists, have the same name
but perform different functions we say that they are overloaded. Method overloading means
two or more methods have the same name but have different parameter lists: either a different
example of what is known as polymorphism. Polymorphism literally means having many forms,
the phenomenon of having methods and operators with the same name performing different
max; the second call, with its three parameters, will call the second version. Not surprisingly then
10
5
Method Overriding
Method overriding occurs when a subclass (child class) has the same method as the parent class.
In other words, method overriding occurs when a subclass provides a particular implementation
of a method declared by one of its parent classes. In other words, If a subclass provides the
specific implementation of the method that has been declared by one of its parent class, it is