0% found this document useful (0 votes)
6 views23 pages

Lecture 4 - Methods

The document explains methods in Java, detailing their purpose, syntax, types, and access specifiers. It covers instance and static methods, method overloading, and the stack mechanism during method execution. Additionally, it distinguishes between predefined and user-defined methods, providing examples for clarity.

Uploaded by

akshatshukla1448
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)
6 views23 pages

Lecture 4 - Methods

The document explains methods in Java, detailing their purpose, syntax, types, and access specifiers. It covers instance and static methods, method overloading, and the stack mechanism during method execution. Additionally, it distinguishes between predefined and user-defined methods, providing examples for clarity.

Uploaded by

akshatshukla1448
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

Methods (behaviors):-

▪ Methods are used to provide the business logic of the project.


▪ The methods like a functions in C-language called functions, in java language is called
methods.
▪ Inside the class it is possible to declare any number of methods based on the developer
requirement.
▪ As a software developer while writing method we have to follow the coding standards like
the method name starts with lower case letters if the method contains two words every
inner word also starts uppercase letter.
▪ It will improve the reusability of the code. By using methods, we can optimize the code.
Syntax:-
[modifiers-list] return-Type Method-name (parameter-list)
Ex:-
public void m1()
public void m2(int a, int b)

Method Signature:-
The name of the method and parameter list is called Method Signature. Return type
and modifiers list not part of a method signature.
Ex:- m2(int ,int )------Method Signature
m1();------------------Method signature
Access Specifier: Access specifier or modifier is the access type of the method.
It specifies the visibility of the method. Java provides four types of access
specifier:
❑ Public: The method is accessible by all classes when we use public specifier
in our application.
❑ Private: When we use a private access specifier, the method is accessible
only in the classes in which it is defined.
❑ Protected: When we use protected access specifier, the method is accessible
within the same package or subclasses in a different package.
❑ Package-access: When we do not use any access specifier in the method
declaration, Java uses default access specifier by default. It is visible only
from the same package only. No special keyword is required.
Types of Methods
There are two types of methods:-
Instance method
Static method
Ex :- instance methods without arguments.
class Test{
void m1() {
[Link](“java");
}
void m2() {
[Link](“programming");
}
public static void main(String[] args) {
Test t=new Test();
t.m1();
t.m2();
}
}
Ex:-instance methods with parameters.
class Test
{
void m1(int i,char ch)
{
[Link](i+"-------"+ch);
}
void m2(float f,String str)
{ instance methods
[Link](f+"------"+str);
}
public static void main(String[] args)
{
[Link]("program statrs ");
Test t=new Test();
t.m1(10,'a');
t.m2(10.2f,“java");
}
}
There are two types of instance method:
•Accessor Method
•Mutator Method
Accessor Method: The method(s) that reads the instance variable(s) is known as the
accessor method.
We can easily identify it because the method is prefixed with the word get. It is also
known as getters. It returns the value of the private field. It is used to get the value of
the private field.
Example:
public int getId()
{
return Id;
}
Mutator Method: The method(s) read the instance variable(s) and also modify the
values. We can easily identify it because the method is prefixed with the word set. I
t is also known as setters or modifiers. It does not return anything. It accepts a
parameter of the same data type that depends on the field. It is used to set the value of
the private field.
Example:
public void setRoll(int roll)
{
[Link] = roll;
}
Example of accessor and mutator method
public class Student public String getName()
{ {
return name;
private int roll; }
private String name; public void setName(String name)
public int getRoll() //accessor method
{
[Link] = name;
{ }
return roll; public void display()
{
}
[Link]("Roll no.: "+roll);
public void setRoll(int roll) //mutator method [Link]("Student name: "+na
{ me);
} }
[Link] = roll;
}
Ex :- static methods without parameters.
class Test
{
static void m1()
{
[Link](“java");
}
static void m2()
{
[Link](“programming");
}
public static void main(String[] args)
{
m1()
m2()
}
}
Ex:-static methods with parameters
class Test
{
static void m1(int i,char ch)
{
[Link](i+"-------"+ch);
}
static methods
static void m2(float f,String str)
{
[Link](f+"------"+str);
}
public static void main(String[] args)
{
m1(10,'a');
m2(10.2f,"ratna");
}
}
Ex :-while calling methods it is possible to provide the variables as a parameter
values to the methods.
public static void main(String[] args)
class Test {
{ int a=10;
void m1(int a,int b) int b=20;
{ boolean c=true;
[Link](a); Test t=new Test();
[Link](b); t.m1(a,b);
} t.m2(c);
void m2(boolean c) }
{ }
[Link](c);
}
Ex:-calling of methods

m1()--→calling --→m2()----→calling------→ m3()


m1()<-------after completion-m2()<------after
completion m3()

class Test { void m3(int a)


void m1() {
{ [Link](a);
m2(); [Link]("m3");
[Link]("m1"); }
} public static void main(String[] args)
void m2() {
{ Test t=new Test();
m3(100); t.m1();
[Link]("m2"); }
m3(200); }
}
Method Overloading in Java

• If a class has multiple methods having same name but different in parameters,
it is known as Method Overloading.

• If we have to perform only one operation, having same name of the methods
increases the readability of the program.

• There are two ways to overload the method in java-


1. By changing number of arguments
2. By changing the data type
1) Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
class Adder{
static int add(int a,int b){
return a+b;
}
static int add(int a,int b,int c){
return a+b+c;
}
}
class TestOverloading1{
public static void main(String[] args){ Output:
[Link]([Link](11,11)); 22
[Link]([Link](11,11,11)); 33
}
}
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
class Adder{
static int add(int a, int b){
return a+b;
}
static double add(double a, double b){
return a+b;
}
}
class TestOverloading2{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](12.3,12.6)); Output:
} 22
}
24.9
Stack Mechanism:-

