0% found this document useful (0 votes)
30 views

Lecture 13 - Methods

Uploaded by

devmith2005
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)
30 views

Lecture 13 - Methods

Uploaded by

devmith2005
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
You are on page 1/ 27

Object Oriented

Programming

Lecture 13
Methods
Method?
• A method is a block of code or collection of statements or a set of code grouped
together to perform a certain task or operation.
• It is used to achieve the reusability of code.
• Write a method once and use it many times.
• No need to write code again and again.
• It also provides the easy modification and readability of code, just by adding or
removing a chunk of code.
• The method is executed only when we call or invoke it.

• The most important method in Java is the main() method.


Java main() Method
• The main() is the starting point for JVM to start execution of a Java program.
• Without the main() method, JVM will not execute the program.
• The syntax of the main() method is:
• public
o It is an access specifier.
o Should use a public keyword before the main() method so that JVM can
identify the execution point of the program.
o If we use private, protected, and default before the main() method, it will not
be visible to JVM.
• static
o Can make a method static by using the keyword static.
o Should call the main() method without creating an object.
o Static methods are the method which invokes without creating the objects.
• void
o In Java, every method has the return type.
o Void keyword acknowledges the compiler that main() method does not return
any value.
• main()
o It is a default signature which is predefined in the JVM.
o It is called by JVM to execute a program line by line and end the execution after
completion of this method.
o Can also overload the main() method.

• String args[]
o The main() method also accepts some data from the user.
o It accepts a group of strings, which is called a string array.
o It is used to hold the command line arguments in the form of string values.
• In Java, there are two types of methods:

o User-defined Methods: We can create our own method based on


our requirements.

o Standard Library Methods: These are built-in methods in Java that


are available to use.
Method
Declaration Syntax

• Declaring a Java Method


• The syntax to declare a method is:

returnType methodName() {
// method body
}
Method
Complete Declaration Syntax

modifier static returnType nameOfMethod (parameter1, parameter2, …)


{
// method body
}
• returnType
o It specifies what type of value a method returns.

o It is Mandatory in syntax.

o If the method does not return a value, its return type is void.

• methodName
o It is an identifier that is used to refer to the particular method in a program.

o It is Mandatory in syntax.

• method body
o It includes the programming statements that are used to perform some tasks.

o The method body is enclosed inside the curly braces { }.


• modifier
o It defines access types whether the method is public, private, and so on.

• static
o If we use the static keyword, it can be accessed without creating objects.

• parameter1/parameter2
o These are values passed to a method.

o Can pass any number of arguments to a method.


Access Modifier/ Visibility
• It defines the access type of the method i.e. from where it can be accessed in your
application.
• In Java, there are 4 types of access specifiers.
o public : It is accessible in all classes in your application.
o protected : It is accessible within the class in which it is defined and, in its
subclass/es
o private : It is accessible only within the class in which it is defined.
o default : It is declared/defined without using any modifier. It is accessible
within the same class and package within which its class is defined.
Naming a Method
• Method name must be a verb and start with a lowercase letter.
• If the method name has more than two words, the first name must be a verb
followed by an adjective or noun.
• In the multi-word method name, the first letter of each word must be in uppercase
except the first word.
o For example, findSum, computeMax, setX, and getX.
Creating a Method
Instance Method / Non-Static Method

1. Instance Method:
• Access the instance data using the object name.
• Declared inside a class.
• Before calling or invoking the instance method, it is necessary to create an object of its class.

Syntax:

void method_name(){
body // instance area
}
Creating a Method
Static Method

2. Static Method
• Access the static data using class name.
• Declared inside class with static keyword.

Syntax:

static void method_name(){


body // static area
}
Static
A method that belongs to a class rather than an instance of a class

• A method that has static keyword is known as static method.

• Main advantage: It can call it without creating an object.


• It can access static data members and change the value of it.
• It is used to create an instance method.
• It is invoked by using the class name.
• The best example of a static method is the main() method.
Method Signature
• It consists of the method name and a parameter list (number of parameters, type
of the parameters, and order of the parameters).
• The return type and exceptions are not considered as part of it.

public void square(int a) {


int square = a * a;
System.out.println("Square is: " + square);
}

Signature: square(int a)
Method
Calling a Method

• The method needs to be called for use its functionality.


• A method returns to the code that invoked it when:
o It completes all the statements in the method
o It reaches a return statement
o Throws an exception
public class ExampleMinNumber {

public static void main(String[] args) {


int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}

Ex: public static int minFunction(int n1, int n2) {


int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
}
public class ExampleMinNumber {

public static void main(String[] args) {


int a = 11;
int b = 6;

ExampleMinNumber ob = new ExampleMinNumber();

int c = ob. minFunction(a, b);


System.out.println("Minimum Value = " + c);
}

public int minFunction(int n1, int n2) {


int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
}
Standard Library Methods
• The standard library methods are built-in methods in Java that are readily available
for use.
• These standard libraries come along with the Java Class Library (JCL) in a Java
archive (*.jar) file with JVM and JRE.
Method Overloading
• With method overloading, multiple methods can have the same name with different
parameters:

• Examples:

int addition(int x)

float addition(float x)

double addition(double x, double y)


Why method overloading?
• Readability and Simplicity:
• Overloading allows using the same method name for logically related operations.
• Consistency:
• Maintains a consistent naming convention when similar operations are performed on
different data types or parameter combinations.
• Ease of Maintenance:
• Updates or improvements to a method can be done in one place, reducing the chance
of errors and simplifying maintenance.
• Avoiding Ambiguity:
• If you were to implement different methods with different names, it might lead to
ambiguity and confusion.
Method Scope • Example:
public class Main {
public static void main(String[] args) {
• Variables declared directly
inside a method are available // Code here CANNOT use x
anywhere in the method
int x = 100;
following the line of code in
which they were declared: // Code here can use x
System.out.println(x);
}

}
Advantages of Methods
• Modularity and Reusability:
o Methods promote code modularity by breaking down a program into smaller,
more manageable and reusable parts.
o This makes code maintenance and updates easier.
• Code Organization:
o Methods help in organizing code by encapsulating specific functionality.
o This enhances code readability and makes it easier to understand and maintain.
• Abstraction:
o Methods allow developers to abstract away the implementation details of a task,
providing a high-level view of functionality while hiding the underlying
complexity.
• Parameter Passing:
o Methods can accept parameters, allowing the passing of data and facilitating
customization of behavior.
o This makes methods versatile and adaptable to various scenarios.
• Code Debugging:
o Smaller methods are easier to debug than large, monolithic code blocks.
o Debugging can be more focused and efficient when dealing with well-defined
and isolated methods.
• Encapsulation:
o Methods encapsulate logic, variables, and operations within a defined scope.
o This helps in preventing unintended interference with other parts of the
program.
• Improved Readability:
o Well-named methods enhance code readability by providing clear and
meaningful names for specific tasks or operations.
• Code Maintenance:
o Methods make it easier to maintain and update code. Changes or
enhancements can be localized to specific methods, reducing the risk of
unintended side effects.
• Code Reusability:
o Once a method is written and tested, it can be reused in multiple parts of the
program or even in different projects, saving development time.
END

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy