0% found this document useful (0 votes)
10 views32 pages

Java Methods: Definitions and Examples

The document provides an introduction to methods in Java, explaining their definition, usage, parameters, and arguments. It includes examples of how to implement methods for summing integers and discusses concepts like method overloading and scope. Additionally, it presents an assignment to create methods for multiplication and division while applying method overloading.
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)
10 views32 pages

Java Methods: Definitions and Examples

The document provides an introduction to methods in Java, explaining their definition, usage, parameters, and arguments. It includes examples of how to implement methods for summing integers and discusses concepts like method overloading and scope. Additionally, it presents an assignment to create methods for multiplication and division while applying method overloading.
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

METHODS IN JAVA

An Introduction
OBJECTIVES

• Define method, parameters and arguments.


• Discuss how methods are used in writing programs in Java.
• Write a Java program implementing methods.
• Compare programs written in Java using methods and without methods.
OPENING PROBLEM
Find the sum of integers from 1 to 10, from 20 to 30, and
from 35 to 45, respectively.

3
PROBLEM
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
[Link]("Sum from 1 to 10 is " + sum);

sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
[Link]("Sum from 20 to 30 is " + sum);

sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
[Link]("Sum from 35 to 45 is " + sum);

4
PROBLEM
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
[Link]("Sum from 1 to 10 is " + sum);

sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
[Link]("Sum from 20 to 30 is " + sum);

sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
[Link]("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;
}

public static void main(String[] args) {


[Link]("Sum from 1 to 10 is " + sum(1, 10));
[Link]("Sum from 20 to 30 is " + sum(20, 30));
[Link]("Sum from 35 to 45 is " + sum(35, 45));
}
6
WHAT IS A METHOD?

• A method is a block of code which only runs when it is called.


• A method is a collection of statements that are grouped together to perform an operation.
• You can pass data, known as parameters, into a method.
• Methods are used to perform certain actions, and they are also known as functions.
• Why use methods? To reuse code: define the code once and use it many times.
CREATE A METHOD Example: Create a method inside Main:

• A method must be declared within a class.


It is defined with the name of the method,
followed by parentheses ().
• Java provides some pre-defined methods,
such as [Link](), but you can
also create your own methods to perform
certain actions:
EXAMPLE EXPLAINED

• myMethod() is the name of the method


• static means that the method belongs to the Main
class and not an object of the Main class.
• void means that this method does not have a
return value.
CALL A METHOD Inside main, call the myMethod() method:

• To call a method in Java, write the


method's name followed by two
parentheses () and a semicolon;
• In the following
example, myMethod() is used to
print a text (the action), when it is
called:
A METHOD
CAN ALSO BE
CALLED
MULTIPLE
TIMES:
PARAMETERS AND ARGUMENTS

• Information can be passed to methods as parameter.


• Parameters act as variables inside the method.
• Parameters are specified after the method name, inside the parentheses. You
can add as many parameters as you want, just separate them with a comma.
PARAMETERS
AND ARGUMENTS

• The following example has a


method that takes
a String called firstname as
parameter.
• When the method is called,
we pass along a first name,
which is used inside the
method to print the full
name:
PARAMETERS
AND ARGUMENTS

• When a parameter is passed


to the method, it is called
an argument. So, from the
example: firstname is
a parameter, while Angela,
Mark and Cristelle
are arguments.
MULTIPLE
PARAMETERS

• You can have as many


parameters as you like:
RETURN VALUES

• The void keyword, used in the examples


above, indicates that the method should
not return a value.
• If you want the method to return a
value, you can use a primitive data type
(such as int, char, etc.) instead of void,
and use the return keyword inside the
method:
THIS EXAMPLE
RETURNS THE
SUM OF A
METHOD'S TWO
PARAMETERS:
• You can also store
the result in a
variable
(recommended, as
it is easier to read
and maintain):
A METHOD WITH
IF...ELSE

• 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:

