Java method Defining and calling

18-Sep-2024

Learn how to define and call methods in Java programs for reusing code



We already learn about method definition in the previous chapter. 

5 points should be kept in mind during method definition.


1. access_modifier

2. return_type

3. method_name

4. parameters

5. method body


We already know about them.

Let's learn a little more about return types. If we use the return type void i.e. if nothing is returned then it's ok. But if there is a return type like int then after all the work of our method we have to return an int value from the method its syntax will return a_int_value;

The type we set the return type must return any value of that type at the end of the method, otherwise an error will appear in the program.


Now lets learn method calling

We have to create the method first and then call it. if your method is static, then you can call it directly without creating the class object. and if the method is not static then first you must create an object of class.

method call syntax:

This Syntax below is used when the method has no parameters and no return type.

For Static method.


public class LearnMethod {

public static void main(String[] args) {

sumWithoutReturn();
}
public static void sumWithoutReturn(){
int result = 23 + 346;
System.out.println(result);
}

}



For non static method.


public class LearnMethod {

public static void main(String[] args) {

LearnMethod learnMethod = new LearnMethod();
learnMethod.sumWithoutReturn();
}
public void sumWithoutReturn(){
int result = 23 + 346;
System.out.println(result);
}

}




This Syntax below is used when the method has parameters no return type.


For static method:


public class LearnMethod {

public static void main(String[] args) {

sumWithoutReturn(235, 345);
}
public static void sumWithoutReturn(int a, int b){
int result = a + b;
System.out.println(result);
}

}



For non static method:



public class LearnMethod {

public static void main(String[] args) {

LearnMethod learnMethod = new LearnMethod();
learnMethod.sumWithoutReturn(235, 345);
}
public void sumWithoutReturn(int a, int b){
int result = a + b;
System.out.println(result);
}

}




Comments