You are on page 1of 7

9/26/2021 How to call a method in Java - Examples Java Code Geeks - 2021

News Knowledge Base Deals About      è Search... 🔍

ANDROID CORE JAVA DESKTOP JAVA ENTERPRISE JAVA JAVA BASICS JVM LANGUAGES PYTHON SOFTWARE DEVELOPMENT DEVOPS

⌂ Home » Core Java » How to call a method in Java


NEWSLETTER
ABOUT FIROUZEH HEJAZI
118,286 insiders are already enjoying weekly
A self-motivated and hard-working developer with more than 4 years of extensive experience in developing software in java platforms. updates and complimentary whitepapers!
A multi-skilled and problem-solving engineer who has participated in implementing a range of applications in different roles. Possess a
MSc in Knowledge Engineering and Decision Science.
Join them now to gain exclusive
access to the latest news in the Java world, as
well as insights about Android, Scala, Groovy and
other related technologies.

Email address:

How to call a method in Java Your email address

 Posted by: Firouzeh hejazi  in Core Java  December 26th, 2019  0  37581 Views Receive Java & Developer job alerts in your
Area
In this article, we will show you how to call a method in Java. A method in java is a collection of statements that are grouped together to
perform an operation. You can pass data, known as parameters, into a method. Methods are also known as functions.
Sign up
You can also check this tutorial in the following video:

Java Methods Tutorial JOIN US

With 1,240,600 monthly


unique visitors and over
500 authors we are
placed among the top Java
related sites around.
Constantly being on the
lookout for partners; we
encourage you to join us.
So If you have a blog with
unique and interesting content then you should
check out our JCG partners program. You can also
be a guest writer for Java Code Geeks and hone
your writing skills!

Java Methods Tutorial – video

Each method has its own name. When that name is encountered in a program, the execution of the program branches to the body of that
method. When the method is finished, execution returns to the area of the program code from which it was called, and the program continues
on to the next line of code.

When you call the System.out.println() method, for example, the system actually executes several statements in the background which is
already stored in the library, in order to display a message on the console.

Execution process

Why use methods? To reuse code: define the code once, and use it many times. Actually modular fashion allows for several programmers
to work independently on separate concepts which can be assembled later to create the entire project. The use of methods will be our first
step in the direction of modular programming.

https://examples.javacodegeeks.com/how-to-call-a-method-in-java/ 1/7
9/26/2021 How to call a method in Java - Examples Java Code Geeks - 2021

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

1. Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by parentheses ().

Method definition consists of a method header and a method body.

Example:

1 public class MyClass {


2 public static void myMethod() {
3 // code to be executed
4 }
5 }

Code explanation:

public static

: modifier, it defines the access type of the method

myMethod()

: name of the method

static

: means that the method belongs to the MyClass class and not an object of the MyClass class.

void

: means that this method does not have a return value.

Note: The word


public

before the method name means that the method itself can be called from anywhere which includes other classes, even from different
packages (files) as long as you import the class. There are three other words that can replace
public

. They are
protected

and
private

. If a method is
protected

, then only this class and subclasses (classes that use this as a basis to build off of) can call the method. If a method is
private

, then the method can only be called inside the class. The last keyword is really not even a word. This is if you had nothing in the place of
public

,
protected

, or
private

. This is called the default, or package-private. This means that only the classes in the same package can call the method. If you are
interested to see more examples you can read this article.

2. How to call a method in Java


To call a method in Java, write the method’s name followed by two parentheses () and a semicolon;

The process of method calling is simple. When a program invokes a method, the program control gets transferred to the called method.

In the following example,


myMethod()

is used to print a text (the action), when it is called:

MyClass.java

01 public class MyClass {


02
03 static void myMethod() {
04 System.out.println("You have called me! My name is: myMethod!");
05 }
06
07 public static void main(String[] args) {
08 myMethod();
09 }
10 }

https://examples.javacodegeeks.com/how-to-call-a-method-in-java/ 2/7
9/26/2021 How to call a method in Java - Examples Java Code Geeks - 2021

Output:

1 You have called me! My name is: myMethod!

In the above example if you remove the



static

keyword, java complains that you can’t call a method from a static function:

Non-static methods cannot be referenced from a static context

If you don’t want to use


static

, you can only call instance method:

