- Method Overview
1.1 What is a Method?
A method is a block of code that performs a specific task and can be called upon when needed. It encapsulates functionality and promotes code reusability.
Important:
- Methods must be defined before they can be used
- After definition, methods must be explicitly called to execute
- Method Definition and Invocation
2.1 Defining and Calling Methods Without Parameters
Definition Format:
public static void methodName() {
// method body
}
Example:
public static void displayGreeting() {
System.out.println("Hello, World!");
}
Invocation Format:
methodName();
Example:
displayGreeting();
Important: Methods must be defined before they are called, otherwise a compilation error will occur.
2.2 Method Invocation Process
When a method is called, it gets pushed onto the call stack and receives its own execution space. After the method completes, it's popped from the stack and removed.
2.3 Practice: Odd or Even Number Check
Requirement: Determine if a number is odd or even.
public class NumberChecker {
public static void main(String[] args) {
int value = 15;
checkParity(value);
}
public static void checkParity(int number) {
if (number % 2 == 0) {
System.out.println("Even number");
} else {
System.out.println("Odd number");
}
}
}
- Methods with Parameters
3.1 Defining and Calling Methods with Parameters
Definition Format:
public static void methodName(parameter1) {
// method body
}
public static void methodName(parameter1, parameter2, parameter3...) {
// method body
}
Examples:
public static void checkEven(int number) {
// implementation
}
public static void findMaximum(int num1, int num2) {
// implementation
}
Important: Both data type and variable name must be specified in method parameters. Missing either will cause errors.
Multiple parameters must be separated by commas.
Invocation Format:
methodName(parameter);
methodName(parameter1, parameter2);
Examples:
checkEven(10);
findMaximum(10, 20);
When calling methods, the number and type of arguments must match the method definition, otherwise erors will occur.
3.2 Formal vs. Actual Parameters
- Formal Parameters: Parameters defined in the method signature (like variable declarations:
int number) - Actual Parameters: Values passed during method invocation (like constants or variables:
10ornumber)
3.3 Practice: Print All Odd Numbers Between n and m
Requirement: Create a method to print all odd numbers between n and m.
Approach:
- Define a method named
printOdds() - Add two
intparameters to accept values - Implement a
forloop from n to m - Add
ifcondition to check for odd numbers - Call the method from
main()
import java.util.Scanner;
public class OddNumberPrinter {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter n: ");
int n = input.nextInt();
System.out.print("Enter m: ");
int m = input.nextInt();
printOdds(n, m);
}
public static void printOdds(int start, int end) {
for (int i = start; i <= end; i++) {
if (i % 2 != 0) {
System.out.print(i + ",");
}
}
}
}
- Methods with Return Values
4.1 Defining and Calling Methods with Return Values
Definition Format:
public static dataType methodName(parameters) {
return value;
}
Examples:
public static boolean isEven(int number) {
return true;
}
public static int findLarger(int a, int b) {
return 100;
}
Important: The return value must match the data type specified in the method definition.
Invocation Format:
methodName(parameters);
dataType variable = methodName(parameters);
Examples:
isEven(5);
boolean result = isEven(5);
Important: Return values are typically assigned to variables; otherwise they serve no purpose.
4.2 Practice: Find Maximum of Two Numbers
Requirement: Create a method to find the larger of two numbers.
Approach:
- Define a method with return value and two parameters
- Use
ifstatement to compare values - Return the appropriate result
- Call the method from
main()
public class MaxFinder {
public static void main(String[] args) {
int x = 15;
int y = 25;
int maximum = findMaximum(x, y);
System.out.println("Maximum value: " + maximum);
}
public static int findMaximum(int first, int second) {
return (first > second) ? first : second;
}
}
- Method Best Practices
Methods cannot be nested within each other:
public class MethodExample {
public static void main(String[] args) {
// main method
}
public static void outerMethod() {
public static void innerMethod() {
// This will cause a compilation error!
}
}
}
The void keyword indicates no return value. You can either omit return or use it alone without a value:
public class VoidExample {
public static void main(String[] args) {
// main method
}
public static void demonstrateReturn() {
return; // valid
// return 100; // compilation error - no return type specified
// System.out.println(100); // unreachable code after return
}
}
- Method Overloading
6.1 Method Overloading Concept
Method overloading occurs when multiple methods in the same class have:
- The same method name
- Different parameter lists (type, number, or both)
Important: Overloading is determined by method name and parameters only. Return type does not affect overloading.
Correct Examples:
public class OverloadDemo {
public static void calculate(int a) {
// implementation
}
public static int calculate(double a) {
// implementation
}
}
public class OverloadDemo {
public static float process(int a) {
// implementation
}
public static int process(int a, int b) {
// implementation
}
}
Incorrect Examples:
public class OverloadDemo {
public static void calculate(int a) {
// implementation
}
public static int calculate(int a) {
// ERROR: Overloading is not determined by return type
}
}
public class Demo1 {
public static void calculate(int a) {
// implementation
}
}
public class Demo2 {
public static int calculate(double a) {
// ERROR: These are methods in different classes
}
}
6.2 Method Overloading Practice
Requirement: Create overloaded methods to compare two integers of different types (byte, short, int, long).
Approach:
- Define a
compare()method with twointparameters - Create overloaded versions with
longparameters - Add methods for
byteandshorttypes - Call all overloaded methods
public class NumberComparator {
public static void main(String[] args) {
System.out.println(compare(10, 20));
System.out.println(compare((byte) 10, (byte) 20));
System.out.println(compare((short) 10, (short) 20));
System.out.println(compare(10L, 20L));
}
public static byte compare(byte a, byte b) {
return (a == b) ? (byte)0 : (byte)-1;
}
public static byte compare(short a, short b) {
return (a == b) ? (byte)0 : (byte)-1;
}
public static byte compare(int a, int b) {
return (a == b) ? (byte)0 : (byte)-1;
}
public static byte compare(long a, long b) {
return (a == b) ? (byte)0 : (byte)-1;
}
}
- Method Parameter Passing
7.1 Parameter Passing - Primitive Types
package com.example.param;
public class PrimitiveTest {
public static void main(String[] args) {
int value = 100;
System.out.println("Before change: " + value);
modifyValue(value);
System.out.println("After change: " + value);
}
public static void modifyValue(int number) {
number = 200;
}
}
Result: The original value remains unchanged.
Conclusion: Changes to formal parameters of primitive types do not affect actual parameters.
Reason: Each method has its own stack space. When the method finishes, its stack frame is removed, so changes are not preserved.
7.2 Parameter Passing - Reference Types
package com.example.param;
public class ReferenceTest {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
System.out.println("Before change: " + numbers[1]);
modifyArray(numbers);
System.out.println("After change: " + numbers[1]);
}
public static void modifyArray(int[] array) {
array[1] = 200;
}
}
Result: The original array is modified.
Conclusion: Changes to formal parameters of reference types affect the actual parameters.
Reason: Reference types pass memory addresses. Both references point to the same memory location, so modifications persist even after the method completes.