Java parameter and return types

18-Sep-2024

Learn how to pass parameters and return values from methods in Java.



We have already seen about parameters in the last chapter. parameters are used to pass data into a method

A method can have parameters.

A method may not have parameters.

A method can have many parameters of the same data type

A method can have many parameters of the different data type


Multiple parameters must be separated by commas. Parameters are given based on the task of the method

let's see some examples:


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



public static void sumOfThreeNumer(int a, int b, int c){
int result = a + b + c;
System.out.println(result);
}



public static void studentDataStore(int roll, String name, String Subject, String address, int age){
// do something with the data
}



Now learn about return types:


The return type can be of different types and can be void (no return type).



No return:



public static void multiply(int a, int b){
int result = a * b;
System.out.println(result);
}


The above multiply method returns nothing that why the return type of the method is void.


If the method has a return type and the method returns a value when calling the method we can store it in a variable. 

Suppose a method takes 2 int parameters and returns the sum of 2 int values. then how to call the method and how to get the result.

For static method


public class LearnMethod {

public static void main(String[] args) {
int result = sumWithoutReturn(345,345);
System.out.println(result);
}
public static int sumWithoutReturn(int a, int b){
int result = a * b;
return result;
}

}



For non static method



public class LearnMethod {

public static void main(String[] args) {
LearnMethod learnMethod = new LearnMethod();
int result = learnMethod.sumWithoutReturn(345,345);
System.out.println(result);
}
public int sumWithoutReturn(int a, int b){
int result = a * b;
return result;
}

}



let's take another example.

Suppose a method takes 2 String parameters and returns the concat value of 2 String values. then how to call the method and how to get the result.


For static method



public class LearnMethod {

public static void main(String[] args) {

String result = concatWIthReturn("Hello","World");
System.out.println(result);

}
public static String concatWIthReturn(String a, String b){
String result = a + " " + b;
return result;
}

}



For non static method



public class LearnMethod {

public static void main(String[] args) {

LearnMethod learnMethod = new LearnMethod();
String result = learnMethod.concatWIthReturn("Hello","World");
System.out.println(result);

}
public String concatWIthReturn(String a, String b){
String result = a + " " + b;
return result;
}

}



Comments