BIG
DATA

JAVA

METHODS IN JAVA

Read more about »
  • Java 9 features
  • Read about Hadoop
  • Read about Storm
  • Read about Storm
 

A Java method is a collection of statements that are grouped together and is referred to by name. It can be called or invoked anywhere in a program simply by using the method's name.

Now we know that each method has its own name and when that name is used in a program, the execution of the program branches to the body of that method. When the method is finished, returns control to the caller from which it was called, and the program continues on to the next line of code. A method is finished when a return statement is executed or it reaches the ending closing brace.

Here is a simple method example:


public class ScoreBoard{
    public void display(String score) {
        System.out.print("Score is " + score);   //prints the the score.
    }
}

In the above we have defined a method called display inside ScoreBoard class. 'display' method takes a single parameter called 'score' which is used to print it to console inside the method. 'display' method does not return any value.

Why would you want to create new methods?

A program becomes unmanageably long in the course of development. Methods are helpful for breaking it up into pieces. Also manytimes you want a program to do the same thing again and again in several different places of a program. In such situation defining a method can be helpful. Methods are time savers, in that they allow for the repetition of sections of code without retyping the code. The use of methods will be your first step in the direction of modular programming.

There are two basic types of methods:

  • Built-in: Build-in methods are part of the compiler package, such as System.out.println( ) and System.exit(0).
  • User-defined: User-defined methods are created by you, the programmer.

Defining methods

The definition of a method follows the following template.

public <returnType> <methodName>(<paramType> <paramName>) {
    //body Of Method
}

example,

public void display(String score) {
	//body of the method
}

The only required elements of a method declaration are the method's return type, name, a pair of parentheses, (), and a body between braces, {}.

Following are the method components:

  • Modifiers:public, private, or others.
  • Return type:the data type of the value returned by the method, or void if the method does not return a value.
  • Method name:name of the method.
  • Parameter list:a comma separated list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses.
  • Exception list:will explain this in exception chapter.
  • Method body:the method's code, goes here.

In the above,

  • public : modifier
  • void : return type
  • display : method name
  • String score : parameter
Naming a Method

Method names should be a verb in lowercase. If a method name is of multi-word, then name should begin with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word names, the first letter of each of the second and following words should be capitalized. Usually, a method has a unique name inside its class. But method may have same name as other methods, this is called as method overloading, which is explained later chapter in OOP. Here are some examples of method names:

move
display
compare
getName
getData
printData
isEmpty

Method Parameters

Using method parameters you can pass values to the method, on which the method can operate. Parameters are declared inside the parentheses after the method name in a comma separated list manner, preceded by their data types.

In the above example,

public void display(String score) {
	System.out.print("Score is " + score);   //prints the the score.
}

variable score is available within display method which will refer to the value it is assigned when calling the method.

ScoreBoard myScoreBd = new ScoreBoard();
myScoreBd.display(35);
ScoreBoard otherScoreBd = new ScoreBoard();
otherScoreBd.display(141);

In above code 'display' method will be executed twice, first time with 'score' variable assigned to 35 and second time to 141. So 'myScoreBd' will display 35 and 'otherScoreBd' will display 141. Output will be,

Score is 35
Score is 141

If you want to pass more than one paramter, then list each parameter's type and name in the method declaration's parentheses, separated by commas. For example,

public void display(String firstInningsScore, String secondInningsScore) {
	System.out.print("Score in first innings is " + firstInningsScore + " and in second innings is " + secondInningsScore);
}

Note:In java, when calling a method, the value assigned to the parameter is copied into the parameter variable. Some call this technique for passing parameters as call by value. The other alternative to call by value is call by reference, where changes to the parameter variable also affect whatever variable is specified in the parentheses. Java does not have any support for call by reference, but some other programming languages do.

Below example will clarify the above note..

public class ScoreBoard {

	public static void main(String [] args) 
	{
		int myScore=5;
		display(myScore);
		System.out.println("Score in main method:" + myScore);
	} 

	static void display(int score){
		System.out.print("Score is " + score); 
		score=10;
	}
}

output will be,

 
Score is 5
Score in main method:5

See how varibale value in main method is not changed after the method call.

final

Just like a variabe, method parameter can be declared as final.The value of a final parameter cannot be changed.

public void display(final String score) {
	System.out.print("Score is " + score);
	score=10;
}

If you try to assign value to a final parameter, you get the following error.

methods

Local variables

A variable can also be declared inside the method, and such variable is called as Local variable. A local variable can be used just like any other variable, but it is only accessible inside the method.

public void display() {
	String firstInningsScore = 99;
	String secondInningsScore = 173;
	System.out.print("Score in first innings is " + firstInningsScore + 
		" and in second innings is " + secondInningsScore);
}

Again, just like method parameter, local variable too can be declared as final

Method Return Types

When a method is invoked (called), a request is made to perform some action, such as setting a value, printing statements etc. But some times method is called to do some calculations or process the data and return it to the called method. Hence a Java method could return a value.

public int getScore() {
	// some java statements
	return 25;
}

The above method returns the score as 25 when called. Notice int keyword after public and before method name. It indicates that the method will return a value of type int. Then check the return statement, which determines what value is returned by the method. You can return any primitive type or any object from a Java method.

It is not necessary to have only one return statement in a method. A method can have multiple return statements. However only one return statement can be executed. Once a return statement is executed, no more code in that method is executed. The program control goes back to the code that called the method.

public int getScore(String innings) {
	if(innings.equals("FIRST"))
	{
		return 25;
	}
	return 49;
}

In this, if statement inside the method tests whether method parameter innings is "FIRST" or not. If method parameter innings is "FIRST" then it will return 25 and skip the rest of the statements in the method. If string parameter is not equals to "FIRST", then the method skips the body of the if statement. It then executes the second return statement, returning 49.

How to invoke (call) a method

When a method is invoked (called), a request is made to perform some action. The code to invoke the method contains the name of the method to be executed and any needed data that are specified in the method's parameter list. And if a method to be called belongs to other class then an object reference should be preceded before method name.

You invoke (call) a method by writing down the calling object followed by a dot, then the name of the method, and finally a set of parentheses that may (or may not) have information for the method.

public class ScoreBoard {

	public static void main(String [] args) 
	{
		Score individualScore = new Score();
		int myScore = individualScore.getScore();
		display(myScore);
	} 

	static void display(int score){
		System.out.print("Score is " + score); 
	}
}

Here, the method 'getScore' belongs to 'Score' class, hence it is called by writing down the Score object(individualScore) followed by a dot and getScore method name. However display method is in same class, so it is called without the object reference.

Method Overloading

When a class has two or more methods by same name but different parameters, it is known as method overloading. Method Overloading is covered in more detail in the text on OOP section.

Static Methods

Static Method is a method which belongs to the class and not to the object(instance).A static method can access only static data. It can not access non-static data (instance variables). Static Methods is covered in more detail in the text on Static section.