01 public class MyClass {


02
03 void myMethod() {
04 System.out.println("You have called me! My name is: myMethod!");
05 }
06
07 public static void main(String[] args) {
08 new MyClass().myMethod();
09 }
10 }

A method can also be called multiple times:

MyClass.java

01 public class MyClass {


02
03 static void myMethod() {
04 System.out.println("You have called me! My name is: myMethod!");
05 }
06
07 public static void main(String[] args) {
08 myMethod();
09 myMethod();
10 myMethod();
11 }
12 }

Output:

1 You have called me! My name is: myMethod!


2 You have called me! My name is: myMethod!
3 You have called me! My name is: myMethod!

3. Java Method Parameters


3.1 Parameters and Arguments
Information can be passed to methods as parameter. Parameters act as variables inside the method.

Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them
with a comma.

The following example has a method that takes an


int

called num as parameter. When the method is called, we pass along a number, which is used inside the method to be multiplied by 2:

Example03

01 public class Math {


02
03 static int multiplyBytwo(int number) {
04 return number * 2;
05 }
06
07 public static void main(String[] args) {
08 int result = multiplyBytwo(2);
09 System.out.println("The output is: " + result);
10 }
11 }

Output:

1 The result of multiplication is: 4

3.2 Multiple Parameters


You can have as many parameters as you like. See the following example:

https://examples.javacodegeeks.com/how-to-call-a-method-in-java/ 3/7
9/26/2021 How to call a method in Java - Examples Java Code Geeks - 2021

Example04

01 public class Math {


02
03 static int sum(int num1, int num2) { 
04 return num1 + num2;
05 }
06
07 public static void main(String[] args) {
08 int result = sum(2,3);
09 System.out.println("Sum of numbers is: " + result);
10 }
11 }

Output:

1 Sum of numbers is: 5

Note: when you are working with multiple parameters, the method call must have the same number of arguments as there are parameters,
and the arguments must be passed in the same order.

In the examples 03 and 04 we have passed parameters by value. In fact the values of the arguments remains the same even after the
method invocation. Lets see another example, example05:

Swapp.java

01 public class Swapp {


02
03 public static void swapFunction(int a, int b) {
04 System.out.println("In swapFunction at the begining: a = " + a + " , b = " + b);
05
06 // Swap n1 with n2
07 int c = a;
08 a = b;
09 b = c;
10 System.out.println("In swapFunction at the end: a = " + a + " , b = " + b);
11 }
12
13 public static void main(String[] args) {
14 int a = 10;
15 int b = 20;
16 System.out.println("Before swapping: a = " + a + " , b = " + b);
17
18 // Invoke the swap method
19 swapFunction(a, b);
20 System.out.println("\n**Now, Before and After swapping values will be same here**:");
21 System.out.println("After swapping: a = " + a + " , b = " + b);
22 }
23
24 }

Output:

1 Before swapping: a = 10 , b = 20
2 In swapFunction at the begining: a = 10 , b = 20
3 In swapFunction at the end: a = 20 , b = 10
4
5 **Now, Before and After swapping values will be same here**:
6 After swapping: a = 10 , b = 20

Now if we pass an object and change any of its fields, the values will also be changed, example06:

Student.java

01 public class Student {


02
03 String firstName;
04 String familyName;
05 int age;
06
07 public Student(){
08
09 }
10
11 public Student(String firstName, String familyName){
12 this.firstName = firstName;
13 this.familyName = familyName;
14 }
15
16 public String getFirstName() {
17 return firstName;
18 }
19
20 public void setFirstName(String firstName) {
21 this.firstName = firstName;
22 }
23
24 public String getFamilyName() {
25 return familyName;
26 }
27
28 public void setFamilyName(String familyName) {
29 this.familyName = familyName;
30 }
31
32 public int getAge() {
33 return age;
34 }
35
36 public void setAge(int age) {
37 this.age = age;
38 }
39 }

Now we create an instance of the


Student

class and initialize its fields by its constructor, after that we will rechange the field value by its method:

01 public class Main {


02
03 public static void main(String[] args) {
04 Student student = new Student("Jack", "Smith");
05 System.out.println("Student's name is set (Constructor): " + student.getFirstName());
06
07 student.setFirstName("John");
08 System.out.println("Student's name is set (Main): " + student.getFirstName());
09 }
10

https://examples.javacodegeeks.com/how-to-call-a-method-in-java/ 4/7
9/26/2021 How to call a method in Java - Examples Java Code Geeks - 2021
11 }

