Methods in Java - GeeksforGeeks

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

2/23/22, 8:15 PM Methods in Java - GeeksforGeeks

Data Structures Algorithms Interview Preparation Topic-wise Practice C++ Java Python Competitive Programming Machine Learnin

Methods in Java
Difficulty Level :
Easy ● Last Updated :
09 Feb, 2022

A method in Java or Java Method is a collection of statement s that per form some specific task and return the result

to the caller. A Java method can per form some specific task without returning anything. Methods in Java allow us to

reuse the code without ret yping the code. In Java, ever y method must be par t of some class that is dif ferent from

languages like C, C++, and P ython. 

Note : Methods are time savers and help us to reuse the code without retyping the code. 

Method Declaration

In general, method declarations has six component s :  

1. Modifier: It defines the access t ype of the method i.e. from where it can be accessed in your application. In Java,

We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and Got It !
there 4 t ypes of access specifiers. 
understood our
Cookie Policy &
Privacy Policy

https://www.geeksforgeeks.org/methods-in-java/ 1/14
2/23/22, 8:15 PM Methods in Java - GeeksforGeeks

public : It is accessible in all classes in your application.

protec ted: It is accessible within the class in which it is defined and in it s subclass/es

Start Your Coding Journey Now!


private : It is accessible only within the class in which it is defined.
Login Register
default : It is declared/defined without using any modifier. It is accessible within the same class and package

within which it s class is defined.

2. The return t ype : The data t ype of the value returned by the method or void if does not return a value.

3. Method Name : the rules for field names apply to method names as well, but the convention is a little dif ferent.

4. Parameter list : Comma-separated list of the input parameters is defined, preceded with their data t ype, within

the enclosed parenthesis. If there are no parameters, you must use empt y parentheses ().

5. Exception list : The exceptions you expect by the method can throw, you can specif y these exception(s).

6. Method body: it is enclosed between braces. The code you need to be executed to per form your intended

operations.

We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and
Got It !
understood our
Cookie Policy &
Privacy Policy

https://www.geeksforgeeks.org/methods-in-java/ 2/14
2/23/22, 8:15 PM Methods in Java - GeeksforGeeks

Start Your Coding Journey Now! Login Register

Types of Methods in Java

There are two t ypes of methods in Java:

1. Predefined Method: In Java, predefined methods are the method that is already defined in the Java class libraries

is known as predefined methods. It is also known as the standard librar y method or built-in method. We can

directly use these methods just by calling them in the program at any point. 

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

methods are modified according to the requirement.

Method Signature

We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and
Got It !
understood our
Cookie Policy &
Privacy Policy

https://www.geeksforgeeks.org/methods-in-java/ 3/14
2/23/22, 8:15 PM Methods in Java - GeeksforGeeks

It consist s of the method name and a parameter list (number of parameters, t ype of the parameters, and order of the

Start Your Coding Journey Now!


parameters). The return t ype and exceptions are not considered as par t of it. 

Login Register
Method Signature of above function:  

max(int x, int y) Number of parameters is 2, Type of parameter is int.

How to Name a Method?

A method name is t ypically a single word that should be a verb in lowercase or multi-word, that begins with a verb

in lowercase followed by an adjec tive, noun….. Af ter the first word, the first letter of each word should be

capitalized. 

Rules to Name a Method

While defining a method, remember that the method name must be a verb and star t with a lowercase letter. 

If the method name has more than two words, the first name must be a verb followed by an adjective or noun. 

In the multi-word method name, the first letter of each word must be in uppercase except the first word. For

example, findSum, computeMax, setX and getX.

Generally, a method has a unique name within the class in which it is defined but sometimes a method might have

the same name as other method names within the same class as method overloading is allowed in Java.

Method Calling

The method needs to be called for using it s functionalit y. There can be three situations when a method is called: 

We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and
Got It !
understood our
Cookie Policy &
Privacy Policy
A method returns to the code that invoked it when:  

https://www.geeksforgeeks.org/methods-in-java/ 4/14
2/23/22, 8:15 PM Methods in Java - GeeksforGeeks

