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

Lecture 12 (Methods01)

Uploaded by

sumrun sahab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lecture 12 (Methods01)

Uploaded by

sumrun sahab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Methods in Java

Rizwan Rashid
Opening Problem
• Find the sum of integers from 1 to 10, from 20
to 30, and from 35 to 45, respectively.
Problem
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
System.out.println("Sum from 1 to 10 is " + sum);

sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
System.out.println("Sum from 20 to 30 is " + sum);

sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
System.out.println("Sum from 35 to 45 is " + sum);
Problem
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
System.out.println("Sum from 1 to 10 is " + sum);

sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
System.out.println("Sum from 20 to 30 is " + sum);

sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
System.out.println("Sum from 35 to 45 is " + sum);
Solution
public static int sum(int i1, int i2) {
int sum = 0;
for (int i = i1; i <= i2; i++)
sum += i;
return sum;
}

public static void main(String[] args) {


System.out.println("Sum from 1 to 10 is " + sum(1, 10));

System.out.println("Sum from 20 to 30 is " + sum(20, 30));

System.out.println("Sum from 35 to 45 is " + sum(35, 45));


}
Methods
A method is a collection of statements grouped together to perform an operation

• Pre-defined Methods
– Already defined in the Java class libraries known
as standard library method or built-in method
– println(), Math.pow(), input.nextInt(), etc.
• User-defined Methods
– The method written by the user or programmer
– Modified as per requirement
Defining a Method
• Syntax
modifier returnValueType methodName(list of parameters)
{
// Method body;
}
Defining a Method
• Access Specifier:
– It specifies the visibility of the method. Java provides four
types of access specifier:
– Public: The method is accessible by all classes
– Private: The method is accessible only in the classes in
which it is defined
– Protected: The method is accessible within the same
package or subclasses in a different package
– Default: When we do not use any access specifier in the
method declaration, Java uses default access specifier by
default. It is visible only from the same package only.
Method Signature
Method signature is the combination of the method name and the
parameter list.

Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}
Formal Parameters
The variables defined in the method header are known
as formal parameters.

Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}
Actual Parameters
When a method is invoked, you pass a value to the parameter. This
value is referred to as actual parameter or argument.

Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}
Return Value Type
A method may return a value. The returnValueType is the data
type of the value the method returns. If the method does not
return a value, the returnValueType is the keyword void. For
example, the returnValueType in the main method is void.
Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}
Naming a Method
• Single-word method name: sum(), area()
• Multi-word method name: areaOfCircle(),
stringComparision()
• It is also possible that a method has the same
name as another method name in the same
class, it is known as method overloading.
Java main() method
• The main() is the starting point for JVM to start execution of a
Java program
public:
JVM can identify the execution
point of the program. If we use
private, protected, and default
before the main() method, it will
not be visible to JVM

static:
Static methods are the method
which invokes without creating
the objects, so we do not need
any object to call the main()
method.
String args[]:
main(): The main() method also
void: It is a default signature which is accepts some data from the
Void keyword acknowledges predefined in the JVM. It is called user. It accepts a group of
the compiler that main() by JVM to execute a program line strings, which is called a string
method does not return any by line and end the execution after array. It is used to hold the
value. completion of this method. We can command line arguments in
also overload the main() method. the form of string values.
Java main() method
• What happens if the main() method is written without String
args[]?
– The program will compile, but not run, because JVM will not recognize
the main() method
– JVM always looks for the main() method with a string type array as a
parameter. public static void main(String[] args){
System.out.println("Hello");
• Execution Process }
static //static block
1. First, JVM executes the static block {
System.out.println("Static block");
2. Then it executes static methods }
3. Then it creates the object needed by the program
4. Finally, it executes the instance methods
Different way to write main()
• public static void main(String args[])
• static public void main(String args[])
• static public void main(String[] x)
• static public void main(String []x)
• static public void main(String...args)
Calling a Method
• Calling a method executes the code in
the method
• Method definition: indicates what the
method does
• How to call a method?
1. Value returning method: a call to the
method is treated as a value
int larger = max(3, 4);

or System.out.println(max(3, 4));

2. Void method: a call to the method


