Java Methods

Java Method is a block of code or a collection of statements that performs a specific task. It provides the reusability of code.

Java methods are declared within a class.

You can create your own methods with or without return values, invoke a method with or without parameters, and apply method abstraction in the program.

Java provices in-built the main() method where java control starts execution of java code.

We can write a method once and use it many times. We do not require to write code again and again. It also provides the easy modification and readability of code

 

How to create method in java class?

Syntax:
 

modifier returnType nameOfMethod (Parameter List) {
   // body
}

public static int methodName(int x, int y) {
   // body
}

   Here, 

    public − Access modifier.
    
    static - We created a static method which means that it can be accessed without creating an object of the class.

    int − return type.

    methodName − name of the method.

    int x, int y − list of parameters with data type.

 

There are two types of methods in Java as below.

1. Predefined Method - The method is already defined in the Java class libraries is known as predefined methods in java. It is also known as the standard library method or built-in method.  Example : print(), main() etc.

Example,

public class Aryatechno   
{  
    public static void main(String[] args)   
    {  
 
        System.out.print("Learn java tutorials! ");  
    }  
}  

2. User-defined Method -The method written by the user or programmer is known as a user-defined method. 

Example ,

public class Aryatechno {
  static void demoMethod() {
    System.out.println("Hello World!");
  }
}

As per as above example, we have created demoMethod method in Aryatechno class. A demoMethod method displays 'Hello World!' message. This method return void datatype value.

 

 

 

Example :

public class Aryatechno {

public static void main(String[] args) {
int x = 19;
int y = 5;
int z = addFunction(x, y);
System.out.println("Addition Value : " + z);
}

/** returns the sum of two numbers */
public static int addFunction(int num1, int num2) {
int result;

result = num1 + num2;

return result;
}
}

Output :

Addition Value : 24

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

79545