Java method return two

How to return multiple values? [duplicate]

Is it possible to return two or more values from a method to main in Java? If so, how it is possible and if not how can we do?

Return array, list, set, map or your custom object containing multiple values. I have seen this same question somewhere. let me find that. There are multiple questions on this topic: stackoverflow.com/search?q=return+multiple+values+in+java%3F

If you are on Java 14+, it is better in general to use a Java Record instead of a SimpleEntry for representing a pair of values.

3 Answers 3

You can return an object of a Class in Java.

If you are returning more than 1 value that are related, then it makes sense to encapsulate them into a class and then return an object of that class.

If you want to return unrelated values, then you can use Java’s built-in container classes like Map, List, Set etc. Check the java.util package’s JavaDoc for more details.

I would add one more point to this — keep your returned object immutable (best initialize it in a constructor and keep your fields final)

You can return an object , but if you have so many return objects in your program it makes the source code complicated. for things that are returned from a method once-of-its-kind-it-the-program better to have Tuples. like c#. darling c# its a great language

I guess there should be C# out or ref parameter equivalent in Java, otherwise I will need to create class even for returning two variables and for each function returning multiple values. If we follow this, then there will be a class for every function returning multiple values. Though using Map feels better approach now.

Источник

return two variables from one method

In Java you can return only one variable/Object. If you want to return two String objects.I recommend you to put those in an array,list or set and then pass return that object.

5 Answers 5

When using Java 8 you could make use of the Pair class.

private static Pair foo (/* some params */) < final String val1 = ""; // some calculation final String val2 = ""; // some other calculation return new Pair<>(val1, val2); > 

Otherwise simply return an array.

@DavidM. I agree with you. Especially when looking forward to Java9 modularization, where one might encounter runtimes without UI modules installed. An array or a simple pojo class could be more elegant.

You cannot return two different values in methods in Java.

When this need occurs, you usually have two options:

  1. Create a class which has the types you want to return, and then return an instance of that class. Usually these classes are very basic, contain public members and optionally a constructor to initiate an instance with all the required values.
  2. Add a reference type object as a parameter to the method which the method will mutate with the values you want to return. In your example you use strings, and so this will not work since in Java strings are immutable.
Читайте также:  Php find if char is in string

Another option would be to use an array of strings, since both your return types are strings. You could use this option as a return value, or a parameter which is altered by the method.

Edit: usually «toString» methods do return only one string. Perhaps you should consider concatenating both your strings into one string using some separator. Example:

Источник

Can a method return two values in Java? [duplicate]

The program should return how many positive and negative numbers there are in a sequence. The main method will read a sequence of numbers from input and for each of them evaluate if it is positive or negative using this method below.

 public static int positiveOrNegativeNumber(int n) < int positiveNumber; //counter for positive numbers int negativeNumber; //counter for negative numbers positiveNumber=0; negativeNumber=0; if (n>0) < positiveNumber = positiveNumber + 1; >else if (n <0) < negativeNumber = negativeNumber + 1; >return positiveNumber & negativeNumber; > 

does the expression return positiveNumber & negativeNumber return them both? edit: So, following Java Geo suggestion I got this:

 public static NumCounter positiveOrNegativeNumber(int n, NumCounter numCounter) < if (n>0) < numCounter.setPositiveNumCounter(numCounter.getPositiveNumCounter()+1); >else if (n <0) < numCounter.setNegativeNumCounter(numCounter.getNegativeNumCounter()+1); >return numCounter; 
 public static void main(String[] args) < int n; while(!Lettore.in.eoln()) < //while the line has not ended n = Lettore.in.leggiInt(); //read n from input // what is missing here?? >> 

Don’t worry about Lettore.in.eoln and Lettore.in.leggiInt, are just methods that make getting things from input easier without having to use the scanner.

For the second part of your question, no. & means «bitwise AND» (unless Java has completely different syntax from other languages in this respect), it doesn’t mean «return both of these».

Your method gets only one number so it can only return if it is positive or negative, but can’t count how many positive and negatives.

6 Answers 6

I will suggest to create a class «NumCounter»

public class NumCounter < int positiveNumCounter; int negativeNumCounter; public int getPositiveNumCounter() < return positiveNumCounter; >public void setPositiveNumCounter(int positiveNumCounter) < this.positiveNumCounter = positiveNumCounter; >public int getNegativeNumCounter() < return negativeNumCounter; >public void setNegativeNumCounter(int negativeNumCounter) < this.negativeNumCounter = negativeNumCounter; >> 

Then modify your method like

public static NumCounter positiveOrNegativeNumber(int n, NumCounter numCounter) < if (n>0) < numCounter.setPositiveNumCounter(numCounter.getPositiveNumCounter()+1); >else if (n <0) < numCounter.setNegativeNumCounter(numCounter.getNegativeNumCounter()+1); >return numCounter; > 

I like this suggestion but how do I print it out? in the main method I can’t just write positiveOrNegativeNumber(n) because I miss the numCounter part, what should I put there?

No, positiveNumber & negativeNumber returns the result of Bit-wise AND of the two integers, and given your logic, will always return 0 ( 0 & 1 == 0 and 0 & 0 == 0 ).

If you want to return multiple values, you can return an int[] or an instance of a class that contains multiple fields.

That said, your method doesn’t count anything. It receives a single number and even if you returned the two counters, one of them will be 0 and the other 1 (unless the input is 0). If you want to count the number of positive and negative values in a sequence, you should pass an array of input numbers to your method.

Читайте также:  What is window object in javascript

