Chapter 04 - Methods in Java
Chapter 04 - Methods in Java
1
Outline
Introduction to Methods
What is a method?
Advantages of using methods
Types of Java methods
Standard Java methods
User defined methods
User Defined methods
Method definition
Method calling/invoking
Various example java programs
With return values
Without return values
With parameters
Without parameters
Overloaded methods (method overloading)
Scope of a variable
Passing arguments to methods
Pass by value
2
Pass by reference
Introduction to Methods
What is a method?
A Java method is similar to function in C/C++.
It is a collection of statements that are grouped together to
perform an operation.
In Java, every method must be part of some class which is
different from languages like C, C++, and Python.
Advantages:
Methods allow us to reuse the code without retyping the code.
Methods are time savers and help us to reuse the code
without retyping the code.
The methods also enable polymorphism
Methods can be overloaded or over ridden .
Methods allow recursion and it acts as a loop
3
Introduction to Methods
Types of Java methods
Depending on whether a method is defined by the user, or available in the
standard library, there are two types of methods in Java:
Standard Library Methods
User-defined Methods
Standard Library Methods
The standard library methods are built-in methods in Java that are readily
available for use.
These standard libraries come along with the Java Class Library (JCL) in a Java
archive (*.jar) file with JVM and JRE.
Examples:
sqrt() is a method of Math class. It returns the square root of a number.
Println methods is a method of System class. This method display data on dos
console.
User defined Methods
We can also create methods of our own choice to perform some task. Such
methods are called user-defined methods.
4
Introduction to Methods
Standard Library Methods
Standard Math Class in Java
The java.lang.Math class contains methods for performing
basic numeric operations such as the elementary
exponential, logarithm, square root, and trigonometric
functions.
Following are the fields for java.lang.Math class
static double E − This is the double value that is closer than any
other to e, the base of the natural logarithms.
static double PI − This is the double value that is closer than any
other to pi, the ratio of the circumference of a circle to its
diameter.
No import statement is needed when using any
method of this class. 5
Introduction to Methods
6
Introduction to Methods
7
User define methods
User define methods:
1)Define a method or method defination
2)Method calling/invoking
1) Define a method
In general, a method has the following syntax:
modifier static returnType methodName(list of parameters)
{
// Method body;
}
A method definition consists of a method header and a method
body. Here are all the parts of a method:
8
Modifier:
User define methods
Defines access type of the method i.e. from where it can be accessed in
your application. In Java, there 4 type of the access specifiers.
public: accessible in all classes in your application.
protected: accessible within the class in which it is defined and in
its subclass(es)
private: accessible only within the class in which it is defined.
default:(declared/defined without using any modifier) : accessible
within same class and package within which its class is defined.
static
If we use the static keyword, it can be accessed without creating objects.
returnType
It specifies what type of value a method returns.
For example if a method has int return type then it returns an integer
value.
Some methods perform the desired operations without returning a value.
In this case, the returnValueType is the keyword void. 9
User define methods
methodName
It is an identifier that is used to refer to the particular method in a
program.
Parameters list (arguments)
These are values passed to a method. We can pass any number of
arguments to a method.
The parameter list refers to the type, order, and number of the
parameters of a method.
Parameters are optional; that is, a method may contain no
parameters.
The method name and the parameter list together constitute
the method signature.
Method Body
The method body contains a collection of statements that define
what the method does. 10
User define methods
2) Method calling/invoking
To use a method, you have to call or invoke it.
When a program calls a method, program control is transferred to the
called method.
A called method returns control to the caller when its return statement is
executed or when its method‐ending closing brace is reached.
There are two ways to call a method; the choice is based on whether the
method returns a value or not.
If the method returns a value, a call to the method is usually treated as a
value.
For example: int larger = max(30, 40);
or you can use output statement to display that returned vale
If the method returns void, a call to the method must be a statement.
For example, the method println returns void. The following call is a
statement:
System.out.println("Welcome to Java!");
11
User define methods
What happens when a method is called/invoked?
12
User define methods
2) Method calling/invoking
To use a method, you have to call or invoke it.
When a program calls a method, program control is transferred to the called
method.
A called method returns control to the caller when its return statement is
executed or when its method‐ending closing brace is reached.
There are two ways to call a method; the choice is based on whether the
method returns a value or not.
If the method returns a value, a call to the method is usually treated as a value.
For example: int larger = max(30, 40);
or you can use output statement to display that returned vale
If the method returns void, a call to the method must be a statement.
For example, the method println returns void. The following call is a
statement:
System.out.println("Welcome to Java!");
13
Example Java Programs
Various example java programs
With return values
Without return values
With parameters
Without parameters
Write the java programs for the following by creating functions
To perform sum of two numbers by creating function sum. Discuss
various possibilities of function sum.
To calculate ab where a is the base and b is power.
Selection sort algorithm
Linear and binary searching using functions.
To display a line of characters ch whose length is N
Simple calculator program using function
Temperature conversion program using function
14
Example Programs
Java program to calculate power of a base by creating method power().
public class CalcPowerMethod
{
public static void main(String[] args)
{
System.out.println("3 power 4="+power(3,4));
System.out.println("2 power 3="+power(2,3));
System.out.println("2.3 power 3="+power(2.3,3));
System.out.println("5 power 2="+power(5,2));
}
public static double power(double base,int pow)
{
double res=1.0;
for(int i=0;i<pow;i++)
res*=base;
return res;
}
15
}
Example Programs
Temperature conversion program using methods to convert the Fahrenheit temperature to Celsius and vise versa.
The conersion Formulas:
import java.util.Scanner;
public class C2FOrF2C
{
public static void main(String[] args)
{
double f,c;
Scanner sc=new Scanner(System.in);
System.out.println("Choose type of conversion \n 1.Fahrenheit to Celsius \n 2.Celsius to Fahrenheit");
int ch=sc.nextInt();
switch(ch)
{
case 1: System.out.println("Enter Fahrenheit temperature");
f=sc.nextDouble();
c=celsius(f);
System.out.println("Celsius temperature is = "+c);
break;
case 2: System.out.println("Enter Celsius temperature");
c=sc.nextDouble();
f=fahrenheit(c);
System.out.println("Fahrenheit temperature is = "+f);
break;
default: System.out.println("please choose valid choice");
}
}
} 16
public class SelectionSort // java program to sort elements
{
public static void main(String []args)
{
int numarray[]={9,23,16,78,5,10,56};
int N=numarray.length;
System.out.println("the original un-sorted list is");
for(int i=0;i<N;i++)
System.out.print(" "+numarray[i]); public static int maxNumLoc(int list[],int start)
{
for(int i=0;i<N-1;i++)
int mx=list[start];
{ int loc=start;
int loc=maxNumLoc(numarray,i); for(int k=start+1;k<list.length;k++)
int temp=numarray[loc]; {
if(mx>list[k])
numarray[loc]=numarray[i]; {
numarray[i]=temp; mx=list[k];
} loc=k;
}
System.out.println("\nthe sorted list is"); }
for(int i=0;i<N;i++) return loc; // end of method body
System.out.print(" "+numarray[i]); } // end of class body
}
Method overloading
Two for more methods that have the same name but different parameter lists
within one class.
These methods differ from each other in terms of:
Number of arguments
Type of arguments
Order of arguments
The Java compiler determines which method is used based on the method
signature.
This is decided at the time of compilation. This is called static polymorphism
Overloading methods can make programs clearer and more readable.
Methods that perform closely related tasks should be given the same name.
Overloaded methods must have different parameter lists.
You cannot overload methods based on different modifiers or return types.
Sometimes there are two or more possible matches for an invocation of a
method due to similar method signature, so the compiler cannot determine
the most specific match. This is referred to as ambiguous invocation.
Method overloading
The methods enable polymorphism
There are two types of polymorphism in java:
Static Polymorphism also known as compile time polymorphism
Dynamic Polymorphism also known as runtime polymorphism
Compile time Polymorphism (or Static polymorphism)
Polymorphism that is resolved during compiler time is known as static
polymorphism. Method overloading is an example of compile time
polymorphism.
Static Polymorphism is also known as compile time binding or early
binding.
Runtime Polymorphism (or Dynamic polymorphism)
It is also known as Dynamic Method Dispatch. Dynamic polymorphism
is a process in which a call to an overridden method is resolved at
runtime, that's why it is called runtime polymorphism.
Dynamic Polymorphism is also known as run time binding or late
binding.
Method overloading
Example Program#01
public class OverloadSum
{
public static void main (String[] args)
{
System.out.println(“the sum two integer numbers is of 20 and 30 is ”+sum(20,30));
System.out.println(“the sum thre integer numbers is of 40,50 and 60 is”+sum(40,50,60));
}
Public int sum(int n1,int n2)
{
return n1+n2;
}
Public int sum(int n1,int n2,int n3)
{
return n1+n2+n3;
}
}
Method
Example Program#02
overloading public static void show(char type,int n)
public class OverloadShow {
{ for(int i=0;i<n;i++)
System.out.print(type);
public static void main(String[] args)
System.out.println();
{ }
show(); public static void show(char type)
System.out.println("Object Oriented Programming"); {
show('*',40); for(int i=0;i<50;i++)
System.out.println("Batch: 19CS"); System.out.print(type);
System.out.println();
show('*',40);
}
System.out.println("2nd Semester 1st year"); public static void show(int n)
show('='); {
System.out.println("Subject Teacher: FAM"); for(int i=0;i<n;i++)
show(30); System.out.print('-');
show(); System.out.println();
}
} // end of main method
public static void show()
{
for(int i=0;i<50;i++)
System.out.print('-');
System.out.println();
}
} // end of class body
Scope of variable
The scope of a variable is the part of the program where the variable can be referenced.
A variable defined inside a method is referred to as a local variable.
The scope of a local variable starts from its declaration and continues to the end of the
block that contains the variable.
A local variable must be declared before it can be used.
A parameter is actually a local variable. The scope of a method parameter covers the
entire method.
A variable declared in the initial action part of a for loop header has its scope in the
entire loop.
But a variable declared inside a for loop body has its scope limited in the loop body
from its declaration to the end of the block that contains the variable as shown below:
You can declare a local variable with the same name multiple times in different non‐
nesting blocks in a method, but you cannot declare a local variable twice in nested
blocks.
Passing arguments to methods
Passing arguments to methods
Pass by value
Pass by reference
Pass by Value
When you invoke a method with a parameter, the value of the argument is passed to
the parameter. This is referred to as pass‐by‐value.
If the argument is a variable rather than a literal value, the value of the variable is
passed to the parameter.
The variable is not affected, regardless of the changes made to the parameter inside the
method.
In fact, when passing arguments by value, a local copy of arguments are created.
If values of parameters are changed inside the method, it means that only local copies
of arguments are changed; original arguments stay unchanged.
Pass by reference
Java is always a pass by value; but, there are a few ways to achieve pass by reference:
Making a public member variable in a class
Return a value and update it
Create a single element array
Passing arguments to methods
Example#01: Passing arguments by value (swapping two integer numbers)
public class SwapPassValue
{
public static void main(String[] args)
{
int num1=20, num2=30;
System.out.println("Before swapping num1="+num1+"and num2="+num2);
swap(num1,num2);
System.out.println("After swapping num1="+num1+"and num2="+num2);
}