DEV Community

R.Shobika CSE
R.Shobika CSE

Posted on

METHODS IN JAVA

METHODS:

  • Methods is a block of code

  • Methods is used for code reusability

  • Methods are used to perform certain actions, and they are also known as functions.

Why methods? ---> To Reduce the code

HOW TO DEFINED A METHOD?

class Calc{
public static void main (String[] args){
Calc casio = new Calc(); ----->object creation
casio.add()  ------> method calling
public void add(){    ---------> method define
int i=10;
int j=20;
int res=i+j;
System.out.println(res)  -------> method define
}
}
}
Enter fullscreen mode Exit fullscreen mode

output:
30
METHOD OVERLOADING:

Same method name but different type of arguments / different number of arguments is called method overloading

example:

class Calc{
public static void main (String[] args){
Calc casio = new Calc(); ----->object creation
casio.add(10,20);  ------> method calling
casio.add(10,20,30);  
public void add(int i,intj){    ---------> method define
int res=i+j;
System.out.println(res)  -------> method define
}
public void add(int i,intj,intk){    ---------> method define
int res=i+j+k;
System.out.println(res)  -------> method define
}
}
}
Enter fullscreen mode Exit fullscreen mode

output:
30
60

Return type:
Void ---> void does not return any value

public void add(){
---
---
}
Enter fullscreen mode Exit fullscreen mode

Primitive data type ---> It will return the value

public int add(){
----
----
}
Enter fullscreen mode Exit fullscreen mode

In Java System.out.println() ---> is also a method overloading

System.out.println(10);
System.out.println();
System.out.println(10.0);
System.out.println(True);
System.out.println("abc");

Enter fullscreen mode Exit fullscreen mode

Because it contain same method name but different type of argument

Method overloading is also called as compile- time polymorphism

Top comments (0)