Output:

1 Student's name is set (Constructor): Jack


2 Student's name is set (Main): John 

4. 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. Consider the following example, which has
one method that adds numbers of different type, example07:

Sum.java

01 public class Sum {


02
03 static int sum(int x, int y) {
04 return x + y;
05 }
06
07 static double sum(double x, double y) {
08 return x + y;
09 }
10
11 public static void main(String[] args) {
12 int int_sum = sum(10, 20);
13 double double_sum = sum(10.5, 23.67);
14
15 System.out.println("int: " + int_sum);
16 System.out.println("double: " + double_sum);
17 }
18
19 }

Output:

1 int: 30
2 double: 34.17

Note: Multiple methods can have the same name as long as the number and/or type of parameters are different.

5. Method Overriding
Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of
its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature and same return type(or
sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.

Method overriding

If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the
subclass is used to invoke the method, then the version in the child class will be executed. In other words, it is the type of the object being
referred to (not the type of the reference variable) that determines which version of an overridden method will be executed.

5.1 Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Let us see an example, example08:

Human.java

1 public class Human {


2
3 //Overridden method
4 public void walk()
5 {
6 System.out.println("Human is walking");
7 }
8
9 }

Now we extend the


https://examples.javacodegeeks.com/how-to-call-a-method-in-java/ 5/7
9/26/2021 How to call a method in Java - Examples Java Code Geeks - 2021

Human

class and create a subclass from it:

HumanChild.java

01 public class HumanChild extends Human{


02
03 //Overriding method
04 public void walk(){
05 System.out.println("Child is walking");
06 }
07 public static void main( String args[]) {
08 HumanChild obj = new HumanChild();
09 obj.walk();
10 }
11
12 }

As you see,
obj.walk();

will call the child class version of


walk()

Output:

1 Child is walking

6. More articles
Best Way to Learn Java Programming Online
Java Tutorial for Beginners (with video)
Java Constructor Example (with video)
Printf Java Example (with video)

7. Download the Source Code


Download
You can download the full source code of this example here: How to call a method in Java
Last updated on Jun. 15th, 2021

Do you want to know how to develop your skillset to become a Java


Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book


2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design

and many more ....

Email address:

Your email address

Receive Java & Developer job alerts in your Area

Sign up

LIKE THIS ARTICLE? READ MORE FROM JAVA CODE GEEKS

 Subscribe 

Be the First to Comment!

{} [+] 

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 COMMENTS  

https://examples.javacodegeeks.com/how-to-call-a-method-in-java/ 6/7
9/26/2021 How to call a method in Java - Examples Java Code Geeks - 2021


KNOWLEDGE BASE HALL OF FAME ABOUT JAVA CODE GEEKS

JCGs (Java Code Geeks) is an independent online community focused on creating the
Courses Android Alert Dialog Example
ultimate Java to Java developers resource center; targeted at the technical architect,
technical team lead (senior developer), project manager and junior developers alike.
Minibooks Android OnClickListener Example
JCGs serve the Java, SOA, Agile and Telecom communities with daily news written by
domain experts, articles, tutorials, reviews, announcements, code snippets and open
News How to convert Character to String and a
source projects.
String to Character Array in Java
Resources
Java Inheritance example DISCLAIMER
Tutorials
Java write to File Example
All trademarks and registered trademarks appearing on Java Code Geeks are the
property of their respective owners. Java is a trademark or registered trademark of
THE CODE GEEKS NETWORK java.io.FileNotFoundException – How to
Oracle Corporation in the United States and other countries. Examples Java Code Geeks
solve File Not Found Exception
is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
.NET Code Geeks java.lang.arrayindexoutofboundsexception
– How to handle Array Index Out Of
Java Code Geeks Bounds Exception

System Code Geeks java.lang.NoClassDefFoundError – How to


solve No Class Def Found Error
Web Code Geeks
JSON Example With Jersey + Jackson

Spring JdbcTemplate Example

Examples Java Code Geeks and all content copyright © 2010-2021, Exelixis Media P.C. | Terms of Use | Privacy Policy | Contact      è

https://examples.javacodegeeks.com/how-to-call-a-method-in-java/ 7/7

You might also like