- Java Methods
- Declaring a Java Method
- Calling a Method in Java
- Example 1: Java Methods
- Java Method Return Type
- Example 2: Method Return Type
- Method Parameters in Java
- Example 3: Method Parameters
- Standard Library Methods
- Example 4: Java Standard Library Method
- What are the advantages of using methods?
- Example 5: Java Method for Code Reusability
- Table of Contents
- Java Methods
- Create a Method
- Example
- Example Explained
- Call a Method
- Example
- Example
- Defining Methods
- Naming a Method
- Overloading Methods
- Method coding in java
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
Java Methods
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:
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.
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 static returnType nameOfMethod (parameter1, parameter2, . ) < // method body >
- 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.
- 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.
// calls the method addNumbers();
Example 1: Java Methods
class Main < // create a method public int addNumbers(int a, int b) < int sum = a + b; // return value return sum; >public static void main(String[] args) < int num1 = 25; int num2 = 15; // create an object of Main Main obj = new Main(); // calling method int result = obj.addNumbers(num1, num2); System.out.println("Sum is: " + result); >>
In the above example, we have created a method named addNumbers() . The method takes two parameters a and b . Notice the line,
int result = obj.addNumbers(num1, num2);
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
class Main < // create a method public static int square(int num) < // return statement return num * num; >public static void main(String[] args) < int result; // call the method // store returned value to result result = square(10); System.out.println("Squared value of 10 is: " + result); >>
Squared value of 10 is: 100
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.
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,
// method with two parameters int addNumbers(int a, int b) < // code >// method with no parameter int addNumbers()< // code >
If a method is created with parameters, we need to pass the corresponding values while calling the method. For example,
// calling the method with two parameters addNumbers(25, 15); // calling the method with no parameters addNumbers()
Example 3: Method Parameters
class Main < // method with no parameter public void display1() < System.out.println("Method without parameter"); >// method with single parameter public void display2(int a) < System.out.println("Method with a single parameter: " + a); >public static void main(String[] args) < // create an object of Main Main obj = new Main(); // calling method with no parameter obj.display1(); // calling method with the single parameter obj.display2(24); >>
Method without parameter Method with a single parameter: 24
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.
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
public class Main < // method defined private static int getSquare(int x)< return x * x; >public static void main(String[] args) < for (int i = 1; i > >
Square of 1 is: 1 Square of 2 is: 4 Square of 3 is: 9 Square of 4 is: 16 Square of 5 is: 25
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
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 certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.
Create a 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:
Example
Create a method inside Main:
Example Explained
- myMethod() is the name of the method
- static means that the method belongs to the Main class and not an object of the Main class. You will learn more about objects and how to access methods through objects later in this tutorial.
- void means that this method does not have a return value. You will learn more about return values later in this chapter
Call a Method
To call a method in Java, write the method’s name followed by two parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called:
Example
Inside main , call the myMethod() method:
public class Main < static void myMethod() < System.out.println("I just got executed!"); >public static void main(String[] args) < myMethod(); >> // Outputs "I just got executed!"
A method can also be called multiple times:
Example
public class Main < static void myMethod() < System.out.println("I just got executed!"); >public static void main(String[] args) < myMethod(); myMethod(); myMethod(); >> // I just got executed! // I just got executed! // I just got executed!
In the next chapter, Method Parameters, you will learn how to pass data (parameters) into a method.
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 generally, method declarations have six components, in order:
- Modifierssuch as public , private , and others you will learn about later.
- The return typethe data type of the value returned by the method, or void if the method does not return a value.
- The method namethe rules for field names apply to method names as well, but the convention is a little different.
- The parameter list in parenthesisa 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 listto be discussed later.
- The method body, enclosed between bracesthe 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.
Definition: Two of the components of a method declaration comprise the method signaturethe method’s name and the parameter types.
The signature of the method declared above is:
calculateAnswer(double, int, double, double)
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:
run runFast getBackground getFinalData compareTo setX isEmpty
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 methodfor 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.
public class DataArtist < . public void draw(String s) < . >public void draw(int i) < . >public void draw(double f) < . >public void draw(int i, double f) < . >>
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.
Method coding in java
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
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
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
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
Like/Subscribe us for latest updates or newsletter