User Define Methods
1. Introduction to Java Methods
In Java, a method is a collection of statements grouped together to perform a specific operation or task.
Also known as functions, methods are fundamental to Java programming, allowing for code reuse, which
improves efficiency and organization. All methods in Java must belong to a class and are executed only
when they are called or invoked.
1.1. Purpose of Methods
Breaking code into distinct methods offers several advantages:
● Reusability: A method can be written once and used multiple times throughout a program,
eliminating redundant code.
● Complexity Management: Large, complex problems can be broken down into smaller,
manageable tasks, each handled by a separate method.
● Readability and Maintainability: Code organized into smaller, named methods is easier to read,
understand, and debug.
● Abstraction (Hiding Details): Methods can hide the specific implementation details from the
caller, who only needs to know what the method does, not how it does it.
1.2. Types of Methods
Java methods are classified into two main categories:
Method Type Description Examples
Predefined Also known as standard library methods or built-in [Link](),
Methods methods, these are created by the developers of [Link](),
Java and are available in class libraries and [Link](),
packages.
[Link]()
User-Define These are methods written by the programmer to A custom method like
d Methods meet specific requirements. The logic and calculateArea() or
functionality are defined by the user. isPrime().
2. Anatomy of a User-Defined Method
A method is defined by its declaration, often referred to as the method prototype or header. The syntax
consists of several key components.
Syntax Example: public static void main(String args[])
Component Description Example Notes
Access Determines the public, If omitted, it defaults to package-private access.
Specifier visibility and private, This part is optional.
accessibility of the protected
method.
Modifier Keywords that static The static keyword designates the method as a
provide additional class method, which can be called without creating
characteristics to an object. If omitted, the method is a non-static
the method. instance method. Other modifiers include final,
native, etc. This is optional.
Return Type Specifies the data int, If a method does not return any value, the void
type of the value double, keyword is used. Every method must have a return
the method boolean, type.
returns.
String
Method A unique identifier main, calc, Naming conventions suggest using a lowercase
Name for the method. checkEven verb. For multi-word names, camelCase format
(e.g., areaOfCircle) is standard.
Parameter A (int x, Each parameter must have a data type and a name.
List comma-separated int y) If a method takes no inputs, the parentheses are left
list of input empty.
variables
(arguments)
enclosed in
parentheses ().
Method The block of code, { int This is where the method's logic resides.
Body enclosed in curly diff = x
braces {}, that - y;
contains the return
statements to be
diff; }
executed.
2.1. Method Prototype vs. Method Signature
These terms are closely related but distinct:
● Method Prototype (or Header): The entire first line of the method definition, including the
access specifier, return type, name, and parameter list.
○ Example: public static int sum(int a, int b)
● Method Signature: A subset of the prototype, consisting only of the method name and the
parameter list (including the number, type, and order of parameters). The return type is not part of
the signature.
○ Example: sum(int a, int b)
The method signature is what Java uses to distinguish between overloaded methods.
3. Method Classification and Behavior
3.1. Static vs. Non-Static (Instance) Methods
The static keyword is a crucial modifier that dictates how a method is accessed.
● Static Methods:
○ Also called class methods.
○ Declared using the static keyword.
○ Belong to the class itself, not to any specific object (instance).
○ They can be called directly using the class name, without needing to create an object of
that class. Example: [Link]().
○ Static methods can only access static data members and call other static methods
directly.
● Non-Static Methods:
○ Also called instance methods.
○ Declared without the static keyword.
○ Belong to an instance (object) of the class.
○ To invoke a non-static method, an object of the class must be created first. The call is then
made through the object. Example: [Link]().
3.2. Return Values and the Statement
A method can either perform an action without sending back a result (void) or compute a value and
return it to the caller.
● Void Methods: Declared with the void return type, these methods do not return a value. The
return; statement can be used to exit the method early, but it cannot return a value.
● Value-Returning Methods: Declared with a specific data type (e.g., int, String), they must
use the return statement to send a value back to the caller.
○ The data type of the value being returned must match the declared return type.
○ The return statement is the last statement executed in a method; any code placed after
it becomes an "unreachable statement" and causes a compile-time error.
○ A method can have multiple return statements (e.g., in different branches of an
if-else block), but only one will be executed per call.
3.3. Pure vs. Impure Methods
Methods can also be categorized based on whether they cause side effects.
Aspect Pure Method Impure Method
Definition A method whose return value depends A method that may change the state of
solely on its arguments and does not an object, modify its arguments, or have
modify the state of any objects or have other side effects (e.g., I/O operations).
other side effects.
Behavior Given the same input, it will always Given the same input, it might produce
produce the same output. different return values on different calls
(e.g., a method using [Link]()).
Argument Does not modify the arguments passed Can modify the state of received objects.
Modification to it.
Parameter Associated with "call by value" where Associated with "call by reference" where
Passing original variables are unaffected. changes to objects are reflected back to
the caller.
4. Invoking Methods and Passing Parameters
4.1. The Method Call Stack
When a method is called, the Java Virtual Machine (JVM) uses a call stack to manage execution. A new
"stack frame" is created and pushed onto the stack for each method call. This frame stores local
variables and the return address. When a method finishes, its frame is popped from the stack, and
control returns to the caller. This operates in a Last-In-First-Out (LIFO) manner.
4.2. Actual vs. Formal Parameters
● Formal Parameters: The variables declared in the method's signature. They act as placeholders
for the data the method will receive. They are also known as dummy parameters.
○ Example: In void sum(int a, int b), a and b are formal parameters.
● Actual Parameters: The actual values or variables passed to the method when it is invoked
(called).
○ Example: In sum(10, 20);, 10 and 20 are actual parameters.
4.3. Parameter Passing Techniques
Java is strictly Pass by Value (also called Call by Value). This means when a method is called, a copy of
the actual parameter's value is passed to the formal parameter.
● For Primitive Types (int, double, etc.): A copy of the value is made. Any changes made to
the formal parameter inside the method do not affect the original actual parameter in the calling
environment.
● For Reference Types (Objects, Arrays): The "value" being passed is the memory address
(reference) of the object. A copy of this reference is passed to the method.
○ Because the formal parameter now holds a reference to the same object, any changes
made to the object's state (e.g., modifying an array element or an object's instance
variable) will be reflected in the original object.
○ This behavior is often confused with "Call by Reference," but it is technically a
pass-by-value of the reference itself. The formal parameter cannot be reassigned to a
new object to affect the original actual parameter.
5. Method Overloading: A Form of Polymorphism
Method overloading is a powerful feature of object-oriented programming that implements
polymorphism. It allows a class to have multiple methods with the same name, provided their
parameter lists are different.
The compiler distinguishes between overloaded methods based on their signatures. The differentiation
can occur in three ways:
1. Different Number of Parameters:
○ void display(int a)
○ void display(int a, int b)
2. Different Types of Parameters:
○ void volume(int side)
○ void volume(double radius)
3. Different Order (Arrangement) of Parameter Types:
○ void calculate(int length, double height)
○ void calculate(double height, int length)
Note: Overloading cannot be achieved by changing only the return type of the method. The name and
parameter list must differ.
The primary advantage of method overloading is that programmers do not need to create and remember
many different names for functions that perform similar tasks on different types or quantities of data.