We Offer 100% Job Guarantee Courses (Any Degree / Diploma Candidates / Year GAP / Non-IT / Any Passed Outs). Placement Records
Hire Talent (HR):+91-9707 240 250

General

Methods in Java

Methods in Java

Java Methods:

A method is a set of instruction or code that is used to perform a particular task. It is will execute the code when it is called or invoked.

There are two types Methods:

  • Standard  Library Methods
  • User-defined Methods

Standard  Library Methods

It is build-in function in java that are readily available for use.

Example:

Print() – it is show the sentences or string value.
Sqrt() - is a method of  Math class. It returns square root of a number.
public class Numbers {
    public static void main(String[] args) {
        System.out.print("Square root of 9 is: " + Math.sqrt(9));
    }
}

Output:

Square root of 9 is: 3.0

Click Here-> Get Prepared for  Java Interviews

User-defined Methods

There are three stages for Methods:
  • Method declaration
  • Method definition
  • Method call or invoke

Method declaration

Syntax:

Modifier return-type Method-name (Parameter List)

Example:

Public void Swap(int a,int b);

Method definition

Public void Swap(int a,int b)
{
//Set of code for achieve the task
}

Method call or invoke

Syntax:

Method-name(Parameter-list);

Example:

Swap(34,56);

Function categories

There are four major categories of function. They are

Function with argument and with return type

Example:

Public int  Add(int a,int b);

Function without argument and with return type

Example:

Public int  Add();

Function with argument and without return type

Example:

Public void Add(int a,int b);

Function without argument and without return type

Syntax:

Public void  Add();

Example:

class Swap
{
public static void main(String[] args)
{
swapNumber(20,30); //Function calling
swapNumber(200,340);
}
public static void swapNumber(int a,int b) //Function Definiton
{
System.out.println("Before Swapping");
System.out.println("a="+a+"\n"+"b="+b);
int temp;
temp=a;
a=b;
b=temp;
System.out.println("After Swapping");
System.out.println("a="+a+"\n"+"b="+b);
}
}

Click Here-> Get Java Training with Real-time Projects

Besant Technologies WhatsApp