Using Methods in Java
Using Methods in Java
In general, a method is a way to perform some task. Similarly, the method in Java is a collection
of instructions that performs a specific task. It provides the reusability of code. We can also
easily modify code using methods. In this section, we will learn what is a method in Java, types
perform a certain task or operation. It is used to achieve the reusability of code. We write a
method once and use it many times. We do not require to write code again and again. It also
provides the easy modification and readability of code, just by adding or removing a chunk of
The most important method in Java is the main() method. If you want to read more about the
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-
type, name, and arguments. It has six components that are known as method header, as we have
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
Public: The method is accessible by all classes when we use public specifier in our application.
Private: When we use a private access specifier, the method is accessible only in the classes in
which it is defined.
Protected: When we use protected access specifier, the method is accessible within the same
Default: When we do not use any access specifier in the method declaration, Java uses default
access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by its
name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left the
parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed.
Naming 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 adjective or noun. In the multi-word method name, the first letter of each word must
It is also possible that a method has the same name as another method name in the same class, it
Types of Method
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. Some pre-
defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any of the
predefined methods in our program, a series of codes related to the corresponding method runs in
Each and every predefined method is defined inside a class. Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we write inside the method. For
Demo.java
Output:
In the above example, we have used three predefined methods main(), print(), and max(). We
have used these methods directly without declaration because they are predefined. The print()
method is a method of PrintStream class that prints the result on the console. The max() method
is a method of the Math class that returns the greater of two numbers.
We can also see the method signature of any predefined method by using the link
https://docs.oracle.com/. When we go through the link and see the max() method signature, we
nonaccess modifier static, return type int, method name max(), parameter list (int a, int b). In the
above example, instead of defining the method, we have just invoked the method. This is the
Similarly, we can also see the method signature of the print() method.
User-defined Method
The method written by the user or programmer is known as a user-defined method. These
Let's create a user defined method that checks the number is even or odd. First, we will define the
method.
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
We have defined the above method named findevenodd(). It has a parameter num of type int. The
method does not return any value that's why we have used void. The method body contains the
steps to check the number is even or odd. If the number is even, it prints the number is even, else
Once we have defined a method, it should be called. The calling of a method in a program is
simple. When we call or invoke a user-defined method, the program control transfer to the called
method.
import java.util.Scanner;
int num=scan.nextInt();
//method calling
findEvenOdd(num);
In the above code snippet, as soon as the compiler reaches at line findEvenOdd(num), the control
Let's combine both snippets of codes in a single program and execute it.
EvenOdd.java
import java.util.Scanner;
int num=scan.nextInt();
//method calling
findEvenOdd(num);
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
Output 1:
12 is even
Output 2:
Let's see another program that return a value to the calling method.
In the following program, we have defined a method named add() that sum up the two numbers.
It has two parameters n1 and n2 of integer type. The values of n1 and n2 correspond to the value
of a and b, respectively. Therefore, the method adds the value of a and b and store it in the
Addition.java
int a = 19;
int b = 5;
}
//user defined method public static int add(int n1, int n2) //n1
int s;
s=n1+n2; return s;
Output:
Static Method
A method that has static keyword is known as static method. In other words, a method that
belongs to a class rather than an instance of a class is known as a static method. We can also
create a static method by using the keyword static before the method name.
The main advantage of a static method is that we can call it without creating an object. It can
access static data members and also change the value of it. It is used to create an instance
method. It is invoked by using the class name. The best example of a static method is the main()
method.
Example of static
method Display.java
show();
Output:
Instance Method
The method of the class is known as an instance method. It is a non-static method defined in the
class. Before calling or invoking the instance method, it is necessary to create an object of its
class. Let's see an example of an instance method. InstanceMethodExample.java public class
InstanceMethodExample
int s;
s = a+b;
return s;
}
}
Output:
Accessor Method
Mutator Method
Accessor Method: The method(s) that reads the instance variable(s) is known as the accessor
method. We can easily identify it because the method is prefixed with the word get. It is also
known as getters. It returns the value of the private field. It is used to get the value of the private
field.
Example
return Id;
}
Mutator Method: The method(s) read the instance variable(s) and also modify the values. We can
easily identify it because the method is prefixed with the word set. It is also known as setters or
modifiers. It does not return anything. It accepts a parameter of the same data type that depends
Example
this.roll = roll;
Student.java
return roll;
this.roll = roll;
return name;
this.name = name;
Abstract Method
The method that does not has method body is known as abstract method. In other words, without
an implementation is known as abstract method. It always declares in the abstract class. It means
the class itself must be abstract if it has abstract method. To create an abstract method, we use
//abstract class
{
//method impelmentation
void display()
System.out.println("Abstract method?");
obj.display();
Example
public class Main {
myMethod();
The void keyword specifies that a method should not have a return value.
Tip: If you want a 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
return 5 + x;
}
System.out.println(myMethod(3));
// Outputs 8
In Java, all method arguments are passed by value. This means when you pass a variable to a
method, Java passes a copy of the variable's value, not the original reference itself. Any changes
made to the parameters inside the method do not affect the original variable.
Key Points:
1. Primitive Data Types: When passing a primitive type (like int, float, double, etc.) to a
method, the method gets a copy of the value. Any changes to this value inside the method
2. Objects: When passing an object to a method, the method still receives a copy of the
reference to the object. The reference itself is passed by value, so any changes made to the
object's fields inside the method will reflect outside. However, if you change the reference
itself (make it point to another object), it won't affect the original object reference outside
the method.
modifyValue(num);
}
}
Explanation:
However, when we return to the main() method, the original value of num remains
unchanged because Java passed a copy of the value (10), not the actual variable.
class Dog {
String name;
Dog(String name) {
this.name = name;
modifyDog(myDog);
// Output: Max
Explanation:
Inside the method, we modify the field name of the dog object.
When we return to the main() method, the change to the name field is reflected because
the method received a copy of the reference to the same object. Changes to the object's
this.name = name;
this.name: The this keyword refers to the current instance of the Dog object being
created. It helps differentiate between the instance variable name of the class and the
The code this.name = name; assigns the value of the parameter name to the instance
variable name of the Dog object. This ensures that the dog's name is stored in the object.
Without this, it would be ambiguous whether you're referring to the instance variable name or
Key Takeaways:
Pass by Value for Primitives: The original variable remains unchanged outside the
method.
Pass by Value for Objects: The object's reference is passed by value, but changes to the
object's internal fields are reflected outside the method because both the original and the
method's parameter refer to the same object. However, if the reference itself is reassigned,
Method Overloading
Definition:
Method overloading allows multiple methods in the same class to have the same name but differ
in their parameter lists (number or types of parameters). It enables a method to perform different
1. Two-parameter method:
return firstIn;
} else {
return secondIn;
2. Three-parameter method:
result = secondIn;
}
result = thirdIn;
return result;
COMPLETE CODE
return firstIn;
} else {
return secondIn;
}
}
int result = firstIn; // Start by assuming the first number is the greatest
return result;
Key Points:
Both methods are named max but differ in the number of parameters.
When called, the compiler determines which method to execute based on the arguments
passed.
Example Calls:
Output:
9
Alternative Approach
Polymorphism
Definition: The ability of methods (or operators) with the same name to perform
Definition:
A menu-driven program provides a user with multiple options and processes the selected option
in a structured manner.
Example: Circle Calculations Program
Purpose: Enables the user to calculate and display the area or circumference of a circle
Structure:
1. Menu Options:
o Enter radius
o Quit program
3. Benefits:
import java.util.Scanner;
char response;
do {
// Display menu
switch (response) {
case '1':
System.out.println("10.00 a.m.");
break;
case '2':
System.out.println("1.00 p.m.");
break;
case '3':
System.out.println("11.00 a.m.");
break;
case '4':
System.out.println("Goodbye!");
break;
default:
Key Features:
Loop: Keeps displaying the menu until the user selects the "quit" option.
Key Takeaways
Menu-Driven Programs use structured menus and modular methods for better readability
and maintainability.
Polymorphism underpins both concepts, emphasizing reusability and adaptability in code
design.
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to
f) this can be used to return the current class instance from the method.
The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of ambiguity.
Let's understand the problem if we don't use this keyword by the example given below:
class Student{
int rollno;
String name;
float fee;
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
class TestThis1{
s1.display();
s2.display();
............
Output:
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same. So, we are
int rollno;
String name;
float fee;
this.rollno=rollno;
this.name=name;
this.fee=fee;
class TestThis2{
s1.display();
s2.display();
}
............
Output:
If local variables(formal arguments) and instance variables are different, there is no need to use
class Student{
int rollno;
String name;
float fee;
rollno=r;
name=n;
fee=f;
}
class TestThis3{
s1.display();
s2.display();
}}
............
Output:
It is better approach to use meaningful names for variables. So we use same name for instance
variables and parameters in real time, and always use this keyword.
2) this: to invoke current class method
You may invoke the method of the current class by using the this keyword. If you don't use the
this keyword, compiler automatically adds this keyword while invoking the method. Let's see the
example
class A{
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
class TestThis4{
A a=new A();
a.n();
}}
............
Output:
hello n
hello m
The this() constructor call can be used to invoke the current class constructor. It is used to reuse
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
class TestThis5{
A a=new A(10);
}}
............
Output:
hello a
10
class A{
A(){
this(5);
System.out.println("hello a");
A(int x){
System.out.println(x);
class TestThis6{
A a=new A();
}}
............
Output:
hello a
Method Overloading in Java
Method overloading in Java is the feature that enables defining several methods in a class having
the same name but with different parameters lists. These algorithms may vary with regard to the
number or type of parameters. When a method is called, Java decides which version of it to execute
depending on the arguments given. If we have to perform only one operation, having the same
Suppose you have to perform the addition of the given numbers, but there can be any number of
arguments if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three
parameters then it may be difficult for you as well as other programmers to understand the behavior
of the method because its name differs. Here's an explanation with real-life examples:
Math Operations:
In a math class, you might have multiple methods for adding numbers, each accepting a different
number of arguments:
3. return a + b;
4. }
6. return a + b + c;
7. }
8. }
Here, the add method is overloaded to handle both adding two integers and adding three doubles.
String Manipulation:
In a utility class for string manipulation, you might have overloaded methods for concatenating
strings:
4. }
7. }
8. }
These methods enable concatenating two or three strings together based on the number of
arguments passed.
File Operations:
In a file handling class, you might have overloaded methods for reading files with different
parameters:
7. }
8. }
These overloaded methods allow reading files with or without specifying the buffer size.
In Java, Method Overloading is not possible by changing the return type of the method only.
1) Method Overloading: changing no. of arguments
Method overloading in Java allows defining multiple methods with the same name but different
parameter lists. One common form of overloading is changing the number of arguments in the
method signature. In this example, we have created two methods, the first add() method performs
addition of two numbers, and the second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for calling
methods.
1. class Adder {
4. return a + b;
5. }
8. return a + b + c;
9. }
10. }
17. }
18. }
Output:
22
33
Method overloading in Java also allows changing the data type of arguments in the method
signature. Here's an example demonstrating method overloading based on the data type of
arguments: In this example, we have created two methods that differs in data type. The first add
method receives two integer arguments and second add method receives two double arguments.
2. class Adder {
5. return a + b;
6. }
10. }
11. }
18. }
19. }
Output:
22
24.9
Q) Why Method Overloading is not possible by changing the return type of method only?
Method overloading in Java is based on the method signature, which includes the method name
and parameter list. The return type alone is not sufficient to distinguish between overloaded
methods because Java does not consider the return type when resolving method calls. If two
methods have the same name and parameter list but different return types, the compiler cannot
determine which method to call based solely on the return type. Let's see how ambiguity may
occur:
1. // Class Adder contains overloaded methods to add numbers
2. class Adder {
5. return a + b;
6. }
9. return a + b;
10. }
11. }
14. // This line of code will cause ambiguity because both add methods have the same signature
16. }
17. }
Output:
^
1 error
should be called?
Note: Compile Time Error is better than Run Time Error. So, java compiler renders
compiler time error if you declare the same method having same parameters.
Yes, technically, it is possible to overload the main() method in Java, but it won't be considered as
the entry point for the Java Virtual Machine (JVM) to start the execution of the program. While
overloading the main() method is syntactically valid, it doesn't serve the purpose of being the entry
point for program execution. The JVM expects the standard signature public static void
main(String[] args) for the entry point. Any other overloaded main() method will be treated as a
regular method and won't be invoked by the JVM to start the program. Therefore, although
overloading main() is possible, it's not practically useful for program execution. Let's see a simple
example:
AD
1. // Class TestOverloading4 demonstrates method overloading with different parameter types and
no parameters
2. class TestOverloading4 {
9. }
13. }
14. }
Output:
One type is promoted to another implicitly if no matching datatype is found. Let's understand the
short datatype can be promoted to int, long, float or double. The char datatype can be promoted to
If there are matching type arguments in the method, type promotion is not performed.
1. class OverloadingCalculation2{
8. }
9. }
Output:
If there are no matching type arguments in the method, and each method promotes similar
1. class OverloadingCalculation3{
4.
7. obj.sum(20,20);//now ambiguity
8. }
9. }
Output:
One type is not de-promoted implicitly for example double cannot be depromoted to any type
implicitly.
Readability and Maintainability: Overloading allows methods to have the same name and different
parameter lists, which increases readability and comprehensibility of the code. It helps developers
to name the different functions in a good way so that other developers can easily understand the
Code Reusability: To avoid using too many methods with different names even when their
function is similar, method overloading makes it possible to reuse method names but have different
types or numbers of parameters. It causes the code to be reusable and, therefore, reduces code
duplication.
Flexibility: Method overloading gives the developer an advantage in creating methods which can
be called with any number of different parameters types or numbers. It offers such flexibility to
which permits objects of the same type to react differently to method calls depending on the
method's arguments. This behavior somewhat polymorphic, hence leads to modularity and
extensibility of code.
Simplifies API Design: In the case of API design, the method overload is simplifying the interface
as it serves multiple ways in which to interact with the same functionality. The API users can select
the most convenient method signature according to their needs and then create a more thoughtful
functions encapsulated within a class. Developers not only pick the same method name for similar
operations, but also the purpose of each method becomes clearer, as well as their intended use
cases.
Overriding in Java
Overriding in Java occurs when a subclass implements a method which is already defined in the
superclass or Base Class. The method in the subclass must have the same signature as in the
class Animal {
// Base class
"Animal is moving."); }
void eat() { System.out.println(
"Animal is eating."); }
// method
System.out.println("Dog is running.");
}
Output
Dog is running.
Animal is eating.
Dog is barking.
Explnation: The Animal class defines base functionalities like move() and eat().t he Dog class
inherits from Animal and overrides the move() method to provide a specific behavior Dog is
running. Both classes can access their own methods. When creating a Dog object, calling
Method overriding is a key concept in Java that enables Run-time polymorphism. It allows a
subclass to provide its specific implementation for a method inherited from its parent class. The
actual method executed is determined by the object’s runtime type, not just the reference
variable’s type. This dynamic behaviour is crucial for creating flexible and extensible object-
oriented designs.
class Parent {
// Inherited class
System.out.println("Child's show()");
// Driver class
class Kinap {
// show is called
obj1.show();
// POLYMORPHISM.
obj2.show();
Output
Parent's show()
Child's show()
Explanation: in this code the Child class inherits from the Parent class and overrides the show()
method, providing its own implementation. When a Parent reference points to a Child object, the
of polymorphism in Java.
An overriding method’s access modifier in a subclass can be more permissive (e.g., protected to
the public) than the overridden method in the superclass. However, reducing the access level
(e.g., making a protected method private) is not allowed and will result in a compile-time error.
// overriding method
class Kinap {
P.m2();
C.m2();
Output
If we don’t want a method to be overridden, we declare it as final. Please see Using Final with
Inheritance.
Example: Java program which shows the final method can not override.
class Parent {
// Can't be overridden
void show() {}
Output:
3. Static methods can not be overridden(Method Overriding vs Method Hiding)
When you define a static method with the same signature as a static method in the base class, it is
Subclass Instance method can override the superclass’s Instance method but when we try to
Subclass Static Method generate compile time when trying to override superclass Instance
method subclass static method hides when trying to override superclass static method.
class Parent {
{
System.out.println("From parent "
+ "static m1()");
void m2()
System.out.println(
{
System.out.println(
// Driver class
class Kinap {
obj1.m1();
obj1.m2();
Output
From parent static m1()
Private methods cannot be overridden as they are bonded during compile time. Therefore we
Example: This example shows private method can not be overridden in java
class SuperClass {
System.out.println(
System.out.println(
privateMethod();
System.out.println(
System.out.println(
privateMethod();
o1.publicMethod();
// method in SubClass
o2.publicMethod();
Output
From Java 5.0 onwards it is possible to have different return types for an overriding method in
the child class, but the child’s return type should be a sub-type of the parent’s return type. This
Example: Java Program which shows Covariant Return Type in Method Overriding.
class SuperClass {
{
System.out.println(
System.out.println(
obj1.method();
Output
We can call the parent class method in the overriding method using the super keyword.
Example: This example shows we can parent’s overridden method using super an.
// Base Class
class Parent {
// Inherited class
{
super.show();
System.out.println("Child's show()");
// Driver class
class Kinap{
o.show();
Output
Parent's show()
Child's show()
We can not override the constructor as the parent and child class can never have a constructor
with the same name(The constructor name must always be the same as the Class name).
Below are two rules to note when overriding methods related to exception handling.
Rule 1:
If the super-class overridden method does not throw an exception, the subclass overriding
method can only throw the unchecked exception, throwing a checked exception will lead to a
compile-time error.
Example: Below is an example of a java program when the parent class method does not declare
the exception
class Parent {
@Override
}
@Override
// compile-time error
Output
Explanation: this example shows that uper-class overridden method does not throw an
exception, the subclass overriding method can only throw the exception because the super class
Rule 2.
If the superclass overridden method does throw an exception, the subclass overriding method can
only throw the same, subclass exception. Throwing parent exceptions in the Exception
hierarchy will lead to compile time error. Also, there is no issue if the subclass overridden
Example: Java program to demonstrate overriding when superclass method does declare an
exception
class Parent {
}
}
// method
try {
p1.m1();
catch (RuntimeException e) {
try {
p2.m1();
catch (RuntimeException e) {
try {
p3.m1();
catch (Exception e) {
System.out.println("Exception caught: " + e);
try {
catch (Exception e) {
Output
Overriding and Abstract Method
Abstract methods in an interface or abstract class are meant to be overridden in derived concrete
The presence of a synchronized/strictfp modifier with the method has no effect on the rules of
overriding, i.e. it’s possible that a synchronized/strictfp method can override a non-
// multi-level overriding
// Base Class
class Parent {
// Inherited class
// Inherited class
System.out.println("GrandChild's show()");
// Driver class
class Kinap {
o.show();
Output
GrandChild's show()
1. Overloading is about the same method having different signatures. Overriding is about the
same method, and same signature but different classes connected through inheritance.
2. Overloading is an example of compiler-time polymorphism and overriding is an example of
run-time polymorphism.
specific implementations of methods defined in a parent class. This supports the “one interface,
enabling code libraries to call methods on new class instances without recompiling, while
maintaining a clean, abstract interface. It allows calling methods from derived classes without
and subclasses in a hierarchy, from general to specialized. The superclass provides common
methods for subclasses to use or override, ensuring flexibility while maintaining a consistent
interface. For example, in an employee management system, the base class Employee defines
methods like raiseSalary(), transfer(), and promote(). Subclasses such as Manager or Engineer
can override these methods with their own logic. This allows us to pass a list of employees, call
methods like raiseSalary(), and let each employee type execute its own implementation without
// of overriding in Java
// Base Class
class Employee {
// Inherited class
// Inherited class
// Driver class
class Main {
System.out.println(e.salary());
printSalary(obj1);
printSalary(obj2);
Output