All About Methods in Java

Spread the love

Method in Java:
The method in Java:

The method 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 together 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
//like
main(String args[]) throws ArrayOutOfBoundException,IllegalThreadStateException
 

Method implementation


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

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:

object_reference.methodName();
object_reference.methodName(paramName1,paramName2......,paramNameN);
//Example:
Student std=new Student();
std.setName("abc");
std.getName();

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:

byte->short->int->long->float->double.

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. 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[])
{
    myNumberTest(-1);
}
}
 

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.

Read Method overloading here for more about this technique.

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.

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 varargs in which we are going to pass the specific type of arguments.
An ellipsis(…) is the key to varargs 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)
{
System.out.println(details);
}
} 
public static void main(String args[])
{
testVarargs("MydigitalVoice","abc123","hello@mydigitalvoice.in");
}
}
 

At compile time the String… registrationDetails are converted to String[] varargs. 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.

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.

Cleanup:

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 there is some activity that must be performed before it reclaims the memory. We must perform that activity by ourselves. We can create our own 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 method as well. When we call a method and there are more than one method with the same name, the compiler will automatically picks the one matches the data types of the arguments, we are passing.

Read here for more about method in java.To call a method we need to know it’s name and parameters.They are defined in the method signature.Java allows us to call methods with 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 objects and methods by using their names.We express same word for 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 same name with different context is referred 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 filename as a String

Defining methods with 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 nae as class name,thus method overloading is essential to allow the same method to be used with different argument types.Although method overloading is 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 print() method with different data.
Example:


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 separate identifier for each variant of point.Instead the same name can be used and the methods are overloaded by client of their different parameter lists.The java compiler distinguishes among overloaded methods on the basis of 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 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();
while(i!=9)
{
MyTree t=new MyTree(i);//calling overloaded method
t.infoAboutTree();
t.infoAboutTree("rose");
i++;
}
}
}
class MyTree{
int height;
MyTree(){
System.out.println("Planting my tree");
height=0;
}
MyTree(int i){
height=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");
}
}

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);
//and 
public int calculateArea(int a,int b);
 

Both these statements will call the same method with 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 other 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 same in terms of method overloading concept. In this case,compiler will raise a flag stating that the method is already defined.This is why return type is not considered during method overloading.So it is illegal to have two methods with 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 behavior of methods or polymorphism.

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();
a.call();
}
}
class A{
void call(){
System.out.println("From A");
}
}
class B extends A{
void call(){
System.out.println("From B");
}
}

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 actually 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 instance of new classes without recompiling while maintaining a class as abstract interface.

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.


Spread the love
  •  
    1
    Share
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Leave a Comment

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

Scroll to Top