METHODS
WHAT IS METHOD?
A block of code that performs a specific task
It define behaviors/actions that can be called by other
parts of the program
Helps in organizing code, improve reusability and
maintaining structure
METHOD COMPONENTS
Parameter list
Return Type Method Name
Method Modifiers
Method Header
Body of method
Passing arguments
The datatype of an argument in a
method must coresspond to the
variable declaration in the parentheses
of a method declaration.
formal parameter
p i (formal parameter)
received the age so that
is why they must have
same data type
In a same class
call displayAge () method and passed
the age (actual parameter)
method call
actual parameter
ORDER MATTERS !
All arguments of the primitive data types (int, char, double, etc.) are passed by
VALUE, only a COPY of an argument’s value is passed into a parameter variable.
public static void modifyValue(int x)
*if a parameter is changed
{
inside a method, it has no
x = x + 10; // Changes the local copy of x
System.out.println("Inside method: " + x); // Output 15 effect to the original
} argument
public static void main(String[] args)
{
int number = 5;
System.out.println("Before method call: " + number); // Outputs 5
modifyValue(number);
System.out.println("After method call: " + number); // Outputs 5 (no change outside the method)
}
Passing Object
references to method
In Java, String is not a primitive data type (line int, double), it is a built-in class in
Java Library.
Any instance of a class (like String) is an object in Java.
For example: String name = “Alexander”;
this created an instance of the String class which makes ‘name’ a reference
variable that points to a String object in memory.
‘name’ does not hold the actual string value, it holds a reference (memory
adress) to the String object “Alexander” in memory.
name points to the String object “Alexander Bell” in memory
reference is copied & passed to S1
S1 points to the same object “Alexander Bell” in memory
When S1 is reassigned to “Alpha”, it is now points to a new String
object in memory
This does not affect the original ‘name’ reference which still points
to “Alexander Bells”
WHY ?
String are immutable [ cannot be modified ]
Any reassignment created new object
Local variable
A method’s local
Declared inside a variables exist only
Different methods
method, not while the method is Local variables must
can have local
accessible to executing. When the be given a value
variables with same
statements outside method ends, the before they can be
names beacuse the
the method local variables and used
methods cannot see
parameter variables
each other’s local
are destroyed and
variables
any values stored are
lost
Local variable
public class LocalVariableExample {
public static void main(String[] args) {
displayMessage(); // Call the displayMessage method
calculateSum(); // Call the calculateSum method
}
// Method 1: Using a local variable
public static void displayMessage() {
String message = "Hello, Local Variables!" ; // message is a local variable
System.out.println(message);
}
// Method 2: Using local variables in a calculation
public static void calculateSum() {
int a = 10; // a is a local variable
int b = 20; // b is a local variable
int sum = a + b; // sum is a local variable
System.out.println("The sum is: " + sum);
}
// Uncommenting the below line will cause an error
// System.out.println(message); // ERROR: message is not accessible here because it is only accesble in displayMessage() method
}
VALUE RETURNING
METHOD
A value-returning method is a method that performs a task and returns a value to the part
of the program that called it.
This type of method is declared with a return type ( eg. int, double, String) and it uses the
return statement to send the value back to the caller.
Syntax
returnType methodName (parameters)
{
// Code to perform the task
return value; // The returned value must match the return type
}
return type
Alternative Way
public static int sum (int num1, int num2) The return statement can directly
{ contain the expression that
int result; calculates the value if it is a simple
result = num1 + num2; operation
return result;
}
public static int sum (int num1, int num2)
{
return num1+num2;
this expression must be same data type as return type
}
return keyword must be included in value-returning method
*If you forget to include a return statement in a value-returning
method, you will get a compilation error.
return type
public static int sum (int num1, int num2)
{
int result;
result = num1 + num2; return statement causes the method to end
execution & it returns a value back to the
return result; statement that called the method
}
this expression must be same data type as return type
return keyword must be included in value-returning method
*If you forget to include a return statement in a value-returning
method, you will get a compilation error.
public static int sum (int num1, int num2)
{
int result;
result = num1 + num2; return statement causes the method to end
execution & it returns a value back to the
return result; statement that called the method
60
}
total = sum (value1, value2) ; // method caller
20 40
Practice 1
Easy
Check if a Number is Positive
Write a method called isPositive that:
Takes an integer as an argument.
Returns true if the number is positive, and false otherwise.
In main method:
receive an integer input from user
Pass the input to isPositive()
Print the output either “It is a positive number” or “ It is a negative number”
Practice 2
Easy
Multiply a Number by 2
Create a method called multiplyby2
that takes an integer as input
returns the result of multiplying it by 2
In main method :
Receive an integer input from user
Pass the input to doubleNumber()
Print the output
Practice 3
Easy
Calculate Hypotenuse
Create a method called calculateHypotenuse
that takes two double as parameter, a and b
returns the hypothenuse of right triangle
with side a and b
return type Double
In main method :
Receive two double input from user
Pass the input to calculateHypotenuse()
Print the output
Practice 4
Create Array Medium
Create a method called createArray
that takes an two integer as parameter
first parameter determine the length of the array
second parameter determine the value in the
elements in the array
return an array of integers
In main method :
Receive two integer input from user
Pass the inputs to createArray()
Print the elements in the array
Practice 5
Medium
Editing Array
Create a method called editArray
that takes an array of integers as input
increment all the array element by 1
return an array of integer
In main method :
Receive integer value of n from user
Receive n number of integer inputs from the user
Store it in an array and pass it to editArray()
Print the the edited Array
Practice 6
MEDIUM+
Finding Max
Create a method called findMaxIndex
that takes an array of intergers as parameter
return an integer of Highest value index
In main method :
Receive integer value of n from user
Receive n number of integer inputs from the user
Store it in an array and pass it to findingMaxIndex()
Print the HIghest value in the array and it’s index