Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Unit1_Method in Java

In Java, a method is a block of code that performs a specific task and promotes code reusability. Methods can be predefined or user-defined, with various components including method signature, access specifier, return type, method name, parameter list, and method body. Additionally, Java supports method overloading, allowing multiple methods with the same name but different parameters to enhance program readability.

Uploaded by

anuja.it
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Unit1_Method in Java

In Java, a method is a block of code that performs a specific task and promotes code reusability. Methods can be predefined or user-defined, with various components including method signature, access specifier, return type, method name, parameter list, and method body. Additionally, Java supports method overloading, allowing multiple methods with the same name but different parameters to enhance program readability.

Uploaded by

anuja.it
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Method in Java

In general, a method is a way to perform some task. Similarly, the method in Java is a collection of
instructions that performs a specific task. It provides the reusability of code. We can also easily modify
code using methods.

What is a method in Java?

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. We write a method once and use it
many times. We do not require to write code again and again. The method is executed only when we call
or invoke it..

Method Declaration

The method declaration provides information about method attributes, such as visibility, return-type,
name, and arguments. It has six components that are known as method header, as we have shown in the
following figure.

Method Signature: Every method has a method signature. It is a part of the method declaration. It
includes the method name and parameter list.

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:

o Public: The method is accessible by all classes when we use public specifier in our application.
o Private: When we use a private access specifier, the method is accessible only in the classes in
which it is defined.
o Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.
o Default: 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.

Return Type: Return type is a data type that the method returns. It may have a primitive data type.If the
method does not return anything, we use void keyword.

Method Name: It is a unique name that is used to define the name of a method. It must be corresponding
to the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers,
the method name must be subtraction(). A method is invoked by its name.

Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses.
It contains the data type and variable name. If the method has no parameter, left the parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is
enclosed within the pair of curly braces.

Types of Method

There are two types of methods in Java:

o Predefined Method
o User-defined Method

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 method. We can
directly use these methods just by calling them in the program at any point. Some pre-defined methods
are length(), equals(), compareTo(), sqrt(), etc. When we call any of the predefined methods in our
program, a series of codes related to the corresponding method runs in the background that is already
stored in the library.

Each and every predefined method is defined inside a class. Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.

Let's see an example of the predefined method.

Demo.java

1. public class Demo


2. {
3. public static void main(String[] args)
4. {
5. // using the max() method of Math class
6. System.out.print("The maximum number is: " + Math.max(9,7));
7. }
8. }
Output:

The maximum number is: 9

In the above example, we have used three predefined methods main(), print(), and max(). We have used
these methods directly without declaration because they are predefined. The max() method is a method of
the Math class that returns the greater of two numbers.

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.

How to Create a User-defined Method

import java.util.*;
class Addition
{ int a,b;
public void add(int a1,int b1)
{
a=a1;
b=b1;
int c=a +b;
System.out.println("c="+c);
}
public static void main(String args[])
{
Addition obj=new Addition();
obj.add(2,3);
}
}
Output:
C=5

In the following program, we have defined a method named add() that sum up the two numbers. It has
two parameters n1 and n2 of integer type. The values of n1 and n2 correspond to the value of a and b,
respectively. Therefore, the method adds the value of a and b and store it in the variable s and returns the
sum.

Addition.java

class Addition
{
public int add(int n1, int n2) //n1 and n2 are formal parameters
{
int s;
s=n1+n2;
return s; //returning the sum
}
public static void main(String[] args)
{
int a = 19;
int b = 5;
Addition obj=new Addition();
//method calling
int c = obj.add(a, b); //a and b are actual parameters
System.out.println("The sum of a and b is= " + c);
System.out.println("The sum of a and b is= "+obj.add(a,b));
}
//user defined method
}

Output:

The sum of a and b is= 24


The sum of a and b is= 24

Static Method

A method that has static keyword is known as static method. In other words, a method that belongs to
a class rather than an instance of a class is known as a static method. We can also create a static method
by using the keyword static before the method name.

The main advantage of a static method is that we can call it without creating an object . It can access static
data members and also 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.

Example of static method

Display.java

class Display
{
static void show()
{
System.out.println("It is an example of static method.");
}
public static void main(String[] args)
{
show();
}
}

Output:

It is an example of a static method.

Abstract Method(will be explained in unit2)

The method that does not has method body is known as abstract method. In other words, without an
implementation is known as abstract method. It always declares in the abstract class. It means the class
itself must be abstract if it has abstract method. To create an abstract method, we use the
keyword abstract.

Syntax

1. abstract void method_name();

Example of abstract method

Demo.java

1. abstract class Demo //abstract class


2. {
3. //abstract method declaration
4. abstract void display();
5. }
6. public class MyClass extends Demo
7. {
8. //method impelmentation
9. void display()
10. {
11. System.out.println("Abstract method?");
12. }
13. public static void main(String args[])
14. {
15. //creating object of abstract class
16. Demo obj = new MyClass();
17. //invoking abstract method
18. obj.display();
19. }
20. }

Output:

Abstract method...

Method Overloading in Java

1. Different ways to overload the method


2. By changing the no. of arguments
3. By changing the datatype
4. Why method overloading is not possible by changing the return type
5. Can we overload the main method
6. method overloading with Type Promotion

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.

Suppose you have to perform addition of the given numbers but there can be any number of arguments, if
you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it
may be difficult for you as well as other programmers to understand the behavior of the method because
its name differs.

So, we perform method overloading to figure out the program quickly.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

In Java, Method Overloading is not possible by changing the return type of the method only.

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 Addition
{
void add(int a,int b)
{
System.out.println("sum of a and b is "+(a+b));

}
void add(int a,int b,int c)
{
System.out.println("sum of a and b is "+(a+b+c));

}
public static void main(String[] args)
{

Addition obj=new Addition();


obj.add(2,3);
obj.add(3,4);
}

} Test it Now

Output:

sum of a and b is 5
sum of a and b is7b is 7

2) Method Overloading: changing data type of arguments

class Addition
{
void add(int a,int b)
{
System.out.println("sum of a and b is "+(a+b));

}
void add(double a,double b)
{
System.out.println("sum of a and b is "+(a+b));
}
public static void main(String[] args)
{
Addition obj=new Addition();
obj.add(2,3);
obj.add(3.4,4.2);
}
} Test it NowOutput:
sum of a and b is 5
sum of a and b is 7.6

You might also like