must be a statement
System.out.println(‚Hello‛);
Calling a Method
• When a program calls a method, program control is
transferred to the called method
• How is the control returned?
– return statement is executed OR
– Ending closing brace ( } )is reached
Using/reusing a method
public class TestMax {
/* main method */
public static void main(String[] args){
i j k num1 num2 result
int i = 5;
5 int j = 2;
int k = max(i, j);
2
System.out.println("The max of "
5 2 + i + " and " + j + " is " + k);
undefined
}
/* Returns the maximum of two numbers */
public static int max(int num1, int
5
num2){
5
int result;
if(num1 > num2)
result = num1;
else
The max of 5 and 2 is 5 result = num2;
return result;
Reusing a static method: Classname.methodName
}
Reusing max(): TestMax.max
}
Calling a Method
Activation record & call stack
• Each time a method is invoked, the system creates an
activation record, a.k.a activation frame
– Stores parameters and variables for the method
• The system places the record in an area of memory
known as a call stack (a.k.a execution stack, runtime
stack, machine stack, or just stack)
– Information is stored in a last-in, first-out fashion
• When a method calls another method, the caller’s
activation record is kept intact, and a new activation
record is created for the called method
• When the called method finishes its work and returns
to its caller, its activation record is removed from the
call stack
Call stack: example
public class TestMax { Activation record for max Activation record for max
method method
/* main method */
public static void main(String[] args){ result: result: 5
int i = 5; num2: 2 num2: 2
num1: 5 num1: 5
int j = 2;
int k = max(i, j); Activation record for main Activation record for main
System.out.println("The max of " method method
+ i + " and " + j + " is " + k);
k: k:
} j:2 j:2
/* Returns the maximum of two numbers */ i:5 i:5
public static int max(int num1, int
num2){
int result;
if(num1 > num2)
result = num1;
else Activation record for main
method
result = num2;
return result; k:5
} j:2 Stack is empty
i:5
}
Void method
• A void method does not
return a value.
• No return statement is
used; ending brace
returns the control to
the caller method

23
Void method with return
Passing arguments by values
• The arguments are passed by value to parameters
when invoking a method (pass-by-value)
– If the argument is a variable, the value of the variable is
passed to the parameter
• Parameter order association
– Arguments must be in the same order as their respective
parameters in the method signature
• Example:
• nPrintln(‚Hi‛, 3);
• nPrintln(3, ‚Hi‛);
• nPrintln(‚Hi‛, ‘3’);
Pass-by-value (example 1)
Pass-by-value (example 2)

What will happen if we change the parameter name n1 in swap


method to num1?
Overloading methods
• Overloading the methods enables their redefinition
with the same name
• Signatures of overloaded methods must be different
• Different number or type of parameters

double larger = max(12.3, 15.7);


int larger = max(10, 5);
max(2, 2.5); ????

Which max method will be invoked?

Why max(double, double) is not


invoked for the call max(3, 4)?
Ambiguous invocation of overloaded
method
• Two or more possible
matches for the
invocation
• Best match cannot be
determined
• Generates a compiler
error
Scope of variables
• The scope of a variable is the portion of the program where it
can be referenced
• Local variable: a variable defined inside a method
– Scope starts from its declaration; continues to the end of the block
– Must be declared and assigned a value before its use
– Method-level scope
• Parameter is a local variable: scope is within the entire method body
• Variables inside a method have method level scope
– Block-level scope
• A variable declared in header of a for-loop can be referenced in the entire
loop
• A variable declared inside for-loop’s body has its scope after declaration
till the end of loop
public class Test {
public static void
main(String[] args){
int x = 5;
System.out.println(x);
System.out.println(y);
}
public static void Method1(){
int x = 1;
int y = 10;
System.out.println(y);
System.out.println(z);
}
public static void Method2(){
int x = 13;
int y = 12;
int z = 5;
System.out.println(x);
System.out.println(y);
}
Scope of variables

A common mistake
Summary
• Method definition & calling
• Value returning method & void method
• The call stack
• Transfer of control
• Pass-by-value (argument passing)
• Method overloading
• The scope of variables

You might also like