10-Methods in Java
10-Methods in Java
An Introduction
OBJECTIVES
3
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);
4
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);
5
SOLUTION
public static int sum(int i1, int i2) {
int sum = 0;
for (int i = i1; i <= i2; i++)
sum += i;
return sum;
}
• It is common to
use if...else statements
inside methods:
JAVA METHOD OVERLOADING
• With method overloading, multiple methods can have the same name with different
parameters:
Example:
int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)
JAVA METHOD
OVERLOADING
• Consider the following
example, which has
two methods that add
numbers of different
type:
JAVA METHOD
OVERLOADING
• Instead of defining two
methods that should do the
same thing, it is better to
overload one.
• In the example below, we
overload
the AdditionMethod method
to work for
both int and double:
JAVA SCOPE
• In Java, variables are only accessible inside the region they are created.
• This is called scope.
METHOD SCOPE
• Variables declared directly inside
a method are available anywhere
in the method following the line
of code in which they were
declared:
BLOCK SCOPE
• A block of code refers to all of the
code between curly braces {}.
• Variables declared inside blocks of
code are only accessible by the
code between the curly braces,
which follows the line in which the
variable was declared:
BLOCK SCOPE
• A block of code may exist on its own or it can belong to an if, while or for statement.
• In the case of for statements, variables declared in the statement itself are also available inside
the block's scope.
SAMPLE
PROGRAM
USING
METHODS
YOUR ASSIGNMENT:
• https://www.w3schools.com/java/java_methods.asp