All About Methods in Java

0
77
Spread the love
  • 24
  • 34
  • 16
  • 12
  •  
  •  
  •  
  • 12
  •  
  •  
    98
    Shares

Method in Java:
Method in Java:

Method in Java:

A larger program can be broken down into pieces by dividing the complex program into 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 tasks grouped together under a block and given a name.So anywhere in our program we can replace these block of codes with this method name.This enables us to use the same code again and again at different part 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 represents actual values passed to 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 class type.

The return type is the type that the method returns when 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 it’s implementation, instead we need to know the interface.
  • The interface should be 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 part as the contract of the subroutine.The semantic component specifies exactly what task the method will accomplish. The syntactic part gives the 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
}

Method calling general Syntax:

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

a method can not be passed as an argument to another method or in 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.

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 return statement.
  2. We have to write void instead of any datatype.

The return statement in 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 form of object.So what we pass via argument list is/are the handle(s)[Exception-the primitive datatypes(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 gets 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 up casting 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 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 other 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.

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 to execute the subroutine as the result may be wrong or the program may crash.
    • The post condition 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 post condition. So a subroutine comes with a set of precondition and post conditions.
    • They can be part of a javadoc commands 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 an statement.To throw a statement of appropriate type we must create 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);
}
}
 

output of the code:

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
  • 24
  • 34
  • 16
  • 12
  •  
  •  
  •  
  • 12
  •  
  •  
    98
    Shares

LEAVE A REPLY

Please enter your comment!
Please enter your name here