Learn Methods in Java in a Quick Manner

The methods in Java:

A larger program can be broken down into pieces by dividing the complex program into a small chunk of codes. These codes can be inside a block or a method if they are used multiple times. So a method consists of the instructions for carrying out a certain task grouped under a block and given a name.

So anywhere in our program, we can replace these blocks of codes with this method name. This enables us to use the same code again and again at the different parts of the program. This can be called from another class another method (depends on the access specifier though). This feature enables us to use small functions again and again without rewriting the same.
Parameter names are arbitrary but meaningful identifiers for types that are passed to the methods. Methods may or may not have parameters.

Arguments represent actual values passed to the method when it is executed so that it can use them for some specific purpose within the implementation of the method.The data types defined in the implementation language of the class or it can be a class type.

The return type is the type that the method returns when the method is finished its execution. The return is also primitive data types(defined in Java). On the other hand, there may not be any return type. In that case, it will be void. Void says that the method does not return any value when it finishes its execution.
So, in a nutshell, a method is a black box as we don’t know or can’t see what is inside of it. As a result, a method needs an interface to deal with another part of the program.

A well-structured method will have the followings:

  • The interface of a method should fairly straight forward, well defined and easy to understand.
  • To use a method, the coder should not need to know anything about its implementation, instead, we need to know the interface.
  • The interface should be the same even if we are changing the internal implementation of the method. This feature will not breakdown the source code written on top of this method.
  • The implementation of a method should not need to know anything about the larger system in which the method will be used.
  • A method’s interface includes syntactic and semantic parts as the contract of the subroutine. The semantic component specifies exactly what task the method will accomplish. The syntactic part gives legal coding.
  • One method can call another method but one method can not physically present inside another method.

Method declaration syntax:

(access specifier)(return type)methodName(parameterList) throws ExceptionLists
main(String args[]) throws ArrayOutOfBoundException,IllegalThreadStateException

Method implementation

