DEV Community

Ezhil Abinaya K
Ezhil Abinaya K

Posted on

Methods in Java

Methods
A method is a block of code which only runs when it is called.You can pass data, known as parameters, into a method.Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can also create your own methods to perform certain actions.

//Create a method inside Main://

public class Geeks
{
    // An example method
    public void printMessage() {
        System.out.println("Hello, Geeks!");
    }

    public static void main(String[] args) {

        // Create an instance of the class
        // containing the method
        Geeks obj = new Geeks();

        // Calling the method
        obj.printMessage(); 
    }
}
O/P:
Hello, Geeks!
Enter fullscreen mode Exit fullscreen mode

Syntax of Java Methods

returnType methodName(parameters) {
  // method body
 return value; // optional (only if returnType is not void)
}
Enter fullscreen mode Exit fullscreen mode

Method Overloading
Same method name with different number of arguments or with diiferent type of arguments are called method overloading or compile time polymorphism.

public class Supermarket
{
//fields
static String supermarketname="D-Mart";
static int supermarketdoorno=13/1;
//non-static variables
String things;
int price;
int discount;
public Supermarket(String things,int price){
this.things=things;
this.price=price;
}
public Supermarket(String things,int price,int discount){
this.things=things;
this.price=price;
this.discount=discount;
}
public static void main(String[] args)
{
//object
Supermarket things1=new Supermarket("Rosemilk",30);
Supermarket things2=new Supermarket("Galaxychocky",50);
Supermarket things3=new Supermarket("Kinderjoy",50,20);
things1.buy();
things1.buy(10);
 System.out.println(Supermarket.supermarketname);
 System.out.println(Supermarket.supermarketdoorno);
 System.out.println(things1.things);
 System.out.println("₹" + things1.price);
 System.out.println(things2.things);
 System.out.println("₹" + things2.price);
 System.out.println(things3.things);
 System.out.println("₹" + things3.price);
  System.out.println(things3.discount + "%" );
 }
 //method overloading
 public void buy(){
 System.out.println("buy-method");
 }
 public void buy(int account){
 System.out.println("buy-method-one-argument");
 }
}
o/p:
buy-method
buy-method-one-argument
D-Mart
13
Rosemilk
30
Galaxychocky
50
Kinderjoy
50
20%

Enter fullscreen mode Exit fullscreen mode

References
https://www.w3schools.com/java/java_methods.asp
https://www.geeksforgeeks.org/java/methods-in-java/

Top comments (0)