0% found this document useful (0 votes)
19 views

Java Week 6

Uploaded by

sophlucy747
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Java Week 6

Uploaded by

sophlucy747
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Methods

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.

Methods are important because they allow for:

➢ Code reusability: Define once and use multiple times.

➢ 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.

Declaring and Defining Methods


A method can only be created within a class. There are a total of six (6) components included in

a method declaration. The components provide various information about the method. Below is

the syntax to declare a method and its components list.

public int addNumbers (int a, int b)

//method body

The six components included in a method declaration will be declared below:

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:

➢ Public: You can access it from any class

➢ Private: You can access it within the class where it is defined

➢ Protected: Accessible only in the same package or other subclasses in another

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.

Below is an example of writing a Java method


Types of Methods in Java

Methods in Java can be broadly classified into two types:

➢ 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

each of them is defined inside their respective classes.

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

and tweak these methods according to the situation.

An example of a User-defined method is the addNumbers methods example above.

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

necessary to create an object of its class.


Method Input and Output

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

display its cost after tax.

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

adding the new tax, if it didn’t do that, it wouldn’t be much use.

The method is going to look like this:


static double addTax(double priceIn, double taxIn)
{
return priceIn * (1 + taxIn/100);
}
Starting from the method header, we have the keyword Static, and then followed by double

(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,

consists of a single line:

return priceIn * (1 + taxIn/100);

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

sends back the result of the calculation:

priceIn * (1 + taxIn/100)
The line in the main method that calls the method addTax is this one:

price = addTax(price, tax);

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

parameters and is illustrated below.

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

program appears 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 = addTax(price, tax); // call the addTax method
System.out.println("Cost after tax = " + price);
}
static double addTax(double priceIn, double taxIn)
{
return priceIn * (1 + taxIn/100);
}
}

Method Overloading

The + operator is not only used for addition, but also for concatenating two strings. So the same

operator can behave differently depending on what it is operating on—operators can be

overloaded. Methods too can be overloaded.

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

number of parameters or different types of parameters. Method overloading is actually one

example of what is known as polymorphism. Polymorphism literally means having many forms,

and it is an important feature of object-oriented programming languages. It refers, in general, to

the phenomenon of having methods and operators with the same name performing different

functions. An example code is given below.

public class OverloadingDemo


{
public static void main(String[] args)
{
int maxOfTwo, maxOfThree;
maxOfTwo = max(2, 10); // call the first version of max
maxOfThree = max(-5, 5, 3); // call the second version of max
System.out.println(maxOfTwo);
System.out.println(maxOfThree);
}
// this version of max accepts two integers and returns the greater of the two
static int max(int firstIn, int secondIn)
{
if(firstIn > secondIn)
{
return firstIn;
}
else
{
return secondIn;
}
}
// this version of max accepts three integers and returns the greatest of the three
static int max(int firstIn, int secondIn, int thirdIn)
{
int result;
result = firstIn;
if(secondIn > result)
{
result = secondIn;
}
if(thirdIn > result)
{
result = thirdIn;
}
return result;
}
}
As the first call to max in the main method has two parameters, it will call the first version of

max; the second call, with its three parameters, will call the second version. Not surprisingly then

the output from this program looks like this:

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

known as method overriding.

You might also like