Java function

Nikhil Shah

Newbie
Joined
Jun 30, 2022
Messages
7
Reaction score
1
In Java, how can I "return" the swapped value of two integers from a function?
Code:
class Solution{
    static List<Integer> get(int a,int b)
    {
    a=a+b;
    b=a-b;
    a=a+b;
//**What will be the return statement?**
        
    }

}
Is it necessary to return an object of some kind, containing the swapped values for a and b, because Java is always pass-by-value? I'm reading this article about swapping two numbers in Java from https://www.scaler.com/topics/swapping-of-two-numbers-in-java/. Also, do I really need the three lines I already wrote in this method?
 
Is it necessary to return an object of some kind, containing the swapped values for a and b, because Java is always pass-by-value?
In this case, yes.

Since the return type of your method is a `List<Integer>`, you're probably going to want to return some sort of `List` implementation that contains both `a` and `b`. There are a number of ways to do this as you can see https://www.baeldung.com/java-init-list-one-line.
 
Last edited:
Back
Top