0

I have a function that returns two integers as a list. Is it possible in Java to separate these into individual int variables from the function?

int first, int second = returnsIntList();

Or am I restricted to initializing.

int numbers[] = returnsIntList();
int firstInt = numbers[0];
int secondInt = numbers [1];

I'm trying to increase readability in my program since the two integers can't be described with a single word but I'm unsure if the syntax exists after searching because 90% of the battle with searching these days is knowing the correct terms to search.

3 Answers 3

5

No, there's nothing like this in Java.

If there will always be two values with specific meaning, it would be better if they were returned in a custom type with appropriate properties. But otherwise, you just have to make do with storing the array reference in one variable, and then fetching the individual values in separate statements.

Sign up to request clarification or add additional context in comments.

Comments

3

You cannot do what you are trying to do.

One of the common practice in Java is use of Value Objects.

To know what Value Objects is have a look here.

You can have a class with getter and setter of the 2 numbers(integers). In the method returnsIntList() you can create an object of the class and set the 2 numbers using the respective set method. The method should then return the object.

You can then get the values from the object from the respective get method.

Comments

1

You can't do this in Java. In this instance you will be limited to initializing. You may want to look into custom data types, then you can just call the numbers through getters.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.