Methods and Overloading methods

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.
  • How to create 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.
Types of Methods:
  • Static method
  • Non-static method
Static method
Syntax:

static return_type method_name()
{
Statements;
}
  • The void keyword, used in the above syntax, indicates that the method should not return a value.
  • If you want the method to return a value, you can use a primitive data type (such as int, char, etc.) instead of void, and use the return keyword inside the method.
How to call static method?
Syntax (in same class):
methodname(argument);

Syntax (in other class):
class_name.methodname(arguments);

Full Example:
public class MyClass {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}

Non-static methods:
Without arguments
  • Syntax:
modifier return_type method_name()
{
Statments;
}
  • Example:
public void sum()
{
System.out.println("sum() method");
}

With arguments:
  • When a parameter is passed to the method, it is called an argument.
  • Information can be passed to methods as a parameter.
  • Parameters act as variables inside the method.
  • Parameters are specified after the method name, inside the parentheses.
  • You can add as many parameters as you want, just separate them with a comma.
  • Syntax:
modifier return_type method_name(argument)
{
Statements;
}
  • Example:
public void sum(int x, int y)
{
System.out.println(x+y);
}

How to call non-static method?
  • To call a method in Java, write the method's name followed by two parentheses () and a semicolon.

Method Overloading in Java
  • If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
  • Example:
  • Addition for two numbers.
public int sum(int x, int y)
{
return (x + y);
}
  • Addition for three numbers.
public int sum(int x, int y, int z)
{
return (x + y + z);
}
  • Advantage:
    • Method overloading increases the readability of the program.
    • Different ways to overload the method
      • By changing the number of arguments
      • By changing the data type
1. Changing no. of arguments

2. Changing data type of arguments

Thanks a lot for query or your valuable suggestions related to the topic.

Previous Post Next Post

Contact Form