❑ Whenever we are executing the program stack memory is created.

❑ Each and every method is called by JVM that method entries are stored in the
stack memory and whatever the variables which are available within the
method that variables are stored in the stack.

❑ If the method is completed the entry is automatically deleted from the stack
means that variables are automatically deleted from the stack.

❑ Based on the 1 & 2 points the local variables scope is only within the method.
Ex :-
class Test{
void deposit(int accno) {
[Link]("money is deposited into "+accno);
}
void withdraw(float amount){
[Link]("money withdraw is over amount "+amount);
}
public static void main(String[] args) {
Test t=new Test();
[Link](111);
[Link](10000);
}
}
Step 1:- An empty stack is created

Step 2:- Once the JVM calls the main method, its entry is stored in the stack memory. The stored entry is
deleted as and when the main method is completed.

Step 3:- Once the JVM is calls the deposit () the method entry is stored in the stack and local variables
are store in the stack. The local variables are deleted whenever the JVM completes the deposit () method
execution. Hence the local variables scope is only within the method.

Step 4 :- The deposit() method is completed, then deposit () method is deleted from the stack.

Step 5 :- Only main method call is present in the stack.

Step 6:- Once the JVM calls the withdraw() method, the entry is stored in the stack.

Step 7:- The withdraw() method is completed, the entry is deleted from the stack.

Step 8:- Once the main() method is completed, the main() method is deleted from the stack.

Step 9:- the empty stack is deleted from the memory.


Ex :-we are getting StackOverFlowError
class Test{
void m1() {
[Link]("rattaiah");
m2();
}
void m2(){
[Link]("durga");
m1();
}
public static void main(String[] args) {
Test t=new Test();
t.m1();
}
}
Predefined Method
❑ In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods.

❑ It is also known as the standard library method or built-in [Link] pre-defined


methods are length(), equals(), compareTo(), sqrt(), etc.

❑ Each and every predefined method is defined inside a class. Such as print() method is
defined in the [Link] class.
User-defined Method
❑ The method written by the user or programmer is known as a user-defined method.

❑ These methods are modified according to the requirement.

You might also like