Learn Java practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn java interactively, java introduction.

  • Java Hello World
  • Java JVM, JRE and JDK
  • Java Variables and Literals
  • Java Data Types
  • Java Operators
  • Java Input and Output
  • Java Expressions & Blocks
  • Java Comment

Java Flow Control

  • Java if...else
  • Java switch Statement
  • Java for Loop
  • Java for-each Loop
  • Java while Loop
  • Java break Statement
  • Java continue Statement
  • Java Arrays
  • Multidimensional Array
  • Java Copy Array

Java OOP (I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructor
  • Java Strings
  • Java Access Modifiers
  • Java this keyword
  • Java final keyword
  • Java Recursion
  • Java instanceof Operator

Java OOP (II)

  • Java Inheritance
  • Java Method Overriding
  • Java super Keyword
  • Abstract Class & Method
  • Java Interfaces
  • Java Polymorphism
  • Java Encapsulation

Java OOP (III)

  • Nested & Inner Class
  • Java Static Class
  • Java Anonymous Class
  • Java Singleton
  • Java enum Class
  • Java enum Constructor
  • Java enum String
  • Java Reflection
  • Java Exception Handling
  • Java Exceptions
  • Java try...catch
  • Java throw and throws
  • Java catch Multiple Exceptions
  • Java try-with-resources
  • Java Annotations
  • Java Annotation Types
  • Java Logging
  • Java Assertions
  • Java Collections Framework
  • Java Collection Interface
  • Java List Interface
  • Java ArrayList
  • Java Vector
  • Java Queue Interface
  • Java PriorityQueue
  • Java Deque Interface
  • Java LinkedList
  • Java ArrayDeque
  • Java BlockingQueue Interface
  • Java ArrayBlockingQueue
  • Java LinkedBlockingQueue
  • Java Map Interface
  • Java HashMap
  • Java LinkedHashMap
  • Java WeakHashMap
  • Java EnumMap
  • Java SortedMap Interface
  • Java NavigableMap Interface
  • Java TreeMap
  • Java ConcurrentMap Interface
  • Java ConcurrentHashMap
  • Java Set Interface
  • Java HashSet
  • Java EnumSet
  • Java LinkedhashSet
  • Java SortedSet Interface
  • Java NavigableSet Interface
  • Java TreeSet
  • Java Algorithms
  • Java Iterator
  • Java ListIterator
  • Java I/O Streams
  • Java InputStream
  • Java OutputStream
  • Java FileInputStream
  • Java FileOutputStream
  • Java ByteArrayInputStream
  • Java ByteArrayOutputStream
  • Java ObjectInputStream
  • Java ObjectOutputStream
  • Java BufferedInputStream
  • Java BufferedOutputStream
  • Java PrintStream

Java Reader/Writer

  • Java Reader
  • Java Writer
  • Java InputStreamReader
  • Java OutputStreamWriter
  • Java FileReader
  • Java FileWriter
  • Java BufferedReader
  • Java BufferedWriter
  • Java StringReader
  • Java StringWriter
  • Java PrintWriter

Additional Topics

  • Java Scanner Class
  • Java Type Casting
  • Java autoboxing and unboxing
  • Java Lambda Expression
  • Java Generics
  • Java File Class
  • Java Wrapper Class
  • Java Command Line Arguments

Java Tutorials

Java Math sqrt()

Java Math acos()

Java Math atan()

Java Math asin()

A method is a block of code that performs a specific task.

Suppose you need to create a program to create a circle and color it. You can create two methods to solve this problem:

  • a method to draw the circle
  • a method to color the circle

Dividing a complex problem into smaller chunks makes your program easy to understand and reusable.

In Java, there are two types of methods:

  • User-defined Methods : We can create our own method based on our requirements.
  • Standard Library Methods : These are built-in methods in Java that are available to use.

Let's first learn about user-defined methods.

  • Declaring a Java Method

The syntax to declare a method is:

  • returnType - It specifies what type of value a method returns For example if a method has an int return type then it returns an integer value. If the method does not return a value, its return type is void .
  • methodName - It is an identifier that is used to refer to the particular method in a program.
  • method body - It includes the programming statements that are used to perform some tasks. The method body is enclosed inside the curly braces { } .

For example,

In the above example, the name of the method is adddNumbers() . And, the return type is int . We will learn more about return types later in this tutorial.

This is the simple syntax of declaring a method. However, the complete syntax of declaring a method is

  • modifier - It defines access types whether the method is public, private, and so on. To learn more, visit Java Access Specifier .
  • static - If we use the static keyword, it can be accessed without creating objects. For example, the sqrt() method of standard Math class is static. Hence, we can directly call Math.sqrt() without creating an instance of Math class.
  • parameter1/parameter2 - These are values passed to a method. We can pass any number of arguments to a method.

Calling a Method in Java

In the above example, we have declared a method named addNumbers() . Now, to use the method, we need to call it.

Here's is how we can call the addNumbers() method.

Call a method in Java using the name the method followed by a parenthesis

Example 1: Java Methods

In the above example, we have created a method named addNumbers() . The method takes two parameters a and b . Notice the line,

Here, we have called the method by passing two arguments num1 and num2 . Since the method is returning some value, we have stored the value in the result variable.

Note : The method is not static. Hence, we are calling the method using the object of the class.

  • Java Method Return Type

A Java method may or may not return a value to the function call. We use the return statement to return any value. For example,

Here, we are returning the variable sum . Since the return type of the function is int . The sum variable should be of int type. Otherwise, it will generate an error.

Example 2: Method Return Type

In the above program, we have created a method named square() . The method takes a number as its parameter and returns the square of the number.

Here, we have mentioned the return type of the method as int . Hence, the method should always return an integer value.

Java method returns a value to the method call

Note : If the method does not return any value, we use the void keyword as the return type of the method. For example,

Method Parameters in Java

A method parameter is a value accepted by the method. As mentioned earlier, a method can also have any number of parameters. For example,

If a method is created with parameters, we need to pass the corresponding values while calling the method. For example,

Example 3: Method Parameters

Here, the parameter of the method is int . Hence, if we pass any other data type instead of int , the compiler will throw an error. It is because Java is a strongly typed language.

Note : The argument 24 passed to the display2() method during the method call is called the actual argument.

The parameter num accepted by the method definition is known as a formal argument. We need to specify the type of formal arguments. And, the type of actual arguments and formal arguments should always match.

  • Standard Library Methods

The standard library methods are built-in methods in Java that are readily available for use. These standard libraries come along with the Java Class Library (JCL) in a Java archive (*.jar) file with JVM and JRE.

  • print() is a method of java.io.PrintSteam . The print("...") method prints the string inside quotation marks.
  • sqrt() is a method of Math class. It returns the square root of a number.

Here's a working example:

Example 4: Java Standard Library Method

To learn more about standard library methods, visit Java Library Methods .

What are the advantages of using methods?

1. The main advantage is code reusability . We can write a method once, and use it multiple times. We do not have to rewrite the entire code each time. Think of it as, "write once, reuse multiple times".

Example 5: Java Method for Code Reusability

In the above program, we have created the method named getSquare() to calculate the square of a number. Here, the method is used to calculate the square of numbers less than 6 .

Hence, the same method is used again and again.

2. Methods make code more readable and easier to debug. Here, the getSquare() method keeps the code to compute the square in a block. Hence, makes it more readable.

Table of Contents

  • Calling a Java Method
  • Method Parameters
  • Advantages of Java Methods

Sorry about that.

Related Tutorials

Java Library

  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot

how to write a method java

  • Explore Our Geeks Community
  • Java Tutorial

Overview of Java

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works - JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?

Basics of Java

  • Java Basic Syntax
  • Java Hello World Program
  • Java Data Types
  • Primitive data type vs. Object data type in Java with Examples
  • Java Identifiers

Operators in Java

  • Java Variables
  • Scope of Variables In Java

Wrapper Classes in Java

Input/output in java.

  • How to Take Input From User in Java?
  • Scanner Class in Java
  • Java.io.BufferedReader Class in Java
  • Difference Between Scanner and BufferedReader Class in Java
  • Ways to read input from console in Java
  • System.out.println in Java
  • Difference between print() and println() in Java
  • Formatted output in Java
  • Fast I/O in Java in Competitive Programming

Flow Control in Java

  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Java Arithmetic Operators with Examples
  • Java Unary Operator with Examples
  • Java Assignment Operators with Examples
  • Java Relational Operators with Examples
  • Java Logical Operators with Examples
  • Java Ternary Operator with Examples
  • Bitwise Operators in Java
  • Strings in Java
  • String class in Java
  • Java.lang.String class in Java | Set 2
  • Why Java Strings are Immutable?
  • StringBuffer class in Java
  • StringBuilder Class in Java with Examples
  • String vs StringBuilder vs StringBuffer in Java
  • StringTokenizer Class in Java
  • StringTokenizer Methods in Java with Examples | Set 2
  • StringJoiner Class in Java
  • Arrays in Java
  • Arrays class in Java
  • Multidimensional Arrays in Java
  • Different Ways To Declare And Initialize 2-D Array in Java
  • Jagged Array in Java
  • Final Arrays in Java
  • Reflection Array Class in Java
  • util.Arrays vs reflect.Array in Java with Examples

OOPS in Java

  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java

Java Methods

Access modifiers in java.

  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java

Inheritance in Java

Abstraction in java, encapsulation in java, polymorphism in java, interfaces in java.

  • 'this' reference in Java
  • Inheritance and Constructors in Java
  • Java and Multiple Inheritance
  • Interfaces and Inheritance in Java
  • Association, Composition and Aggregation in Java
  • Comparison of Inheritance in C++ and Java
  • abstract keyword in java
  • Abstract Class in Java
  • Difference between Abstract Class and Interface in Java
  • Control Abstraction in Java with Examples
  • Difference Between Data Hiding and Abstraction in Java
  • Difference between Abstraction and Encapsulation in Java with Examples
  • Difference between Inheritance and Polymorphism
  • Dynamic Method Dispatch or Runtime Polymorphism in Java
  • Difference between Compile-time and Run-time Polymorphism in Java

Constructors in Java

  • Copy Constructor in Java
  • Constructor Overloading in Java
  • Constructor Chaining In Java with Examples
  • Private Constructors and Singleton Classes in Java

Methods in Java

  • Static methods vs Instance methods in Java
  • Abstract Method in Java with Examples
  • Overriding in Java
  • Method Overloading in Java
  • Difference Between Method Overloading and Method Overriding in Java
  • Differences between Interface and Class in Java
  • Functional Interfaces in Java
  • Nested Interface in Java
  • Marker interface in Java
  • Comparator Interface in Java with Examples
  • Need of Wrapper Classes in Java
  • Different Ways to Create the Instances of Wrapper Classes in Java
  • Character Class in Java
  • Java.Lang.Byte class in Java
  • Java.Lang.Short class in Java
  • Java.lang.Integer class in Java
  • Java.Lang.Long class in Java
  • Java.Lang.Float class in Java
  • Java.Lang.Double Class in Java
  • Java.lang.Boolean Class in Java
  • Autoboxing and Unboxing in Java
  • Type conversion in Java with Examples

Keywords in Java

  • List of all Java Keywords
  • Important Keywords in Java
  • Super Keyword in Java
  • final Keyword in Java
  • static Keyword in Java
  • enum in Java
  • transient keyword in Java
  • volatile Keyword in Java
  • final, finally and finalize in Java
  • Public vs Protected vs Package vs Private Access Modifier in Java
  • Access and Non Access Modifiers in Java

Memory Allocation in Java

  • Java Memory Management
  • How are Java objects stored in memory?
  • Stack vs Heap Memory Allocation
  • How many types of memory areas are allocated by JVM?
  • Garbage Collection in Java
  • Types of JVM Garbage Collectors in Java with implementation details
  • Memory leaks in Java
  • Java Virtual Machine (JVM) Stack Area

Classes of Java

  • Understanding Classes and Objects in Java
  • Java Singleton Class
  • Object Class in Java
  • Inner Class in Java
  • Throwable Class in Java with Examples

Packages in Java

  • Packages In Java
  • How to Create a Package in Java?
  • Java.util Package in Java
  • Java.lang package in Java
  • Java.io Package in Java
  • Java Collection Tutorial

Exception Handling in Java

  • Exceptions in Java
  • Types of Exception in Java with Examples
  • Checked vs Unchecked Exceptions in Java
  • Java Try Catch Block
  • Flow control in try catch finally in Java
  • throw and throws in Java
  • User-defined Custom Exception in Java
  • Chained Exceptions in Java
  • Null Pointer Exception In Java
  • Exception Handling with Method Overriding in Java
  • Multithreading in Java
  • Lifecycle and States of a Thread in Java
  • Java Thread Priority in Multithreading
  • Main thread in Java
  • Java.lang.Thread Class in Java
  • Runnable interface in Java
  • Naming a thread and fetching name of current thread in Java
  • What does start() function do in multithreading in Java?
  • Difference between Thread.start() and Thread.run() in Java
  • Thread.sleep() Method in Java With Examples
  • Synchronization in Java
  • Importance of Thread Synchronization in Java
  • Method and Block Synchronization in Java
  • Lock framework vs Thread synchronization in Java
  • Difference Between Atomic, Volatile and Synchronized in Java
  • Deadlock in Java Multithreading
  • Deadlock Prevention And Avoidance
  • Difference Between Lock and Monitor in Java Concurrency
  • Reentrant Lock in Java

File Handling in Java

  • Java.io.File Class in Java
  • Java Program to Create a New File
  • Different ways of Reading a text file in Java
  • Java Program to Write into a File
  • Delete a File Using Java
  • File Permissions in Java
  • FileWriter Class in Java
  • Java.io.FileDescriptor in Java
  • Java.io.RandomAccessFile Class Method | Set 1
  • Regular Expressions in Java
  • How to write Regular Expressions?
  • Matcher pattern() method in Java with Examples
  • Pattern pattern() method in Java with Examples
  • Quantifiers in Java
  • java.lang.Character class methods | Set 1
  • Java IO : Input-output in Java with Examples
  • Java.io.Reader class in Java
  • Java.io.Writer Class in Java
  • Java.io.FileInputStream Class in Java
  • FileOutputStream in Java
  • Java.io.BufferedOutputStream class in Java
  • Java Networking
  • TCP/IP Model
  • User Datagram Protocol (UDP)
  • Differences between IPv4 and IPv6
  • Difference between Connection-oriented and Connection-less Services
  • Socket Programming in Java
  • java.net.ServerSocket Class in Java
  • URL Class in Java with Examples

The method in Java or Methods of Java is a collection of statements that perform some specific task and return the result to the caller. A Java method can perform some specific task without returning anything. Java Methods allow us to reuse the code without retyping the code. In Java, every method must be part of some class that is different from languages like C, C++, and Python. 

1. A method is like a function i.e. used to expose the behavior of an object. 2. It is a set of codes that perform a particular task.

Syntax of Method

Advantage of Method

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

Method Declaration

In general, method declarations have 6 components:

1. Modifier: It defines the access type of the method i.e. from where it can be accessed in your application. In Java, there 4 types of access specifiers. 

  • public: It is accessible in all classes in your application.
  • protected: It is accessible within the class in which it is defined and in its subclass/es
  • private: It is accessible only within the class in which it is defined.
  • default: It is declared/defined without using any modifier. It is accessible within the same class and package within which its class is defined.
Note: It is Optional in syntax.

2. The return type: The data type of the value returned by the method or void if does not return a value. It is Mandatory in syntax.

3. Method Name: the rules for field names apply to method names as well, but the convention is a little different. It is Mandatory in syntax.

4. Parameter list: Comma-separated list of the input parameters is defined, preceded by their data type, within the enclosed parenthesis. If there are no parameters, you must use empty parentheses ().  It is Optional in syntax.

5. Exception list: The exceptions you expect by the method can throw, you can specify these exception(s). It is Optional in syntax.

6. Method body: it is enclosed between braces. The code you need to be executed to perform your intended operations.  It is Optional in syntax.

methods in java

Types of Methods in Java

There are two types 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 library 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.

2 Ways to Create Method in Java

There are two ways to create a method in Java:

1. Instance Method: Access the instance data using the object name.Declared inside a class.

2. Static Method: Access the static data using class name. Declared inside class with static keyword.

Method Signature

It consists of the method name and a parameter list (number of parameters, type of the parameters, and order of the parameters). The return type and exceptions are not considered as part of it. 

Method Signature of the above function:  

How to Name a Method?

A method name is typically a single word that should be a verb in lowercase or a multi-word, that begins with a verb in lowercase followed by an adjective, noun….. After 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 start 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 use its functionality. There can be three situations when a method is called:  A method returns to the code that invoked it when:  

  • It completes all the statements in the method
  • It reaches a return statement
  • Throws an exception

The control flow of the above program is as follows: 

methods in java

Memory 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 after that, the arguments 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 tracks the top of the stack which is adjusted accordingly.

Example: pseudo-code for implementing methods

There are several advantages to using methods in Java, including:

  • Reusability : Methods allow you to write code once and use it many times, making your code more modular and easier to maintain.
  • Abstraction : Methods allow you to abstract away complex logic and provide a simple interface for others to use. This makes your code more readable and easier to understand.
  • Improved readability : By breaking up your code into smaller, well-named methods, you can make your code more readable and easier to understand.
  • Encapsulation : Methods allow you to encapsulate complex logic and data, making it easier to manage and maintain.
  • Separation of concern s: By using methods, you can separate different parts of your code and assign different responsibilities to different methods, improving the structure and organization of your code.
  • Improved modularity : Methods allow you to break up your code into smaller, more manageable units, improving the modularity of your code.
  • Improved testability : By breaking up your code into smaller, more manageable units, you can make it easier to test and debug your code.
  • Improved performance: By organizing your code into well-structured methods, you can improve performance by reducing the amount of code that needs to be executed and by making it easier to cache and optimize your code.

FAQs in Methods in Java

1. what is a method in java programming.

Java Method is a collection of statements that perform some specific task and return the result to the caller. 

2. What are parts of method in Java?

The 5 methods parts in Java are mentioned below:

  • Return Type
  • Method Name
  • Method Body

Related Articles:   

  • Java is Strictly Passed By Value
  • Method Overloading and Null Error in Java
  • Can we overload or override static methods in Java?
  • Java Quizzes

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org . See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.

Please Login to comment...

Similar read thumbnail

  • Akanksha_Rai
  • simmytarika5
  • nishkarshgandhi
  • sg4ipiafwot258z3lh6xa2mjq2qtxd89f49zgt7g
  • amartajisce
  • aditiyadav20102001
  • anikettchavan

Please write us at contrib[email protected] to report any issue with the above content

Improve your Coding Skills with Practice


Java Tutorial

  • Java Tutorial
  • Java - Home
  • Java - Overview
  • Java - Environment Setup
  • Java - Basic Syntax
  • Java - Variable Types
  • Java - Basic Datatypes
  • Java - Basic Operators
  • Java Control Statements
  • Java - Loop Control
  • Java - Decision Making
  • Java - If-else
  • Java - Switch
  • Java - For Loops
  • Java - For-Each Loops
  • Java - While Loops
  • Java - do-while Loops
  • Java - Break
  • Java - Continue
  • Object Oriented Programming
  • Java - Object & Classes

Java - Methods

  • Java - Constructors
  • Java - Access Modifiers
  • Java - Inheritance
  • Java - Polymorphism
  • Java - Overriding
  • Java - Abstraction
  • Java - Encapsulation
  • Java - Interfaces
  • Java - Packages
  • Java - Inner classes
  • Java - Enums
  • Java Data Types
  • Java - Numbers
  • Java - Boolean
  • Java - Characters
  • Java - Strings
  • Java - Arrays
  • Java - Date & Time
  • Java - Math Class
  • Java File Handling
  • Java - Files
  • Java - Files and I/O
  • Java Error & Exceptions
  • Java - Exceptions
  • Java Multithreading
  • Java - Multithreading
  • Java Synchronization
  • Java - Synchronization
  • Java - Inter-thread Communication
  • Java - Thread Deadlock
  • Java - Thread Control
  • Java Networking
  • Java - Networking
  • Java - URL Processing
  • Java - Generics
  • Java Collections
  • Java - Collections
  • Java List Interface
  • Java - List Interface
  • Java - ArrayList
  • Java - Vector Class
  • Java - Stack Class
  • Java Queue Interface
  • Java - Queue Interface
  • Java - PriorityQueue
  • Java - Deque Interface
  • Java - LinkedList
  • Java -  ArrayDeque
  • Java Map Interface
  • Java - Map Interface
  • Java - HashMap
  • Java - LinkedHashMap
  • Java - WeakHashMap
  • Java - EnumMap
  • Java - SortedMap Interface
  • Java - TreeMap
  • Java - The IdentityHashMap Class
  • Java Set Interface
  • Java - Set Interface
  • Java - HashSet
  • Java - EnumSet
  • Java - LinkedHashSet
  • Java - SortedSet Interface
  • Java - TreeSet
  • Java Data Structures
  • Java - Data Structures
  • Java - Enumeration
  • Java - BitSet Class
  • Java - Dictionary
  • Java - Hashtable
  • Java - Properties
  • Java Collections Algorithms
  • Java - Iterators
  • Java - Comparators
  • Java - Collection Interface
  • Java Miscellenous
  • Java - Regular Expressions
  • Java - Serialization
  • Java - Sending Email
  • Java - Applet Basics
  • Java - Documentation
  • Java Useful Resources
  • Java - Questions and Answers
  • Java - Quick Guide
  • Java - Useful Resources
  • Java - Discussion
  • Java - Examples
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out. println() method, for example, the system actually executes several statements in order to display a message on the console.

Now you will learn how to create your own methods with or without return values, invoke a method with or without parameters, and apply method abstraction in the program design.

Creating Method

Considering the following example to explain the syntax of a method −

public static − modifier

int − return type

methodName − name of the method

a, b − formal parameters

int a, int b − list of parameters

Method definition consists of a method header and a method body. The same is shown in the following syntax −

The syntax shown above includes −

modifier − It defines the access type of the method and it is optional to use.

returnType − Method may return a value.

nameOfMethod − This is the method name. The method signature consists of the method name and the parameter list.

Parameter List − The list of parameters, it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters.

method body − The method body defines what the method does with the statements.

Here is the source code of the above defined method called min() . This method takes two parameters num1 and num2 and returns the maximum between the two −

Method Calling

For using a method, it should be called. There are two ways in which a method is called i.e., method returns a value or returning nothing (no return value).

The process of method calling is simple. When a program invokes a method, the program control gets transferred to the called method. This called method then returns control to the caller in two conditions, when −

  • the return statement is executed.
  • it reaches the method ending closing brace.

The methods returning void is considered as call to a statement. Lets consider an example −

The method returning value can be understood by the following example −

Following is the example to demonstrate how to define a method and how to call it −

The void Keyword

The void keyword allows us to create methods which do not return a value. Here, in the following example we're considering a void method methodRankPoints . This method is a void method, which does not return any value. Call to a void method must be a statement i.e. methodRankPoints(255.7); . It is a Java statement which ends with a semicolon as shown in the following example.

Passing Parameters by Value

While working under calling process, arguments is to be passed. These should be in the same order as their respective parameters in the method specification. Parameters can be passed by value or by reference.

Passing Parameters by Value means calling a method with a parameter. Through this, the argument value is passed to the parameter.

The following program shows an example of passing parameter by value. The values of the arguments remains the same even after the method invocation.

Method Overloading

When a class has two or more methods by the same name but different parameters, it is known as method overloading. It is different from overriding. In overriding, a method has the same method name, type, number of parameters, etc.

Let's consider the example discussed earlier for finding minimum numbers of integer type. If, let's say we want to find the minimum number of double type. Then the concept of overloading will be introduced to create two or more methods with the same name but different parameters.

The following example explains the same −

Overloading methods makes program readable. Here, two methods are given by the same name but with different parameters. The minimum number from integer and double types is the result.

Using Command-Line Arguments

Sometimes you will want to pass some information into a program when you run it. This is accomplished by passing command-line arguments to main( ).

A command-line argument is the information that directly follows the program's name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy. They are stored as strings in the String array passed to main( ).

The following program displays all of the command-line arguments that it is called with −

Try executing this program as shown here −

The this keyword

this is a keyword in Java which is used as a reference to the object of the current class, with in an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables and methods.

Note − The keyword this is used only within instance methods or constructors


In general, the keyword this is used to −

Differentiate the instance variables from local variables if they have same names, within a constructor or a method.

Call one type of constructor (parametrized constructor or default) from other in a class. It is known as explicit constructor invocation.

Here is an example that uses this keyword to access the members of a class. Copy and paste the following program in a file with the name, This_Example.java .

Variable Arguments(var-args)

JDK 1.5 enables you to pass a variable number of arguments of the same type to a method. The parameter in the method is declared as follows −

In the method declaration, you specify the type followed by an ellipsis (...). Only one variable-length parameter may be specified in a method, and this parameter must be the last parameter. Any regular parameters must precede it.

The finalize( ) Method

It is possible to define a method that will be called just before an object's final destruction by the garbage collector. This method is called finalize( ) , and it can be used to ensure that an object terminates cleanly.

For example, you might use finalize( ) to make sure that an open file owned by that object is closed.

To add a finalizer to a class, you simply define the finalize( ) method. The Java runtime calls that method whenever it is about to recycle an object of that class.

Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed.

The finalize( ) method has this general form −

Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class.

This means that you cannot know when or even if finalize( ) will be executed. For example, if your program ends before garbage collection occurs, finalize( ) will not execute.

Kickstart Your Career

Get certified by completing the course

Trending now

What is html blink tag, virtual memory: everything you need to know, the ultimate guide to top front end and back end programming languages for 2021, semaphores in operating systems: a comprehensive overview, paging in os: an ultimate guide, final keyword in java: all you need to know, 20 most popular programming languages to learn in 2023, list to string in python, industry insights: what's changing in the blockchain space for 2024 and beyond, top 40 coding interview questions you should know, an introduction to methods in java with examples.

Methods in Java - Understanding Java Methods With Examples

Table of Contents

Methods in Java or Java methods is a powerful and popular aspect of Java programming.

What are Methods in Java?

A method in Java is a block of code that, when called, performs specific actions mentioned in it. For instance, if you have written instructions to draw a circle in the method, it will do that task. You can insert values or parameters into methods, and they will only be executed when called. They are also referred to as functions. The primary uses of methods in Java are:

  • It allows code reusability (define once and use multiple times)
  • You can break a complex program into smaller chunks of code
  • It increases code readability

Basics to Advanced - Learn It All!

Basics to Advanced - Learn It All!

How to Declare Methods in Java?

You can only create a method within a class. There are a total of six components included in a method declaration. The components provide various information about the method. 

Below is the syntax to declare a method and its components list.

public int addNumbers (int a, int b){

//method body

Access specifier:

It is used to define the access type of the method. The above syntax sees the use of the “public” access specifier. However, Java provides four different specifiers, which are:

  • Public: You can access it from any class
  • Private: You can access it within the class where it is defined
  • Protected: Accessible only in the same package or other subclasses in another package
  • Default: It is the default access specifier used by the Java compiler if we don’t mention any other specifiers. It is accessible only from the package where it is declared


It defines the return type of the method. In the above syntax, “int” is the return type. We can mention void as the return type if the method returns no value.

Method name:

It is used to give a unique name to the method. In the above syntax, “addNumbers” is the method name. This tutorial looks at some tips for naming a method, shortly.

Parameter list:

It is a list of arguments (data type and variable name) that will be used in the method. In the above syntax, “int a, int b” mentioned within the parentheses is the parameter list. You can also keep it blank if you don’t want to use any parameters in the method.

Method signature:

You don’t have to do anything additional here. The method signature is just a combination of the method name and parameter list.

Method body:

This is the set of instructions enclosed within curly brackets that the method will perform.


In the above example:

  • ‘Public’ is the access specifier
  • The return type is ‘int’ (i.e. integer)
  • The method name is addNumbers
  • int x and int y are the parameters
  • addNumbers (int x, int y) is the method signature
  • The method body is:

int addition = x + y;

return addition;

Adding an Example would be great to increase the clarity about the concept

How to Name a Method?

Some of the rules and tips to name the methods in Java are:

  • Try to use a name that corresponds to the functionality (if the method is adding two numbers, use add() or sum())
  • The method name should start with a verb and in lowercase (Ex: sum(), divide(), area())
  • For a multi-word name, the first word should be a verb followed by a noun or adjective without any space and with the first letter capitalized (Ex: addIntegers(), areaOfSquare)

How to Call a Method?

As mentioned earlier, you need to call a method to execute and use its functionalities. You can call a method by using its name followed by the parentheses and a semicolon. Below is the syntax for calling a method:

The example below will create an example method named exMethod() and call it to print a text.


What are the Types of Methods in Java?

Methods in Java can be broadly classified into two types:

  • User-defined

Predefined Methods

As the name gives it, predefined methods in Java are the ones that the Java class libraries already define. This means that they can be called and used anywhere in our program without defining them. There are numerous predefined methods, such as length(), sqrt(), max(), and print(), and each of them is defined inside their respective classes.

The example mentioned below uses three predefined methods, which are main(), print(), and sqrt().


User-defined Methods

Custom methods defined by the user are known as user-defined methods. It is possible to modify and tweak these methods according to the situation. Here’s an example of a user-defined method.


Methods in Java can also be classified into the following types:

  • Static Method
  • Instance Method
  • Abstract Method

Factory Method

Creating static methods in java.

Static methods are the ones that belong to a class and not an instance of a class. Hence, there is no need to create an object to call it, and that’s the most significant advantage of static methods. It is possible to create a static method by using the “static” keyword. The primary method where the execution of the Java program begins is also static.

Please add the code manually by typing


Applying Instance Methods in Java Code

The instance method is a non-static method that belongs to the class and its instance. Creating an object is necessary to call the instance method.


Instance methods are further divided into two types:

Accessor Method

It is used to get a private field’s value, accessor methods in Java can only read instance variables. They are always prefixed with the word ‘get’.

Mutator Method

It is used to get and set the value of a private field, mutator methods in Java can read and modify instance variables. They are always prefixed with the word  ‘set’.

Using Abstract Methods in Java

Abstract methods in Java do not have any code in them. This means that there is no need to provide the implementation code while declaring it. Instead, it is possible to declare the method body later in the program. It is known that one can declare an abstract method by using the “abstract” keyword. There is another hard rule to declare abstract methods, and it is that they can only be declared within an abstract class .


Factory methods are the ones that return an object to the class where it belongs. Usually, all static methods also fall into this type of method.

Don't miss out on the opportunity to become a Certified Professional with Simplilearn's Post Graduate Program in Full Stack Web Development . Enroll Today!

In this tutorial, you were introduced to everything about methods in Java. It’s time to implement your learning and do some practicals. You can also refer to our methods and encapsulation tutorial to delve deeper into this concept. This tutorial will help you learn how to apply the OOPs concepts of access modifiers and encapsulation to Java classes. It will enable you to get a strong grasp on Java programming. But if you want to excel in overall Java development, Simplilearn’s Post Graduate Program in Full Stack Web Development  is the best way to do so. The 60 hours of applied learning and 35 coding-related exercises make the course adept at helping you become an expert developer. You will work on the most popular Java frameworks, including Hibernate and Spring during this course. Have any questions for us? Leave them in the comments section, and our experts will get back to you sovon. Happy learning!

Find our Post Graduate Program in Full Stack Web Development Online Bootcamp in top cities:

About the author.


Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

Recommended Programs

Post Graduate Program in Full Stack Web Development

Full Stack Java Developer Job Guarantee Program

Java Certification Training

*Lifetime access to high-quality, self-paced e-learning content.

StringBuilder in Java: Constructors, Methods, and Examples

StringBuilder in Java: Constructors, Methods, and Examples

Recommended resources.

Free eBook: Pocket Guide to the Microsoft Certifications

Free eBook: Pocket Guide to the Microsoft Certifications

Set in Java : The Methods and Operations You Can Perform

Set in Java : The Methods and Operations You Can Perform

What Are Java Strings And How to Implement Them?

What Are Java Strings And How to Implement Them?

Free eBook: Enterprise Architecture Salary Report

Free eBook: Enterprise Architecture Salary Report

HashSet In Java: Features, Hierarchy, Constructors, Methods, and More

HashSet In Java: Features, Hierarchy, Constructors, Methods, and More

Arrays In Java: Declare, Define, and Access Array

Arrays In Java: Declare, Define, and Access Array

  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Javatpoint Logo

Java Tutorial

Control statements, java object class, java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.


  • Send your Feedback to [email protected]

Help Others, Please Share


Learn Latest Tutorials

Splunk tutorial


Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial



Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h [email protected] , to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • Graphic Designing
  • Digital Marketing
  • On Page and Off Page SEO
  • Content Development
  • Corporate Training
  • Classroom and Online Training

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] . Duration: 1 week to 2 week

RSS Feed

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

Defining Methods

Here is an example of a typical method declaration:

The only required elements of a method declaration are the method's return type, name, a pair of parentheses, () , and a body between braces, {} .

More generally, method declarations have six components, in order:

  • Modifiers—such as public , private , and others you will learn about later.
  • The return type—the data type of the value returned by the method, or void if the method does not return a value.
  • The method name—the rules for field names apply to method names as well, but the convention is a little different.
  • The parameter list in parenthesis—a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, () . If there are no parameters, you must use empty parentheses.
  • An exception list—to be discussed later.
  • The method body, enclosed between braces—the method's code, including the declaration of local variables, goes here.

Modifiers, return types, and parameters will be discussed later in this lesson. Exceptions are discussed in a later lesson.

The signature of the method declared above is:

Naming a Method

Although a method name can be any legal identifier, code conventions restrict method names. By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word names, the first letter of each of the second and following words should be capitalized. Here are some examples:

Typically, a method has a unique name within its class. However, a method might have the same name as other methods due to method overloading .

Overloading Methods

The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures . This means that methods within a class can have the same name if they have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled "Interfaces and Inheritance").