It completes all the statement s in the method

It reaches a return statement

Start Your Coding Journey Now!


Throws an exception
Login Register

Example :

Java

// Java Program to Illustrate Methods


  
// Importing required classes
import java.io.*;
  
// Class 1
// Helper class
class Addition {
  
    // Initially taking sum as 0
    // as we have not started computation
    int sum = 0;
  
    // Method
    // To add two numbers
    public int addTwoInt(int a, int b)
    {
  
        // Adding two integer value
        sum = a + b;
  
        // Returning summation of two values
        return sum;
    }
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and Got It !
} understood our
Cookie Policy &
Privacy Policy

https://www.geeksforgeeks.org/methods-in-java/ 5/14
2/23/22, 8:15 PM Methods in Java - GeeksforGeeks

  
// Class 2
// Helper class
class GFG { Start Your Coding Journey Now! Login Register
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // Creating object of class 1 inside main() method
        Addition add = new Addition();
  
        // Calling method of above class
        // to add two integer
        // using instance created
        int s = add.addTwoInt(1, 2);
  
        // Printing the sum of two numbers
        System.out.println("Sum of two integer values :"
                           + s);
    }
}

Output

Sum of two integer values :3

Example 2:

Java

We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and Got It !
understood our
Cookie Policy &
Privacy Policy
// Java Program to Illustrate Method Calling 
https://www.geeksforgeeks.org/methods-in-java/ 6/14
2/23/22, 8:15 PM Methods in Java - GeeksforGeeks

// Via Different Ways of Calling a Method


  
// Importing required classes
import java.io.*;Start Your Coding Journey Now! Login Register
  
// Class 1
// Helper class
class Test {
  
    public static int i = 0;
  
    // Constructor of class
    Test()
    {
  
        // Counts the number of the objects of the class
        i++;
    }
  
    // Method 1
    // To access static members of the class and
    // and for getting total no of objects
    // of the same class created so far
    public static int get()
    {
  
        // statements to be executed....
        return i;
    }
  
    // Method 2
    // Instance method calling object directly
    // that is created inside another class 'GFG'.
  
    //
We use cookies to ensureCan alsothebe
you have bestcalled
browsing by object
experience directly
on our created
website. By in you
acknowledge
using our site, the that you have read and Got It !
    // same class and understood our
Cookie
from another Policy &
Privacy
method defined Policy
in the

https://www.geeksforgeeks.org/methods-in-java/ 7/14
2/23/22, 8:15 PM Methods in Java - GeeksforGeeks

    // same class and return integer value as return type is


    // int.
    public int m1()
    { Start Your Coding Journey Now! Login Register
  
        // Display message only
        System.out.println(
            "Inside the method m1 by object of GFG class");
  
        // Calling m2() method within the same class.
        this.m2();
  
        // Statements to be executed if any
        return 1;
    }
  
    // Method 3
    // Returns nothing
    public void m2()
    {
  
        // Print statement
        System.out.println(
            "In method m2 came from method m1");
    }
}
  
// Class 2
// Main class
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and
We use cookies Got It !
        // Creating object understood
of our
Cookie Policy &
Privacy
above class insidePolicy
thi class

https://www.geeksforgeeks.org/methods-in-java/ 8/14
2/23/22, 8:15 PM Methods in Java - GeeksforGeeks

        Test obj = new Test();


  
        // Calling method 2 inside main() method
Start Your Coding Journey Now!
        int i = obj.m1(); Login Register
  
        // Display message only
        System.out.println(
            "Control returned after method m1 :" + i);
  
        // Call m2() method
        // obj.m2();
        int no_of_objects = Test.get();
  
        // Print statement
        System.out.print(
            "No of instances created till now : ");
        
        System.out.println(no_of_objects);
    }
}

Output

Inside the method m1 by object of GFG class

In method m2 came from method m1

Control returned after method m1 :1

No of instances created till now : 1

The control flow of the above program is as follows:

