Master java skills

Methods In Java

2. Methods

Methods define behaviour of a class. A method contains business logic which is executed when the method is invoked. Methods are the ways to manipulate objects data. Let’s take a look at the below example

Syntax of a method :

<access-modifier> <return-type><name-of-the-method> ({optional}<type-of-parameter><name-of-the-parameter>){ //method logic }

example1: public void displayPlayerInfo()

example2: public int addNumbers(int num1, int num2)

Anatomy of a method:

Access-modifier – tells about the accessibility of a method. A public method is available from everywhere. A private method is accessible only within the class.

Return Type – tells what type of value the method would return upon invokation. ‘Void’ means nothing will be returned. ‘int’ means integer type value will be returned from the method etc.

Name of the method – This gives method a name. Methods are invoked using this name only. We should give descriptive names for the methods. One should be able to understand the functionality of the method by just reading name. For Example, multiply name suggests that the method multiplies numbers. ‘displayPlayerInfo’ suggests that the method displays information about the player. Also, if method name consists of more than one word, use camelCase. Camel Case means first letter should be small and then first letter of the every word should be capital e.g. displayPlayerInfo().

Type of parameter – This defines the type of parameter the method expects. An empty paranthesis means no parameters are expected. Multiple parameters are separated with comma.

Parameter Name – This is the name of the parameter. Parameters are accessed within the methods using these names only.

Method body – The section of code that we write inside curly brackets is called method body. It is that part of the method where business logic is written.

Examples :

public void displayPlayerInfo() {}
public String getPlayerName(int playerId) {}
public int getPlayerAge(int playerId, String name) {}

package com.jts;

public class Player {

	private int id = 10;
	private String name = "Arjun";

	// This method is used to display player information
	public void displayInfo() {
		System.out.println("Player Id : " + id);
		System.out.println("Player Name : " + name);
	}

	public static void main(String[] args) {
		Player p = new Player();
		p.displayInfo();
	}
}
Output: 

Player Id : 10
Player Name : Arjun

In the above example, displayPlayerInfo() method prints player information. There is no business logic in here. Let’s see another example where we will get the multiplication of two numbers.

package com.jts;

public class Calculation {

	public int multiply(int num1, int num2) {
		return num1 * num2;
	}

	public static void main(String[] args) {
		Calculation c = new Calculation();
		int result = c.multiply(12, 4);
		System.out.println("Result = " + result);
	}
}

Output :
Result = 48

Method Signature

Method name along with the parameters list is known the signature of the method.

Note -> Return type is not considered part of method signature.

Access Modifier/Specifier

Access modifier or speicfier defines the visibility of a method. Following four types of modifiers are applicable to methods:

private : private methods are accessible only within the class.

protected : protected methods are accessible in the same package and all the subclasses whether in the same package or different package

public : public methods are accessible from everywhere meaning from all the classes in and from other packages.

default : default means when we do not specify any access modifier. Default methods are accessible only within the same package

Naming Convention for Methods

Method name should never start with a capital letter. Instead, it should follow camel case, like calculateSum(), displayPlayInfo() etc. First letter of the name should be small and then first letter of every word should be capital.

Aways try to keep the name of the method in the verb form of part of speech. It should signify an action. Examples are: multiplyNumbers(), runRace(), energizePerson(), boostImmunity(), printNumbers(), displayContent() etc.

Predefined Methods (language api methods)

Java api provides numerous predefined classes and methods in those classes. Such as String is an API class. There are many predefined methods in it. Like, equals(String anotherString), equalsIgnoreCase(String anotherString), contains(CharSequence s) etc.

User Defined Methods

Every method that we define are user defined methods.

Static Method

If we write static before a method, then method is called a static method. Static methods are associated with the class and can be accessed using the class name. There is no need to create an object of the class to access that method. We cannot access instance variables from inside the static methods.

package com.jts;

public class Player {

	private String name = "Arjun";
	public static String team = "India";
	
	public static void displayInfo() {
		Player p = new Player();
		System.out.println("Player name : " + p.name);
		//static attribute should be accessed using the class name
		System.out.println("Player team : " + Player.team);
	}

	public static void main(String[] args) {
		displayInfo();
	}
}
Output:

Player name : Arjun
Player team : India

Instance Method

Non static methods are known as instance methods. We have already seen examples of instance methods.

Abstract Method

Abstract method is the one for which we don’t give any definition. Meaning, we only declare a method but don’t provide its body. We have to write abstract after access modifier to declare a method as abstract.

Note -> We cannot keep abstract methods in a concrete class. The class also needs to be declared as abstract to keep abstract method.

package com.sks;

public abstract class SportsPerson {
      
      private static int playerId = 10;
      private static String name = "Arjun";
      
      public abstract void registerPlayer();

}