If you want to pass a single number of a sequence to each call of your method, you can make your positiveNumber and negativeNumber counters static members of your class, and initialize them to 0 outside your method. In that case, your method won’t have to return anything at all, since you’ll be able to access the counters from outside your method.

Источник

How to return 2 values from a Java method?

Instead of returning an array that contains the two values or using a generic Pair class, consider creating a class that represents the result that you want to return, and return an instance of that class. Give the class a meaningful name. The benefits of this approach over using an array are type safety and it will make your program much easier to understand.

Note: A generic Pair class, as proposed in some of the other answers here, also gives you type safety, but doesn’t convey what the result represents.

Example (which doesn’t use really meaningful names):

final class MyResult < private final int first; private final int second; public MyResult(int first, int second) < this.first = first; this.second = second; >public int getFirst() < return first; >public int getSecond() < return second; >> // . public static MyResult something() < int number1 = 1; int number2 = 2; return new MyResult(number1, number2); >public static void main(String[] args)

This would be my preferred route — presumably the pair of numbers has some meaning, and it would be nice if the return type represented this.

You can use SimpleEntry from java.util.AbstractMap.SimpleEntry and use it with getKey() to get object 1 and getValue() to get object 2

I feel very strongly that Java should allow you to return multiple values. It would be faster (fewer objects created) and wouldn’t require extra classes (bloated code) every time you want to do something a bit different. I don’t see any downsides, perhaps someone can enlighten me?

@AnumSheraz The answer to «how to . just like in Python» is: you don’t, because Java does not have such a language feature.

Java might get a convenient way to return multiple values from a method in the future, based on pattern matching with records. But this is not yet available in Java 17.

Java does not support multi-value returns. Return an array of values.

// Function code public static int[] something()< int number1 = 1; int number2 = 2; return new int[] ; > // Main class code public static void main(String[] args)

This is almost always the wrong thing to do, especially if the types of the two result values are different.

@BarAkiva, the reason it is wrong is because you loose type safety. If you’re returning values of a homogenous type then you should always prefer a List over an array. In particular, if you’re dealing with generic values then a List is always preferred as a return value over T[] because you can always construct a List on a generic type but never an array; you cannot do this: «new T[length];» The approach of creating a Pair class as indicated here for disparate types is a better option for heterogenous types.

Читайте также:  Repeating backgrounds in html

You could implement a generic Pair if you are sure that you just need to return two values:

public class Pair < /** * The first element of this Pair */ private U first; /** * The second element of this Pair */ private V second; /** * Constructs a new Pair with the given values. * * @param first the first element * @param second the second element */ public Pair(U first, V second) < this.first = first; this.second = second; >//getter for first and second 

and then have the method return that Pair :

You can only return one value in Java, so the neatest way is like this:

return new Pair(number1, number2); 

Here’s an updated version of your code:

public class Scratch < // Function code public static Pairsomething() < int number1 = 1; int number2 = 2; return new Pair(number1, number2); > // Main class code public static void main(String[] args) < Pairpair = something(); System.out.println(pair.first() + pair.second()); > > class Pair  < private final T m_first; private final T m_second; public Pair(T first, T second) < m_first = first; m_second = second; >public T first() < return m_first; >public T second() < return m_second; >> 

Here is the really simple and short solution with SimpleEntry:

AbstractMap.Entry myTwoCents=new AbstractMap.SimpleEntry<>("maximum possible performance reached" , 99.9f); String question=myTwoCents.getKey(); Float answer=myTwoCents.getValue(); 

Only uses Java built in functions and it comes with the type safty benefit.

Use a Pair/Tuple type object , you don’t even need to create one if u depend on Apache commons-lang. Just use the Pair class.

you have to use collections to return more then one return values

in your case you write your code as

public static List something() < Listlist = new ArrayList(); int number1 = 1; int number2 = 2; list.add(number1); list.add(number2); return list; > // Main class code public static void main(String[] args) < something(); ListnumList = something(); > 
public class Mulretun < public String name;; public String location; public String[] getExample() < String ar[] = new String[2]; ar[0]="siva"; ar[1]="dallas"; return ar; //returning two values at once >public static void main(String[] args) < Mulretun m=new Mulretun(); String ar[] =m.getExample(); int i; for(i=0;i> o/p: return values are: siva return values are: dallas 

I’m curious as to why nobody has come up with the more elegant callback solution. So instead of using a return type you use a handler passed into the method as an argument. The example below has the two contrasting approaches. I know which of the two is more elegant to me. 🙂

public class DiceExample < public interface Pair < T1 getLeft(); T2 getRight(); >private Pair rollDiceWithReturnType() < double dice1 = (Math.random() * 6); double dice2 = (Math.random() * 6); return new Pair() < @Override public Integer getLeft() < return (int) Math.ceil(dice1); >@Override public Integer getRight() < return (int) Math.ceil(dice2); >>; > @FunctionalInterface public interface ResultHandler < void handleDice(int ceil, int ceil2); >private void rollDiceWithResultHandler(ResultHandler resultHandler) < double dice1 = (Math.random() * 6); double dice2 = (Math.random() * 6); resultHandler.handleDice((int) Math.ceil(dice1), (int) Math.ceil(dice2)); >public static void main(String[] args) < DiceExample object = new DiceExample(); Pairresult = object.rollDiceWithReturnType(); System.out.println("Dice 1: " + result.getLeft()); System.out.println("Dice 2: " + result.getRight()); object.rollDiceWithResultHandler((dice1, dice2) -> < System.out.println("Dice 1: " + dice1); System.out.println("Dice 2: " + dice2); >); > > 

Источник

Оцените статью