We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and Got It !
understood our
Cookie Policy &
Privacy Policy

https://www.geeksforgeeks.org/methods-in-java/ 9/14
2/23/22, 8:15 PM Methods in Java - GeeksforGeeks

Start Your Coding Journey Now! Login Register

Memor y Allocation for Methods Calls

Methods calls are implemented through a stack. Whenever a method is called a stack frame is created within the

stack area and af ter that, the argument s passed to and the local variables and value to be returned by this called

method are stored in this stack frame and when execution of the called method is finished, the allocated stack frame

would be deleted. There is a stack pointer register that track s the top of the stack which is adjusted accordingly.

Related Ar ticles :  

Java is Strictly Passed B y Value

Method Overloading and Null Error in Java

Can we overload or override static methods in Java?

Java Quizzes

This ar ticle is contributed by Nitsdheerendra. If you like Geek sforGeek s and would like to contribute, you can also
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and Got It !
understood our
Cookie Policy &
Privacy Policy
write an ar ticle using write.geek sforgeek s.org or mail your ar ticle to review-team@geek sforgeek s.org. See your

https://www.geeksforgeeks.org/methods-in-java/ 10/14
2/23/22, 8:15 PM Methods in Java - GeeksforGeeks

ar ticle appearing on the Geek sforGeek s main page and help other Geek s. Please write comment s if you find

Start Your Coding Journey Now!


anything incorrect, or you want to share more information about the topic discussed above.

Login Register

Like 105

Previous Next

Classes and Objects in Java Access Modifiers in Java

We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and
Got It !
understood our
Cookie Policy &
Privacy Policy

https://www.geeksforgeeks.org/methods-in-java/ 11/14
2/23/22, 8:15 PM Methods in Java - GeeksforGeeks

RECOMMENDED ARTICLES Page : 1 2 3


Start Your Coding Journey Now! Login Register

Static methods vs Instance methods in Java Private and final methods in Java
01 09, Dec 16
05 21, Dec 12

Java.util.BitSet class methods in Java with Can we Overload or Override static methods
02 06
Examples | Set 2 in java ?
18, Nov 16 23, Jun 13

Java.io.BufferedWriter class methods in Java Can we override private methods in Java?


03 29, Dec 16
07 10, Sep 13

java.lang.Character class methods | Set 1 Java Interface methods


04 29, Nov 16
08 19, Apr 16

Ar ticle Contributed By : Vote for difficulty

Current difficulty :
Easy

GeeksforGeeks
Easy Normal Medium Hard Expert

We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and Got It !
understood our
Cookie Policy &
Privacy Policy

https://www.geeksforgeeks.org/methods-in-java/ 12/14
2/23/22, 8:15 PM Methods in Java - GeeksforGeeks

Improved By : Akanksha_Rai, sg4ipiafwot258z3lh6xa2mjq2qtxd89f49zgt7g, amartajisce, nishkarshgandhi


Article Tags : Java
Start Your Coding Journey Now! Login Register
Practice Tags : Java

Improve Article Report Issue

Writing code in comment?


Please use ide.geeksforgeeks.org,
generate link and share the link here.

Load Comments

5th Floor, A-118,

Sector-136, Noida, Uttar Pradesh - 201305

feedback@geeksforgeeks.org

Company Learn Web Development


We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and ContributeGot It !
understood our
Cookie Policy &
Privacy Policy

https://www.geeksforgeeks.org/methods-in-java/ 13/14
2/23/22, 8:15 PM Methods in Java - GeeksforGeeks

About Us Algorithms Web Tutorials Write an Article


Careers Data Structures HTML Write Interview Experience
Privacy Policy
Start Your Coding Journey Now! CSS
Languages
Login Register
Internships
Contact Us CS Subjects JavaScript Videos
Copyright Policy Video Tutorials Bootstrap

@geeksforgeeks
, Some rights reserved

We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and Got It !
understood our
Cookie Policy &
Privacy Policy

https://www.geeksforgeeks.org/methods-in-java/ 14/14

You might also like