access_specifier modifier returnType methodName(parameterList) throws ExceptionLists{
public static void main(String args[]) throws ArrayOutOfBoundException,IllegalThreadStateException{

Each of the formal parameters of a method must be preceded by a type name even if there is more than one parameter of the same type. Corresponding arguments must match the type of their corresponding formal parameter.

Method calling general Syntax:

Student std=new Student();

The method can not be passed as an argument to another method or in the constructor. Instead, an object reference is passed to the method or constructor so that the object reference is made available to that method or constructor or to other members of the class that invokes the method.

The single parameter is replaced by a computable value i.e an argument when the method is invoked and executed.

In some cases, an automatic typecast is performed by java. For an argument of type int, if we push parameter type double, java does an auto-upgrade and cast int value to double. The type conversion or typecasting happens in the following order:


Argument vs Parameter in a method

While we invoke a method, the parameters are known as actual parameters and known as arguments but when we define a method, the parameters are known as formal parameters and known generally as parameters. These parameters are local to methods.

Parameters of a primitive Type

Parameters are given in parentheses after the method name in the heading of a method definition. A parameter of a primitive type such as int, double, char is a local variable.

When the method is invoked, the parameter is initialized to the value of the corresponding argument in the method invocation. Th\is mechanism is called call by value parameter mechanism.

The argument in a method invocation can be a literal constant, such as 4 or ‘B’ a variable or any expression that yields a value of an appropriate type.

Return types of a method:

Java methods can return one of the following:

  • Void- if the method does not return anything
  • One of the java’s primitive datatypes
  • A class object

The return keyword has two objectives:

  1. It indicates that the method is done, no statement after return will be executed.
  2. It produces a value and passed right after the return statement.

If we wish to return nothing from a method then we can do the followings:

  1. We have to remove the return statement.
  2. We have to write a void instead of any datatype.

The return statement in the second and third cases must match the return type specified in the deceleration of the method. In that, it must return a value of the same type as the return type. If stated void there should not be any return statement in the method body.

The argument list

The method argument list specifies what info we will pass into the method. The argument list is nothing but the form of the object. So what we pass via argument list is/are the handle(s)[Exception-the primitive data types(boolean, char, byte, short, int, long, float, double)].

The argument list can be empty. In general, when a method is called, the actual parameters in the method call statement are evaluated and the values are assigned to the formal parameters in the method’s definition. The body will then get executed.
A formal parameter must be a name with some valid type just like a normal variable. The type of the actual parameter must be one that could legally be assigned to the formal parameter with an assignment statement. In this method of operation upcasting is allowed like int value from actual parameter can be passed to double of formal parameter or int can be assigned to double.

See also  Class LinkageError in Java: Quick Guide In Just 5 Minutes

A bad style of coding is to assign the formal parameters outside of the method. Some places, even it is allowed to create confusion later. This fundamental issue of misusing formal parameters may create unnecessary bugs. We need to understand formal variables are not independent. These values should come from another method.

int getSize(String str)
return str.length();

This argument is of type String and called str, passed into the method to find the size of str to the method called getSize().length() method is defined in the String class that returns the number of characters present in the string.

this parameter

Within a method definition, we can use the keyword as a name for the calling object. If an instance variable or method in the class is used without calling object, then it is understood to be the calling object.

Accessor and Mutator method

Accessor methods allow us to use to obtain data from a class. The accessor method often starts with ‘get’ words like getValue(),getMonth() etc. The Accessor methods need not always return the value each instance variable but they must return something equivalent to the value.

Mutator methods allow us to change the data in a class object. Mutator methods often start with a word ‘set’ like setValue(),setData() etc. The Mutator method can return a boolean value to assure the user that the operation (set value) is successful.

A class generally provides public accessors and mutators methods.

General Subroutine/method contract

    • The precondition of a subroutine is something that must be true when the subroutine is called to work it correctly. This is the primary part of the contract. If we do not meet the contract correctly, there is no point in executing the subroutine as the result may be wrong or the program may crash.
    • The postcondition of a subroutine is another side of the contract. It is something that will be true after the subroutine has run(if the precondition is met). Subroutines are often described by comments that explicitly specify their precondition and postcondition. So a subroutine comes with a set of precondition and postconditions.
    • They can be part of a Javadoc command as well as @precondition or @postcondition tags.
    • methods set up a contract with the specified details like -modifier, return type, method name, parameter list etc.but if the caller of the method violets the contact the method can intercept that and can throw a statement. To throw a statement of the appropriate type we must create an object and have a throw statement.like -IllealArgumentException(“error message”)

public class MyTest{
static void myNumberTest(int value)
if (value<=0)
    throw new IllegalArgumentException("value must be greater than zero");
public static void main(String args[])

the output of the code:

$javac MyTest.java

$java -Xmx128M -Xms16M MyTest Exception in thread “main” java.lang.IllegalArgumentException: The value must be greater than zero at MyTest.myNumberTest(MyTest.java:5) at MyTest.main(MyTest.java:10) so if this method gets a negative or zero value, it will immediately terminate the execution by throwing an exception.

Argument Passing mechanism:

Arguments can be passed in the following two ways:

  • Call by value.
  • Call by reference.

If a primitive type ( int, float, long etc ) variable is passed to a method as an argument, The mechanism is done by call-by-value approach.

If an object is passed to a method, is passes an object reference. The object reference is also passed by using call by value technology. Remember as the value, that is being passed refers to an object, the copy of that value will refer to the same object as the argument.

Reference variable and formal parameter of a method in case of passing reference variable always refer to the same object. So any alteration to the formal object using formal parameter will be reflected in the reference variable.

Interestingly. If we assign a new reference in the formal parameter. Inside the method, the fast reference variable will not be able to catch up with the changes.

Java supports two types of methods-

  • Instance Methods
  • Static Methods

Instance Methods:-

These are normal methods. They can be involved via creating an object ( Even if we have the instance method call inside a static method.

Static Method:-

Static methods can be accessed and involved by using objects or class name. Static methods have only access to static members. One static method can directly call another static method if without an object or class name if they both belong to the same class.

What Is Public Static Void Main Method in Java?

The main method in Java

For a standalone java program, the class name should be the same as the file name. we will get a compilation error if otherwise. The class should contain a main() method with the given signature:

public static void main(String[] args){}

Conceptually every java program must include a main() method to run independently.main() is the starting point or triggering point for the interpreter to begin execution. A java program can have n-numbers of classes but only one of them includes a main() method to initiate the execution.

public-> is available for the world to use.
String[] args->It declares a parameter named args of the type String array. The argument to the main is an array of String objects. In the IDE model of development, they will never be used in general, but they hold the arguments invoked on the command line.
Static: The static keyword declares this method /variable as one that belongs to the entire class and not part of any object of the class. The main() method must always be declared as static since the interpreter uses this method before any objects are created. Non-static things belong to the object. If the main is non-static, we can not have the main method until we create an object. But when we start java code, no objects have been created yet. The statements that are executed in the main method start creating objects.
void–>this modifier declares that the main() method does not return any value.

Command Line Arguments:-

During runtime, if we want to pass some information into our program, we use command line arguments. These information’s goes to the main( ) method as a string.

To access the command-line arguments the main ( ) method needs to read the string.

Methods with Varargs in Java

All About Methods with Varargs in Java:

Varargs represent variable-length arguments in the method. This makes java simple yet very powerful.

The general syntax is given as:

<access specifier><return type>methodName(<argument type>... arguments)

This method contains an argument referred to as var args in which we are going to pass the specific type of arguments.
An ellipsis(…) is the key to var args and argument is the name of the variable.

public void registration(String userName,String password,String emailId);
//can be written as:
public void registration(String... registrationDetails)

String… registrationDetails specifies that we can pass any number of String arguments to the registration() method.
How to retrieve the values:

class Registration{
testVarargs(String... registrationDetails)
for(String details:registrationDetails)
public static void main(String args[])
testVarargs("MydigitalVoice","abc123","[email protected]");

At compile time the String… registrationDetails are converted to String[] var args. we can pass an array of Strings to the methods. Varargs does not generate any compile-time errors even if an empty argument is passed as a parameter to the method.

See also  Class Modifier in Java

What is the Finalize method in Java?

Finalizer Method:

when a constructor initializes an object, the mechanism is called initialization. Similarly, java supports one more method just opposite to this, called finalization. Java garbage collector frees up memory used by the objects. But objects may hold other nonobjects (not created by Java new operator) resources(like file descriptor, window system fonts, etc).

The garbage collector can not free up these items as they as not created by the new operator. To reclaim such memories, the finalize() method is used. The Finalize () method needs to define explicitly.

If an object performs some specific actions before it is destroyed, In those cases, we will use the finalize method. The process of clean up ( file handler, free up some resources etc) is called Finalization.


protected void finalize( ){
// all clean up code here

We can use the public instead of protected too.


Many times programmers forget to clean up memory. Nobody wants to clean up the small chunk of memory for int or character like this approach. To free up the memory java came up with a concept called Garbage collector to reclaim the memory of objects those which are no longer in use.

But garbage collector can only reclaim memory for objects which are created by ‘new’ operator. If some program is occupying memory using some other way, Garbage collector won’t be able to reclaim those memories. To handle such conditions, Java has provided a method called finalize(). This method can be defined for any class.

How does it work?

When the Garbage collector is ready to release the storage of the object, it calls the finalize() method first. And only the next Garbage collection pass will reclaim the memory for the object. We can override the finalize() method by redefining the method.

We have to understand the below points while working with Garbage Collector:

  1. Garbage collection does not object to destruction. As java has no concept for destructor for clean up memory. It just ensures if some activity must be performed before it reclaims the memory. We must perform that activity by ourselves. We can create our methods to clean up the memory.
  2. All objects may not get garbage collected. It may so happen that our program never faces the memory shortage issue(maybe the code is too small and the available memory is too high).In that case, garbage collectors may reclaim the memory. So after the termination of the program, the memory is returned to the Operating system. The garbage collection process has some overhead, in the above way we never have to incur the expense.
  3. Garbage collection is not only about memory reclaim. If we use as a synonym of memory release the finalize has to be the same.

The role of Finalize():

Now if we create some other objects in our code and call finalize() method, will they be released? No, it won’t. The garbage collector will take care of the release of other objects in the memory, irrespective of how the objects are created. Since everything in java objects, in that case where we will define the finalize() method?

Well,Java supports native methods(C,C++ etc).In these native languages, there are ways to allocate memories like calloc(), malloc(). Unless we call free() method, the storage will never be released, causing a memory leak in java code via native methods. We can define the C language free() method in the other function where all our functions were defined. It is a best practice to write free() method inside finalize() method.Java does not allow us to create local objects rather all objects should be created using the new operator.

Method Overloading Concept Simplified In Java

In Java, a method is distinguished by its name, by the number of types and position of the arguments. This is not for only constructors. It applies to the method as well. When we call a method and there is more than one method with the same name, the compiler will automatically pick the one matches the data types of the arguments, we are passing.

If a method overloading can be resolved by the compiler during compilation time(compilation can check and decide which version of the method needs to be invoked), it is called static binding or compile-time polymorphism.

Incase compiler cannot decide which version of the method needs to invoked, the JVM will resolve this during the runtime. It is called dynamic binding or runtime polymorphism.

Java supports to have more than one method with the same name but differs-

  • Number of parameters
  • Types of parameters
  • Order of parameters

This phenomenon is called method overloading.

Note – In case, if the type of the actual parameters is passed and they do not exactly match with the formal parameters of the overloaded methods. Then the parameters are promoted to the next higher type. This up-gradation continues until a proper match is found.

If no proper match is found, Java flags an error during compilation.

To call a method we need to know its name and parameters. They are defined in the method signature.Java allows us to call methods with the same name with different parameter lists. This mechanism is called Method overloading. Off course these methods are semantically related. However method signature does not include the method’s return type. A method is a name of an action for an object(refers to a String). We refer to objects and methods by using their names. We express the same word for a different meaning. Like

  • open a box
  • open a file
  • open a container

They all express the action open but context changes from line to line. In java, the same phenomenon can be replicated and the same name with different context is referred to as overloading. Methods with the same name but with different parameters (arguments) list are said to be overloaded. The term overloading, as it applies to the method name has more than one meaning. The concept of overloading acme from constructor overloading.Because the constructor name is predetermined by the name of the class so there could be only one constructor. That means we can create an object with only one way. There could be a chance that the object can be created in different ways. So for file opening, we can have

  1. default constructor
  2. one argument that takes a filename as a String

Defining methods with the same name and different argument type is called method overloading. Overloaded methods may have different return types but only if they have different arguments.

class OpenFile{
public OpenFile(){...}//default constructor
public OpenFile(String fileName){...}//argumented constructor

Here both the constructors as they have the same name as the class name, thus method overloading is essential to allow the same method to be used with different argument types. Although method overloading is a must for constructors, it is a general convenience and can be used with any method.

In real-time, when we debug an application we use the print() method with different data.

void print(boolean b);//prints boolean value
void print(char c);//prints char value
void print(char[] b);//prints an array of characters
void print(String sb);//prints String value
void print(Object obj);//prints object value
void print(double d);//prints double value
void print(float f);//prints float value
void print(int i);//prints int value
void print(long l);//prints long value
so on...

It would be very tedious, inconvenient to have a separate identifier for each variant of the point. Instead, the same name can be used and the methods are overloaded by a client of their different parameter lists. The java compiler distinguishes among overloaded methods based on their parameter lists. The method return type is not considered when methods are overloaded. Thus even if there are two different return types, if they have the same argument list, they would not be considered as method overloaded.
an Example:

public class OverloadingTest{
public static void main(String []args){
int i=0;
new MyTree();
MyTree t=new MyTree(i);//calling overloaded method
class MyTree{
int height;
System.out.println("Planting my tree");
MyTree(int i){
System.out.println("My tree is growing "+height+" inch tall");
void infoAboutTree(){
System.out.println("My tree is growing "+height+" inch tall");
void infoAboutTree(String myTree){
System.out.println("My tree"+myTree+" is growing "+height+" inch tall");

the output of the code:
$javac OverloadingTest.java
$java -Xmx128M -Xms16M OverloadingTest
Planting my tree
My tree is growing 0 inch tall
My tree is growing 0 inch tall
My treerose is growing 0 inch tall
My tree is growing 1 inch tall
My tree is growing 1 inch tall
My treerose is growing 1 inch tall
My tree is growing 2 inch tall
My tree is growing 2 inch tall
My treerose is growing 2 inch tall
My tree is growing 3 inch tall
My tree is growing 3 inch tall
My treerose is growing 3 inch tall
My tree is growing 4 inch tall
My tree is growing 4 inch tall
My treerose is growing 4 inch tall
My tree is growing 5 inch tall
My tree is growing 5 inch tall
My treerose is growing 5 inch tall
My tree is growing 6 inch tall
My tree is growing 6 inch tall
My treerose is growing 6 inch tall
My tree is growing 7 inch tall
My tree is growing 7 inch tall
My treerose is growing 7 inch tall
My tree is growing 8 inch tall
My tree is growing 8 inch tall
My treerose is growing 8 inch tall
Why return type is not considered during overloading?

public void calculateArea(int a,int b);
public int calculateArea(int a,int b);

Both these statements will call the same method with the different return type. However, we can call a method and ignore the return value(referred as calling a method for its side effects since we do not want the return value.Rather we are interested to see another effect of the method call).In this case, java will be confused to understand which method -calculateArea(int a, int b) to call. Also, these two methods are the same in terms of method overloading concept. In this case, the compiler will raise a flag stating that the method is already defined. This is why the return type is not considered during method overloading. So it is illegal to have two methods with the same signature but different return type in the same class. It will be a syntax error for a class to contain two such methods.
This phenomenon is often called as polymorphic behaviour of methods or polymorphism.

See also  Abstract Class SocketImpl in Java

Dynamic Method Dispatch Concept Simplified in Java

Methods can be called in java dynamically. Whenever a method is called on an object reference, the declared type object reference is checked at compile-time to make sure that the method definition exists in the declared class. At run time the object reference could be referring to an instance of some subclass of the declared reference type. This phenomenon is referred to as Dynamic Method Dispatch in java.
An Example

public class WhoTest{
public static void main(String []args){
A a=new B();
class A{
void call(){
System.out.println("From A");
class B extends A{
void call(){
System.out.println("From B");

The output of the code:
$javac WhoTest.java
$java -Xmx128M -Xms16M WhoTest
From B
Here we have declared a variable to be of type A but stores reference to an instance of class B.When we call a method call(), java notices that the reference is an instance of class B. So it calls Class B’s call() method instead of A’s. This helps to ensure reusability and robustness. This is how we call methods from libraries on an instance of new classes without recompiling while maintaining a class as an abstract interface.

By this mechanism, Java resolves the overridden instance method at runtime. ( Java does not do it in compile time). This is how Java implements runtime polymorphism.

A superclass reference variable can refer to a subclass object. Java resolves calls to an overridden method at runtime. When an overridden method is called through a superclass object, Java determines the version of the method that needs to be executed based on the type of the object that initiates the method call.

Dynamic method dispatch depends on the type of object that is being referred to but does not depend on the type of reference.

Dynamic method dispatch helps Java to support runtime polymorphism. Polymorphism allows a general class to specify a certain method, which is common to all its derivatives. This also allows child classes to define the specific implementation of some or all of these methods.

Methods and Java API vs Security

The Java API is a set of runtime libraries that provides us with a standard way to access the system resources on the host computer. When we run a Java Program, the virtual machine initially loads the Java API class files(they are referred by our code).

Now the combined class files(Java API files and our code files) then again combined with other libraries that contain native methods. This whole set of libraries then sent to execute.

The class file of the Java API file is specific to the underlying host platform. Before a platform hosts Java, need to provide the API’s functionality as per the platform. To gain access to the native resources of the host, Java calls the native methods. As Java’s API library does this, we do not need to think and implement the native methods.

Java virtual machines and the  Java API are implemented specifically for each particular host platform, but for a Java code, the Java API looks same. Hence it becomes platform-independent. Apart from these, Java API libraries also contribute to Java’s security model.

Before executing any method that may work on the underlying host system, the methods of Java API check the required permission by using the security manager. A security manager grants permission to work with any underlying resources.

If a method does not get approval from the security manager it just refuses to perform the said operation. Access controller is another object that performs the same operation after the release of Java 1.2. The specific class inspects the stack to check if a specific operation can be done.

Share and Enjoy !

Leave a Reply

Your email address will not be published. Required fields are marked *