Methods in Java
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.
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.
Java provides some pre-defined methods, such as [Link](),
but you can also create your own methods to perform certain actions:
Create a Method
A method must be declared within a class. It is defined with the name of the
method, followed by parentheses ().
The syntax to declare a method is:
returnType methodName() {
// method body
}
Here,
• 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 braces {
}.
For example,
int addNumbers() {
// code
}
In the this example, the name of the method is adddNumbers() . And, the return
type is int .
This is the simple syntax of declaring a method. However, the complete
syntax of declaring a method is
modifier static returnType Method_Name (parameter1, parameter2, ...) {
// method body
}
Or
<access_modifier> <return_type> <method_name>(list_of_parameters) {
// method body
}
Where:
• modifier - It defines access types whether the method is public, private,
and so on.
• 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 [Link]() 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.
Call a Method
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 = [Link](num1, num2);
[Link]("Sum is: " + result);
}
}
Output
Sum is: 40
In the above example, we have created a method named addNumbers() . The
method takes two parameters a and b . Notice the line,
int result = [Link](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.
A method can also be called multiple times:
Example
public class Main {
static void myMethod() {
[Link]("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!
Parameters and Arguments
Information can be passed to methods as a 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 a String called fname as
parameter. When the method is called, we pass along a first name, which is
used inside the method to print the full name:
Example
public class Main {
static void myMethod(String fname) {
[Link](fname + " Refsnes");
public static void main(String[] args) {
myMethod("Ahmed");
myMethod("Ali");
myMethod("Khaled");
// Ahmed Refsnes
// Ali Refsnes
// Khaled Refsnes
When a parameter is passed to the method, it is called an argument. So,
from the example above: fname is a parameter,
while Ahmed, Ali and Khaled are arguments.
Multiple Parameters
You can have as many parameters as you like:
Example
public class Main {
static void myMethod(String fname, int age) {
[Link](fname + " is " + age);
public static void main(String[] args) {
myMethod("Ahmed", 5);
myMethod("Ali", 8);
myMethod("Khaled", 31);
// Ahmed is 5
// Ali is 8
// Khaled is 31
Note that 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.
Example
public class Main {
// Create a checkAge() method with an integer variable called age
static void checkAge(int age) {
// If age is less than 18, print "access denied"
if (age < 18) {
[Link]("Access denied - You are not old enough!");
// If age is greater than, or equal to, 18, print "access granted"
} else {
[Link]("Access granted - You are old enough!");
public static void main(String[] args) {
checkAge(20); // Call the checkAge method and pass along an age of 20
// Outputs "Access granted - You are old enough!"
Return Values
In the previous page, we used the void keyword in all examples, which
indicates that the method should not return a value.
If you want the method to return a value, you can use a primitive data type
(such as int, char, etc.) instead of void, and use the return keyword inside
the method:
Example
public class Main {
static int myMethod(int x) {
return 5 + x;
public static void main(String[] args) {
[Link](myMethod(3));
// Outputs 8 (5 + 3)
This example returns the sum of a method's two parameters:
Example
public class Main {
static int myMethod(int x, int y) {
return x + y;
public static void main(String[] args) {
[Link](myMethod(5, 3));
// Outputs 8 (5 + 3)
You can also store the result in a variable (recommended, as it is easier to read
and maintain):
Example
public class Main {
static int myMethod(int x, int y) {
return x + y;
public static void main(String[] args) {
int z = myMethod(5, 3);
[Link](z);
// Outputs 8 (5 + 3)
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.
For example,
• print() is a method of [Link] . 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
public class Main {
public static void main(String[] args) {
// using the sqrt() method
[Link]("Square root of 4 is: " + [Link](4));
}
}
Run Code
Output:
Square root of 4 is: 2.0
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 <= 5; i++) {
// method call
int result = getSquare(i);
[Link]("Square of " + i + " is: " + result);
}
}
}
Output:
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.
Method Overloading
With method overloading, multiple methods can have the same name with
different parameters:
Example
int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)
Consider the following example, which has two methods that add numbers of
different type:
Example
static int plusMethodInt(int x, int y) {
return x + y;
static double plusMethodDouble(double x, double y) {
return x + y;
public static void main(String[] args) {
int myNum1 = plusMethodInt(8, 5);
double myNum2 = plusMethodDouble(4.3, 6.26);
[Link]("int: " + myNum1);
[Link]("double: " + myNum2);
Instead of defining two methods that should do the same thing, it is better to
overload one.
In the example below, we overload the plusMethod method to work for
both int and double:
Example
static int plusMethod(int x, int y) {
return x + y;
static double plusMethod(double x, double y) {
return x + y;
public static void main(String[] args) {
int myNum1 = plusMethod(8, 5);
double myNum2 = plusMethod(4.3, 6.26);
[Link]("int: " + myNum1);
[Link]("double: " + myNum2);
Note: Multiple methods can have the same name as long as the number and/or
type of parameters are different.
Java Scope
In Java, variables are only accessible inside the region they are created. This is
called scope.
Method Scope
Variables declared directly inside a method are available anywhere in the
method following the line of code in which they were declared:
Example
public class Main {
public static void main(String[] args) {
// Code here CANNOT use x
int x = 100;
// Code here can use x
[Link](x);
}
Block Scope
A block of code refers to all of the code between braces {}.
Variables declared inside blocks of code are only accessible by the code between
the braces, which follows the line in which the variable was declared:
Example
public class Main {
public static void main(String[] args) {
// Code here CANNOT use x
{ // This is a block
// Code here CANNOT use x
int x = 100;
// Code here CAN use x
[Link](x);
} // The block ends here
// Code here CANNOT use x
}
}
A block of code may exist on its own or it can belong to
an if, while or for statement. In the case of for statements, variables declared
in the statement itself are also available inside the block's scope.
Java Recursion
Recursion is the technique of making a function call itself. This technique
provides a way to break complicated problems down into simple problems
which are easier to solve.
Recursion may be a bit difficult to understand. The best way to figure out
how it works is to experiment with it.
Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers
is more complicated. In the following example, recursion is used to add a
range of numbers together by breaking it down into the simple task of
adding two numbers:
Example
Use recursion to add all of the numbers up to 10.
public class Main {
public static void main(String[] args) {
int result = sum(10);
[Link](result);
public static int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
Example Explained
When the sum() function is called, it adds parameter k to the sum of all
numbers smaller than k and returns the result. When k becomes 0, the
function just returns 0. When running, the program follows these steps:
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 +9+8+7+6+5+4+3+2+1+0
Since the function does not call itself when k is 0, the program stops there
and returns the result.
Halting Condition
Just as loops can run into the problem of infinite looping, recursive functions
can run into the problem of infinite recursion. Infinite recursion is when the
function never stops calling itself. Every recursive function should have a
halting condition, which is the condition where the function stops calling
itself. In the previous example, the halting condition is when the
parameter k becomes 0.
It is helpful to see a variety of different examples to better understand the
concept. In this example, the function adds a range of numbers between a
start and an end. The halting condition for this recursive function is
when end is not greater than start:
Example
Use recursion to add all of the numbers between 5 to 10.
public class Main {
public static void main(String[] args) {
int result = sum(5, 10);
[Link](result);
public static int sum(int start, int end) {
if (end > start) {
return end + sum(start, end - 1);
} else {
return end;
The developer should be very careful with recursion as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess
amounts of memory or processor power. However, when written correctly
recursion can be a very efficient and mathematically-elegant approach to
programming.
Java Constructors
A constructor in Java is similar to a method that is invoked when an object of
the class is created.
Unlike Java methods, a constructor has the same name as that of the class
and does not have any return type. For example,
class Test {
Test() {
// constructor body
}
}
Here, Test() is a constructor. It has the same name as that of the class and
doesn't have a return type.
Example: Java Constructor
class Main {
private String name;
// constructor
Main() {
[Link]("Constructor Called:");
name = "Programiz";
}
public static void main(String[] args) {
// constructor is invoked while
// creating an object of the Main class
Main obj = new Main();
[Link]("The name is " + [Link]);
}
}
Run Code
Output:
Constructor Called:
The name is Programiz
In the above example, we have created a constructor named Main() .
Inside the constructor, we are initializing the value of the name variable.
Notice the statement creating an object of the Main class.
Main obj = new Main();
Here, when the object is created, the Main() constructor is called. And the
value of the name variable is initialized.
Hence, the program prints the value of the name variables as Programiz .
Types of Constructor
In Java, constructors can be divided into three types:
1. No-Arg Constructor
2. Parameterized Constructor
3. Default Constructor
1. Java No-Arg Constructors
Similar to methods, a Java constructor may or may not have any parameters
(arguments).
If a constructor does not accept any parameters, it is known as a no-argument
constructor. For example,
private Constructor() {
// body of the constructor
}
Example: Java Private No-arg Constructor
class Main {
int i;
// constructor with no parameter
private Main() {
i = 5;
[Link]("Constructor is called");
}
public static void main(String[] args) {
// calling the constructor without any parameter
Main obj = new Main();
[Link]("Value of i: " + obj.i);
}
}
Run Code
Output:
Constructor is called
Value of i: 5
In the above example, we have created a constructor Main() .
Here, the constructor does not accept any parameters. Hence, it is known as
a no-arg constructor.
Notice that we have declared the constructor as private.
Once a constructor is declared private , it cannot be accessed from outside the
class.
So, creating objects from outside the class is prohibited using the private
constructor.
Here, we are creating the object inside the same class.
Hence, the program is able to access the constructor. To learn more,
visit Java Implement Private Constructor.
However, if we want to create objects outside the class, then we need to
declare the constructor as public .
Example: Java Public no-arg Constructors
class Company {
String name;
// public constructor
public Company() {
name = "Programiz";
}
}
class Main {
public static void main(String[] args) {
// object is created in another class
Company obj = new Company();
[Link]("Company name = " + [Link]);
}
}
Run Code
Output
Company name = Programiz
2. Java Parameterized Constructor
A Java constructor can also accept one or more parameters. Such
constructors are known as parameterized constructors (constructors with
parameters).
Example: Parameterized Constructor
class Main {
String languages;
// constructor accepting single value
Main(String lang) {
languages = lang;
[Link](languages + " Programming Language");
}
public static void main(String[] args) {
// call constructor by passing a single value
Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}
Run Code
Output
Java Programming Language
Python Programming Language
C Programming Language
In the above example, we have created a constructor named Main() .
Here, the constructor takes a single parameter. Notice the expression:
Main obj1 = new Main("Java");
Here, we are passing the single value to the constructor.
Based on the argument passed, the language variable is initialized inside the
constructor.
3. Java Default Constructor
If we do not create any constructor, the Java compiler automatically creates a
no-arg constructor during the execution of the program.
This constructor is called the default constructor.
Example: Default Constructor
class Main {
int a;
boolean b;
public static void main(String[] args) {
// calls default constructor
Main obj = new Main();
[Link]("Default Value:");
[Link]("a = " + obj.a);
[Link]("b = " + obj.b);
}
}
Run Code
Output
Default Value:
a = 0
b = false
Here, we haven't created any constructors.
Hence, the Java compiler automatically creates the default constructor.
The default constructor initializes any uninitialized instance variables with
default values.
Type Default Value
boolean false
byte 0
short 0
int 0
long 0L
char \u0000
float 0.0f
double 0.0d
object Reference null
To learn more, visit Java Data Types.
In the above program, the variables a and b are initialized with default
value 0 and false respectively.
The above program is equivalent to:
class Main {
int a;
boolean b;
Main() {
a = 0;
b = false;
}
public static void main(String[] args) {
// call the constructor
Main obj = new Main();
[Link]("Default Value:");
[Link]("a = " + obj.a);
[Link]("b = " + obj.b);
}
}
Run Code
Output
Default Value:
a = 0
b = false
Important Notes on Java Constructors
• Constructors are invoked implicitly when you instantiate objects.
• The two rules for creating a constructor are:
1. The name of the constructor should be the same as the class.
2. A Java constructor must not have a return type.
• If a class doesn't have a constructor, the Java compiler automatically
creates a default constructor during run-time. The default constructor
initializes instance variables with default values. For example,
the int variable will be initialized to 0
• Constructor types:
No-Arg Constructor - a constructor that does not accept any
arguments
Parameterized constructor - a constructor that accepts arguments
Default Constructor - a constructor that is automatically created by the
Java compiler if it is not explicitly defined.
• A constructor cannot be abstract or static or final .
• A constructor can be overloaded but can not be overridden.
Constructors Overloading in Java
Similar to Java method overloading, we can also create two or more
constructors with different parameters. This is called constructor overloading.
Example: Java Constructor Overloading
class Main {
String language;
// constructor with no parameter
Main() {
[Link] = "Java";
}
// constructor with a single parameter
Main(String language) {
[Link] = language;
}
public void getName() {
[Link]("Programming Language: " + [Link]);
}
public static void main(String[] args) {
// call constructor with no parameter
Main obj1 = new Main();
// call constructor with a single parameter
Main obj2 = new Main("Python");
[Link]();
[Link]();
}
}
Run Code
Output
Programming Language: Java
Programming Language: Python
In the above example, we have two constructors: Main() and Main(String
language) .
Here, both the constructors initialize the value of the variable language with
different values.
Based on the parameter passed during object creation, different constructors
are called, and different values are assigned.
It is also possible to call one constructor from another constructor.
We have used this keyword to specify the variable of the class.