Methods Lecture
Methods Lecture
Introduction to Methods
Methods are blocks of code designed to perform a specific task in a Java program. They help improve
code reusability, readability, and maintainability by encapsulating behavior within a named unit that
can be invoked multiple times.
A method in Java consists of a declaration (or signature) and a body. The declaration includes the
method name, return type, and parameters (if any), while the body contains the code to be executed
when the method is called.
Syntax of a Method
returnType methodName(parameters)
{
// Method body
}
returnType: The data type of the value the method returns. Use void if no value is returned.
methodName: A descriptive name that follows Java naming conventions.
parameters: Input values that the method can accept (optional).
Method body: The code to be executed when the method is called.
Example:
public int addNumbers(int a, int b)
{
return a + b;
}
Example:
int number = 9;
double result = Math.sqrt(number);
System.out.println("Square root: " + result);
2. User-Defined Methods
These are methods created by the programmer to perform specific tasks. They can be further classified
into several types based on their functionality and return type.
Example:
public void displayMessage()
{
System.out.println("Hello, World!");
}
Example:
public void greetUser(String name)
{
System.out.println("Hello, " + name);
}
3. Methods with No Parameters but a Return Value
These methods do not accept any input parameters but return a value to the caller.
Syntax:
returnType methodName()
{
// Code to execute
return value;
}
Example:
public int getNumber()
{
return 42;
}
Example:
public int addNumbers(int a, int b)
{
return a + b;
}
Usage:
ClassName.printMessage();
2. Instance Methods
Belong to an instance of a class.
Require creating an object of the class to be invoked.
Example:
public void showDetails()
{
System.out.println("This is an instance method.");
}
Usage:
ClassName obj = new ClassName();
obj.showDetails();
3. Constructor Methods
Special methods that are called when an object is instantiated.
Have the same name as the class and no return type.
Example:
public class Person
{
public Person()
{
System.out.println("Person object created.");
}
}
Usage:
Person person1 = new Person();
Method Overloading
Method overloading allows multiple methods to have the same name but with different parameter lists.
Example:
public int add(int a, int b)
{
return a + b;
}
Conclusion
Methods are essential building blocks in Java programming. They improve code structure, reusability,
and maintainability. Understanding the different types of methods and how to use them effectively is
crucial for writing clean, efficient Java programs.