In Java, a method is a set of statements performing a specific task. Methods organize code into manageable, reusable pieces, enhancing readability. They are part of a class and can be called by other code.
In Java, method is a set of statements that performs a specific task. Methods are used to break down a program into smaller, manageable pieces of code, making code more organized, reusable, and easier to understand. Methods are typically associated with a class and can be invoked by other parts of the program.
Advantages of Methods:
When defining a method in Java, we need to take care of methods parts to ensure the method is well-designed and effective.
Key components of method:
Access Modifier:
It determines the accessibility of the method from within package of other classes and outside of the packages too.
Common access modifiers include public, private, protected, and package-private (no explicit modifier). Example:
private void netSal() {
// Method implementation
}
Return Type:
It specifies the type of value the method returns, if any. If the method doesn't return a value, its return type is void.
Example:
public int findSum(int num1, int num2) {
return num1 + num1;
}
Method Name:
A descriptive name that represents the action or behaviour performed by the method.
It should follow Java naming conventions (camelCase).
Example:
public void printMessage(String message) {
System.out.println(message);
}
Parameter List:
It specifies the data the method expects to receive when it's called.
Parameters are optional and can be of any data type.
Example:
public void findSum(int num1, int num2) {
System.out.println(num1 + " + " + num2 + " = "+(num1+num2);
}
Method Body:
It contains the actual implementation of the method, including statements to perform a specific task. Enclosed within curly braces {}.
Example:
public int findMax(int num1, int num2) {
int max = num1;
if (num2>max) {
max=num3
}
return max;
}
Documentation (Optional but recommended):
Comments that provide information about the method's purpose, parameters, return value, and any side effects.
It helps other developers understand how to use the method correctly.
Example:
/**
* Returns the sum of two integers.
*
* @param num1 the first integer
* @param num2 the second integer
* @return the sum of num1 and num2
*/
public int findSum(int num1, int num2) {
return num1 + num1;
}
Different types of methods we can create as following:
Instance Methods:
Instance methods are associated with objects of a class.
They can access instance variables and other instance methods directly.
These methods are invoked using an instance of the class.
public class MyClass {
int x;
// Instance method
public void setX(int newValue) {
x = newValue;
}
}
Static Methods:
Static methods belong to the class rather than any specific instance.
They can only access static variables and other static methods directly.
Static methods are invoked using the class name.
public class MyClass {
static int y;
// Static method
public static void setY(int newValue) {
y = newValue;
}
}
Constructor Methods:
Constructor methods are special methods invoked when an object of a class is created.
They initialize the newly created object.
public class MyClass {
int z;
// Constructor method
public MyClass(int initialValue) {
z = initialValue;
}
}
Accessor Methods:
Accessor methods, also known as getter methods, are used to retrieve the values of private instance variables.
They typically do not modify the state of the object.
public class MyClass {
private int value;
// Accessor method
public int getValue() {
return value;
}
}
Mutator Methods:
They are simply setter methods, are used to modify the values of private instance variables.
public class MyClass {
private int value;
// Mutator method
public void setValue(int newValue) {
value = newValue;
}
}
When to use what type of method:
Use instance methods when you need to perform operations on instance variables or when the method is related to the behaviour of individual objects.
Use static methods when the method doesn't rely on instance variables and can be shared among all instances of the class or when you need utility methods that perform common operations.
Constructor methods should be used to initialize object states when they are created.
Accessor and mutator methods should be defined for each private instance variable to control access to them.
Accessor methods should return the value of the variable, while mutator methods should modify the value of the variable. This helps maintain encapsulation and ensures that the class's internal state is accessed and modified in a controlled manner.
Create an application which help you to perform sum, product, findBigger, findOddOrEven
class:Calculator
-----------------
int sum(int num1,int num2);
int product(int num1,int num2,int num3);
int findBigger(int num1,int num2);
findOddOrEven(int num1);
--coding in java------------->
package calc;
public class Calculator {
public int sum(int num1,int num2){
return num1+num2;
}
public int product(int num1,int num2,int num3){
return num1*num2*num3;
}
public int findBigger(int num1,int num2){
int temp=(num1>num2)?num1:num2;
return temp;
}
public String findOddOrEven(int num1){
String result="";
if(num1%2==0){
result=num1+" is an even number";
}else{
result=num1+" is odd number";
}
return result;
}
}
MainMethod class:
package service;
import calc.Calculator;
public class Main {
public static void main(String[] args) {
Calculator calculator=new Calculator();
System.out.println("Sum of values:"+calculator.sum(12,34));
System.out.println("Product of values:"+calculator.product(3,4,6));
System.out.println("Bigger number is :"+calculator.findBigger(56,89));
System.out.println("Bigger number is :"+calculator.findBigger(516,89));
System.out.println("Bigger number is :"+calculator.findBigger(56,56));
System.out.println(calculator.findOddOrEven(10));
System.out.println(calculator.findOddOrEven(19));
}
}