Suppose that you have a class that can use calligraphy to draw various types of data (strings, integers, and so on) and that contains a method for drawing each data type. It is cumbersome to use a new name for each method—for example, drawString , drawInteger , drawFloat , and so on. In the Java programming language, you can use the same name for all the drawing methods but pass a different argument list to each method. Thus, the data drawing class might declare four methods named draw , each of which has a different parameter list.

Overloaded methods are differentiated by the number and the type of the arguments passed into the method. In the code sample, draw(String s) and draw(int i) are distinct and unique methods because they require different argument types.

You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.

The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.

About Oracle | Contact Us | Legal Notices | Terms of Use | Your Privacy Rights

Copyright © 1995, 2022 Oracle and/or its affiliates. All rights reserved.

How to Create a Method in Java

A method is a unit of code that you call in a Java program. A method can support arguments and usually returns a value. To create a method in Java, follow these four steps.

Java Source for Method

The method you have coded is named computeAreaOfRectangle . It accepts two integer arguments and returns an integer, the product of the two arguments.

  • Save your file as CreateAMethodInJava.java .

Compile Program with Method

Related Articles

  • How to Check Object Type in Java
  • How to Create a Jar File in Java
  • How to Compile Packages in Java
  • How to Throw an Exception in Java
  • How to Create an Exception Class in Java
  • How to Use the super Keyword to Call a Base Class Constructor in Java
  • How to Use the Comparator.comparing Method in Java 8
  • How to Use System.in in Java
  • How to Call an Interface Method in Java
  • How to Add a Time Zone in the Java 8 Date/Time API
  • How to Rethrow an Exception in Java
  • How to Use the instanceof Operator with a Generic Class in Java
  • How to Instantiate an Object in Java
  • How to Filter Distinct Elements from a Collection in Java 8
  • How to Create a Derived Class in Java
  • How to Skip Elements with the Skip Method in Java 8
  • How to Create a Java Bean
  • How to Implement an Interface in Java
  • How to Compare Two Objects with the equals Method in Java
  • How to Set PATH from JAVA_HOME
  • How to Prevent Race Conditions in Java 8
  • How to Write a Block of Code in Java
  • How to Display the Contents of a Directory in Java
  • How to Group and Partition Collectors in Java 8
  • How to Create a Reference to an Object in Java
  • How to Reduce the Size of the Stream with the Limit Method in Java 8
  • How to Write an Arithmetic Expression in Java
  • How to Format Date and Time in the Java 8 Date/Time API
  • How to Use Comparable and Comparator in Java
  • How to Break a Loop in Java
  • How to Use the this Keyword to Call Another Constructor in Java
  • How to Write a Unit Test in Java
  • How to Declare Variables in Java
  • How to Override Base Class Methods with Derived Class Methods in Java
  • How to Use Serialized Objects in Java
  • How to Write Comments in Java
  • How to Implement Functional Interfaces in Java 8
  • How to Write Type Parameters with Multiple Bounds in Java
  • How to Add Type and Repeating Annotations to Code in Java 8
  • How to Use Basic Generics Syntax in Java
  • How to Map Elements Using the Map Method in Java 8
  • How to Work with Properties in Java
  • How to Write while and do while Loops in Java
  • How to Use the finally Block in Java
  • How to Write for-each Loops in Java
  • How to Create a Method in Java (this article)
  • How to Continue a Loop in Java
  • How to Handle Java Files with Streams
  • How to Create an Interface Definition in Java
  • How Default Base Class Constructors Are Used with Inheritance


  1. An Introduction to Methods in Java with Examples

    how to write a method java

  2. How to Create a Method in Java

    how to write a method java

  3. Java Methods

    how to write a method java

  4. How to Call a Method in Java (with Pictures)

    how to write a method java

  5. How To Write A Method In Java

    how to write a method java

  6. Methods in Java

    how to write a method java


  1. What Is Concrete Class in Java?

    Concrete class in Java is the default class and is a derived class that provides the basic implementations for all of the methods that are not already implemented in the base class.

  2. Java Developer Course Online for Free: Where to Start

    Java is one of the most popular programming languages in the world, and a career in Java development can be both lucrative and rewarding. However, taking a Java developer course online for free can be a challenge. With so many options avail...

  3. Common Mistakes to Avoid When Downloading Free Java Software

    Java is a popular programming language widely used for developing a variety of applications and software. If you are looking to download free Java software, it is important to be cautious and aware of some common mistakes that many people m...

  4. 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

  5. Java Methods (With Examples)

    Java Methods · User-defined Methods: We can create our own method based on our requirements. Standard Library Methods · methodName - It is an identifier that is

  6. Java Methods

    How to Name a Method? · While defining a method, remember that the method name must be a verb and start with a lowercase letter. · If the method

  7. Creating your own Method?

    For the sake of this example, let's say myString.setText("Knife"); . Now since we know myString is a knife, could I create a method where I

  8. Java

    A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for example

  9. An Introduction to Methods in Java with Examples

    A method in Java is a block of code that, when called, performs specific actions mentioned in it. For instance, if you have written instructions

  10. Method in Java

    How to Create a User-defined Method · //user defined method · public static void findEvenOdd(int num) · { · //method body · if(num%2==0) · System.out.println(num+" is

  11. Defining Methods

    The only required elements of a method declaration are the method's return type, name, a pair of parentheses, () , and a body between braces, {} . More

  12. How to Create a Method in Java

    How to Create a Method in Java · Open your text editor and create a new file. Type in the following Java statements: · Save your file as CreateAMethodInJava.

  13. Methods in Java Tutorial #26

    ✓ In this video I show exactly how to make a method in java for your program! Start practicing now with 10 free java programs - http

  14. Intro to Creating a Method

    A method in Java is a set of related Java statements to accomplish a task ... write a similar method You create methods by writing a method