1. Based on the given sample program, add a


method to multiply two integers and a method to
divide two integers.
2. Apply method overloading to minimize the given
sample code.
ACCEPTING
INPUT FROM
THE USER
REFERENCES:

• [Link]

Common questions

Powered by AI

Static methods in Java are associated with the class itself rather than with any particular object, allowing for global access without instantiation. They are beneficial for operations that do not rely on object states, such as common mathematical operations. In contrast, object methods require an object to call them, supporting encapsulation and association with instance data. For example, a static method for addition can be called globally like `ClassName.add(a, b)`, whereas an object method involves creating an object's instance, which is not necessary for simple, stateless operations .

Accepting multiple parameters in a Java method allows developers to increase the method's capability and handle more complex operations with varied input. This practice facilitates richer method functionality and enhances customization by processing data sets concurrently within a single method call. For instance, using two parameters in a summation method allows not only flexibility in specifying ranges but also makes the method adaptable for different business logic, such as thresholds or configurable limits .

Method overloading in Java occurs when multiple methods have the same name but different parameters, allowing for different implementations based on input types or number of inputs. This technique is beneficial when similar operations need different input data types or counts, such as a scenario where you have to add both integer and floating-point numbers. Instead of defining separate methods like `int add(int, int)` and `double add(double, double)`, method overloading allows these to be reconciled under a single method name, aiding code clarity and reducing redundancy .

Returning values from methods instead of directly printing them allows greater flexibility and integration into other parts of a program, making it easier to use the results in further calculations or logic without modifying the method. This separation improves code reusability and allows the method to serve a broader purpose beyond immediate output. For example, a method returning a sum can be called in various places, assignments, or conditions, without cluttering the output interface with unnecessary details .

In Java, scope rules determine the accessibility of variables. Method scope restricts variables to the method they are declared in, whereas block scope limits them to the immediate block defined by curly braces `{}`. For instance, in a method, a variable declared inside a loop block will not be accessible outside that block, preserving its lifecycle and avoiding interference with similarly named variables elsewhere. For example, in a `for` loop, an index variable, say `i`, is accessible only within that loop and not beyond .

Using methods in Java allows for code reuse, modularizes the program, and enhances readability. When calculating sums, methods enable defining the summation code once and reuse it with different parameters, which simplifies maintenance and reduces errors. By using methods, you avoid code repetition, as seen in the solution where a method calculates sums from different ranges by calling `sum()` with different arguments .

Refactoring repeated code blocks into a single method enhances maintainability, reduces errors, and optimizes performance by enforcing code reuse. It centralizes changes to logic in one location, improving scalability when code evolves. This consolidation simplifies testing and debugging, as seen when calculating different integer sums using a method rather than three separate loops. This approach reduces the chance of inconsistencies across repeated implementations and saves execution time by minimizing compiled code size .

Parameters in Java methods allow arguments to be passed, making the methods flexible and reusable across various contexts. Parameters act as placeholders for data that a method will operate on, facilitating different outcomes based on input arguments. This abstraction enables the same method to perform specific tasks without rewriting for different data inputs. For example, a summation method with parameters `int i1, int i2` is versatile enough to compute sums for any integer range .

Proper use of method and block scope in Java enhances memory management by restricting variable lifespan and accessibility, thus preventing unnecessary memory consumption and variable conflicts. By limiting scope to the smallest context necessary, Java programs are easier to debug and maintain, as variable states are localized and predictable. It avoids side effects from unintended variable interactions, which can significantly aid in tracing issues and optimizing resources, especially in large-scale applications .

The choice between 'void' and returning a value in method design impacts how the method can be used and integrated into program flow. 'Void' is used when the method performs an action without a need for feedback, suitable for simple actions like printing. Returning a value makes the method useful for computations, allowing its result to be directly used in expressions or another processing, thereby enhancing its utility and flexibility in complex procedures or iterative adjustments .

You might also like