Aright, I think i got this going. But now I'm having an issue with the interface methods. The interface method uses a generic type and 1 object. But the assignment calls for adding two objects. I'm now stuck at this point. I'm not sure how to write the add(T o) interface since I can only send one object into the method. I've tried using value1.add(value2) but when I test the values only values for values1 seems to come up. I have no idea where value2 goes Here is my class and the interface
public class MyFraction implements MyMath<MyFraction> {
private List<Character> sign = new ArrayList<Character>();
private List<Integer> numerator = new ArrayList<Integer>();
private List<Integer> denominator = new ArrayList<Integer>();
public MyFraction(int numerator, int denominator, char sign) {
this.numerator.add(numerator);
this.denominator.add(denominator);
this.sign.add(sign);
}
public MyFraction(){}
public static void main(String[] args) {
MyFraction run = new MyFraction();
run.start();
}
private void start() {
char sign = JOptionPane.showInputDialog(null, "Enter - for negative + for positive number ").charAt(0);
int numerator = Math.abs(Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a numerator ")));
int denominator = Math.abs(Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a denominator ")));
MyFraction value1 = new MyFraction(numerator, denominator, sign);
sign = JOptionPane.showInputDialog(null, "Enter - for negative + for positive number ").charAt(0);
numerator = Math.abs(Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a numerator ")));
denominator = Math.abs(Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a denominator ")));
MyFraction value2 = new MyFraction(numerator, denominator, sign);
System.out.println("numerator 1: "+value1.getNumerator() );
System.out.println("denominator 1: "+value1.getDenominator() );
System.out.println("sign 1: "+value1.getSign() );
System.out.println();
System.out.println("numerator 2: "+value2.getNumerator() );
System.out.println("denominator 2: "+value2.getDenominator() );
System.out.println("sign 2: "+value2.getSign() );
}
public int getNumerator(){
int value = this.numerator.get(0);
return value;
}
public int getDenominator(){
int value = this.denominator.get(0);
return value;
}
public char getSign(){
char value = this.sign.get(0);
return value;
}
#Override
public MyFraction add(MyFraction o) {
return null;
}
#Override
public MyFraction subtract(MyFraction o) {
// TODO Auto-generated method stub
return null;
}
#Override
public MyFraction divide(MyFraction o) {
// TODO Auto-generated method stub
return null;
}
#Override
public MyFraction multiply(MyFraction o) {
// TODO Auto-generated method stub
return null;
}
}
public interface MyMath<T> {
public T add(T o);
public T subtract(T o);
public T divide(T o);
public T multiply(T o);
}
An interface is somewhat a contract, that sais "whoever implements me must contain an implementation of all the methods declared in me". Every class that implements that interface figuratevely signs that contract and therefore must have it's own implementation of these methods.
In your class you are missing the implementation of the whole interface, which is why your code is not compiling. Your class should look like:
public class MyFraction implements MyMath<MyFraction> {
....
}
//interface memebers
#Override
public MyFraction subtract(MyFraction o){
//do subtraction here
return null;
}
#Override
public MyFraction divide(MyFraction o){
//do division here
return null;
}
#Override
public MyFraction multiply(MyFraction o){
//do multiplication here
return null;
}
#Override
public MyFraction add(MyFraction o) {
// do adding here
return null;
}
}
Please take a step back and think about the solution you got so far. Your class MyFraction contains four lists - why? "My" MyFraction would consist of a numerator, a denominator and maybe a sign.
Would I choose a Character to store the sign-> I do not know. But you should think about negative values for the numerator and denominator, e.g. numerator is -4 and denominator -2. What value has MyFraction when the sign is entered as "-".
To create a MyFraction instance you should be able to use a constructor like this
public MyFraction(Integer theNumerator, Integer theDenominator, Character theSign)
And remember to implement all methods of the interface. You got only the method add so far and code will not compile because of the missing implementations.
Related
I have three classes for now one is the main class,
Class A:
class A{
int result;
int getHeightBase() {
return result;
}
void setHeightBase(int h, int b) {
result=h*b;
}
}
Class B:
This class will perform different calculations than A
class B{
int result;
int getHeightBase() {
return result;
}
void setHeightBase(int h, int b) {
result=12*h*b;
}
}
MainClass:
public class Main {
public static void main(String[] args) {
A a= new A();
B b= new B();
calculateArea(a,b);
}
void calculateArea(A obj1, B obj2){
obj1.setHeightBase(5,6);
obj2.setHeightBase(5,6);
}
}
Now, when I change arguments of class A method setHeightBase or class B method setHeightBase for some reason I got to change in MainClass as well where I am sending integer values , and I think this opposes design patterns, could anyone please guide me how to get rid of this, I want to change arguments later on but I don't want to effect any other class or change any other class, I tried to use interface but did not get how to get rid of this problem
thanks a lot in advance , any help would be appreciated
Let's say you have this class:
public void printNumbers(int one, int two) {
int result = one + two;
System.out.println("result = " + result);
}
And this is being called from multiple other classes. You can't just change the signature (returntype, method name, parameterlist) and expect everything to work just fine.
Now, let's assume you don't want it to automatically print a sum, but you want to be able to choose what action to take addition or subtraction.
For the current method, don't change anything. It's been used for addition. So, you'll add an overloaded method, which accepts an additional parameter:
public void printNumbers(int one, int two) {
int result = one + two;
System.out.println("result = " + result);
}
public void printNumbers(int one, int two, String action) {
// action is either add or sub
if ( !"add".equals(action) && !"sub".equals(action) ) {
System.out.println("Error");
} else if ("add".equals(action) {
int result = one + two;
System.out.println("result = " + result);
} else {
int result = one - two;
System.out.println("result = " + result);
}
}
Once you did that, you can change the original method to:
public void printNumbers(int one, int two) {
printNumbers(one, two, "add");
}
public void printNumbers(int one, int two, String action) {
// action is either add or sub
if ( !"add".equals(action) && !"sub".equals(action) ) {
System.out.println("Error");
} else if ("add".equals(action) {
int result = one + two;
System.out.println("result = " + result);
} else {
int result = one - two;
System.out.println("result = " + result);
}
}
and the functionality that was once provided will remain the same, while you won't have to change any other existing code
You can use method overloading,
void setHeightBase(int h, int b) {
result=12*h*b;
}
void setHeightBase(double h, double b) {
result=12.0*h*b;
}
this will save the previous method and also creates a method with exact name and different arguments.
I would use an abstract class as the base and extend other classes from it. The public methods in the abstract class will act as the contract to the outside world. In future, if you want to expose other method you add them to the interface and depending on the functionality, you could provide a default implementation. In real world scenarios, you avoid changing an existing contract.
As an example, your classes can be written as such
abstract class Shape{
int height;
int base;
Shape(int height, int base){
super();
this.height = height;
this.base = base;
}
public int area(){
return height * base;
}
}
class Shape1 extends Shape{
Shape1(int height, int base){
super(height, base);
}
}
class Shape2 extends Shape{
Shape2(int height, int base){
super(height, base);
}
#Override
public int area(){
return 12 * height * base;
}
}
public class Test{
public static void main(String args[]){
Shape s1 = new Shape1(2,3);
Shape s2 = new Shape2(2,3);
System.out.println(s1.area());
System.out.println(s2.area());
}
}
I created an abstract class Fruit, which overrides the equals() method. Then I created a subclass, Orange, which overrides the copy() and the equals() method. In my test file, TestFruit.java, I am creating an array of oranges and testing their methods. I am trying to create a deep copy of orange and do a deep comparison between the parent orange and the copy. However, in my output, the comparison always returns false. I checked the parent and the copy's attributes and they do seem to be the same. Any pointers would be appreciated. I am pretty new to Java and copying. I attached my code below.
Fruit.java:
package juicer;
import copy.Copyable;
public abstract class Fruit implements Copyable, Cloneable
{
private double mass;
private boolean isJuicedRemoved;
protected Fruit(double theMass)
throws IllegalMassException
{
{
if (theMass <= 0)
{
throw new IllegalMassException(theMass);
}
else
{
this.mass = theMass;
this.isJuicedRemoved = false;
}
}
}
protected Fruit(Fruit fruit)
{
this.mass = fruit.mass;
this.isJuicedRemoved = fruit.isJuicedRemoved;
}
public double getMass()
{
return mass;
}
public boolean getIsJuicedExtracted()
{
return isJuicedRemoved;
}
protected void setMass(double value)
{
this.mass = value;
}
protected abstract double juiceRatio();
public double extractJuice()
{
double liquidMass = amountJuice();
if (!isJuicedRemoved)
{
isJuicedRemoved = true;
mass -= liquidMass;
}
return liquidMass;
}
public double amountJuice()
{
if (isJuicedRemoved) return 0.0;
return mass * juiceRatio();
}
#Override
public boolean equals(Object obj)
{
// Steps to override the equals() method():
// Step 1: Test if obj is an instance of Fruit.
// If it is not, then return false.
if (!(obj instanceof Fruit)) return false;
// Step 2: Cast obj to an Fruit.
Fruit rhs = (Fruit)obj;
// Step 3: Test if the data fields of the invoking object are
// equal to the ones in rhs using a deep comparison
// and return this result.
return super.equals(obj) && // test for equality in the super class
mass == rhs.mass &&
isJuicedRemoved == rhs.isJuicedRemoved;
}
#Override
public int hashCode()
{
int result = super.hashCode();
result = 31*result + Double.hashCode(mass);
result = 31*result + Boolean.hashCode(isJuicedRemoved);
return result;
}
#Override
public Object clone() throws CloneNotSupportedException
{
Fruit objectClone = (Fruit)super.clone();
objectClone.mass = mass;
objectClone.isJuicedRemoved = isJuicedRemoved;
return objectClone;
}
#Override
public String toString()
{
return "\tmass = " + mass +
"\n\tisJuiceExtracted = " + isJuicedRemoved + "\n";
}
}
Orange.java:
package juicer;
public class Orange extends Fruit
{
public Orange(double mass)
{
super(mass);
}
// copy constructor
public Orange(Orange other)
{
super(other);
}
#Override
protected double juiceRatio()
{
return 0.87;
}
#Override
public boolean equals(Object obj)
{
// Steps to override the equals() method():
// Step 1: Test if obj is an instance of Orange.
// If it is not, then return false.
if (!(obj instanceof Orange)) return false;
// Step 2: Cast obj to an Orange.
// This step is not needed since the only data fields this
// class has are the ones it inherits.
// Step 3: Test if the data fields of the invoking object are
// equal to the ones in rhs using a deep comparison
// and return this result.
return super.equals(obj);
}
#Override
public Object copy()
{
return new Orange(this);
}
#Override
public String toString()
{
return "Orange:\n" + super.toString();
}
}
TestFruit.java:
package test;
import juicer.*;
import java.util.Random;
public class TestFruit
{
public static void main(String[] args)
{
Orange[] oranges = new Orange[1];
//Random double generator for mass
Random rd = new Random();
//create oranges
for (int i = 0; i <= oranges.length - 1; i++ )
{
oranges[i] = new Orange(rd.nextDouble());
}
for (Orange orange : oranges)
{
Orange orangeCopy = new Orange(orange);
if (orange == orangeCopy)
{
System.out.print("The comparison is true!");
}
else
{
System.out.print("Does not match.");
}
}
}
}
One of the common misconceptions in Java is the use of == vs .equals(). When you use == to compare two objects in Java, internally it's comparing its memory address. == does not actually call .equals().
In this case, you have two distinct orange objects, so the comparison will always return false.
If you use a.equals(b), then it will actually invoke your equals method which you implemented.
As #Andreas pointed out in the comments, there's another issue. Calling super.equals(obj) in Fruit will call the superclass implementation of equals, and the superclass of Fruit is Object. Object.equals() behaves the same as == (i.e. also checking for reference equality). Overriding .equals() is not trivial, so it can often be nice to have the IDE generate it for you.
In contrast with a language like C++, Java does not have operator overloading. This means that you can't define a different implementation for ==. This is why it's best practice to always call .equals() when comparing any non-primitive types (unless you're explicitly checking reference equality, which is rare).
I am using three classes in my program:
Term class with variables coefficient and exponent, toString() method etc.
Polynome class, using an ArrayList to store the different Term objects.
Main class that runs the program.
Can I use the toString method of ArrayList in my Polynome class? I'm trying to, but I can't.
I need my polynome to output like this: [3x^2, 3x^1, 1x^0]
I am really confused, I'm calling the toString method of Term, using a for-loop to access each term separately.
My code:
public class Term {
private int coëfficiënt;
private int exponent;
public Term(int coëfficiënt, int exponent) {
this.coëfficiënt = coëfficiënt;
this.exponent = exponent;
}
public int getCoef() {
return coëfficiënt;
}
public int getExp() {
return exponent;
}
public String toString() {
return coëfficiënt + "x^" + exponent;
}
}
Polynome class:
public class Polynoom {
private ArrayList<Term> polynoom;
public Polynoom() {
polynoom = new ArrayList<Term>();
}
public void add(Term term) {
polynoom.add(term);
}
public Term get(int i) {
return polynoom.get(i);
}
public int size() {
return polynoom.size();
}
public String toString() {
// what should I write here?
}
}
Main class:
public class opgave3 {
public static void main(String[] args) {
Polynoom polynoom1, polynoom2, sompolynoom;
polynoom1 = new Polynoom();
polynoom1.add(new Term(1, 2));
polynoom1.add(new Term(3, 1));
polynoom1.add(new Term(1, 0));
polynoom2 = new Polynoom();
polynoom2.add(new Term(-1, 3));
polynoom2.add(new Term(2, 2));
polynoom2.add(new Term(-5, 0));
System.out.println("Tests: ");
System.out.println(polynoom1.toString());
for (int i = 0; i < polynoom1.size(); i++) {
System.out.println(polynoom1.get(i).toString());
}
System.out.println(polynoom1.get(0).toString());
}
}
You just need to use your ArrayList's toString() method as the results of Polynome's toString() method.
public class Polynome {
public ArrayList<Term> terms;
#Override
public String toString() {
if (terms != null) {
return terms.toString();
} else {
return "";
}
}
}
EDIT: The quick answer, since you put your code up is to put
return polynoom.toString();
where you have indicated. Then in your Main class you can simply write
System.out.println(polynoom1);
to show the contents in the desired format.
As Tenner said, use the toString() method of your ArrayList to get the desired output. But also make sure your Term class has a useful toString method of its own:
public class Term {
private int co, ex;
public Term(int coeff, int exp) {
co = coeff;
ex = exp;
}
#Override
public String toString() {
return co + "x^" + ex;
}
}
Add #Override toString() to your Term & Polynome class. The Term class toString() should return a string in the format of coefficientx^exponent.
Then have the Polynome class toString() return yourArrayList.toString()
public static void main(String[] args) throws Exception {
Polynome polynome = new Polynome();
polynome.addTerm(3, 2);
polynome.addTerm(3, 1);
polynome.addTerm(1, 0);
System.out.println(polynome);
}
public static class Term {
private int coefficient;
private int exponent;
public Term(int c, int e) {
coefficient = c;
exponent = e;
}
#Override
public String toString() {
return coefficient + "x^" + exponent;
}
}
public static class Polynome {
private List<Term> terms = new ArrayList<>();
public void addTerm(int coefficient, int exponent) {
terms.add(new Term(coefficient, exponent));
}
#Override
public String toString() {
return terms.toString();
}
}
Results:
Long story short, you can ALWAYS use toString() on anything, even if it's a user defined class. When you call the method, it calls the closest parent class's toString() method, which is guaranteed to be there as Object has one. If you want to control the output of toString() called on your object, you must override it. As it is, if you have an object with a member of type ArrayList, calling your object's toString() will include a ton of extra information that you probably don't want. In order to get the output you want, you need to have the code given by #Tenner's answer, which is
public class Polynome {
public ArrayList<Term> terms;
#Override
public String toString() {
if (terms != null) {
return terms.toString();
} else {
return "";
}
}
}
But you also need to override toString() in the Term class, so that each term outputs in the form desired. The reason this is required is that when you call toString() on an ArrayList, or any other container for that matter, it iterates through the container, calling each object's toString() in turn, adding whatever formatting the container class defines. Ultimately, Term's toString() will be called, and you can control that output by overriding it in the Term class.
As for the last part of the question, you need not call Term's toString() directly, as calling the toString() method of the ArrayList will do this on its own.
I need to make an add(Length) method that return a new length that is equal in size to the sum of the sizes of this length and the argument. I am unsure whether I need to return a double or Length and how to add
public class Length implements Comparable<Length>{
private final double length; //private! Do NOT add a getter
// This constructor must remain private
private Length(double l){
length = l;
}
public double add(Length l){
return ;
}
public double subtract(Length l){
}
public double scale(double d){
}
public double divide(Length l){
}
public double Length(Position one, Position two){
}
// TODO: For all constants, have a line:
// public static final Length ... = new Length(...);
// Use the #Override annotation on all methods
// That override a superclass method.
#Override
public boolean equals(Object other){
//TODO
}
#Override
public int hashCode(){
//TODO
}
#Override
public String toString(){
//TODO
}
// If you are overriding a method from an interface, then Java 5
// says you CANNOT use Override, but Java 6 says you MAY. Either is OK.
// #Override
public int compareTo(Length other) {
//TODO
}
// TODO Write the rest of the methods for this class, and
// the other two classes.
}
It depends on your requirement, but typically you'd want to return a new Length object.
public Length add(Length other){
// check that other is not null
return new Length(this.length + other.length);
}
You would do something similar for all the other mathematical methods.
As Rohit has stated in their comment, this makes your class immutable since there is no method that can modify the length field (but instead return a new Length object).
I am trying to return 2 values from a Java method but I get these errors. Here is my code:
// Method code
public static int something(){
int number1 = 1;
int number2 = 2;
return number1, number2;
}
// Main method code
public static void main(String[] args) {
something();
System.out.println(number1 + number2);
}
Error:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - missing return statement
at assignment.Main.something(Main.java:86)
at assignment.Main.main(Main.java:53)
Java Result: 1
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) {
MyResult result = something();
System.out.println(result.getFirst() + result.getSecond());
}
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[] {number1, number2};
}
// Main class code
public static void main(String[] args) {
int result[] = something();
System.out.println(result[0] + result[1]);
}
You could implement a generic Pair if you are sure that you just need to return two values:
public class Pair<U, V> {
/**
* The first element of this <code>Pair</code>
*/
private U first;
/**
* The second element of this <code>Pair</code>
*/
private V second;
/**
* Constructs a new <code>Pair</code> 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:
public Pair<Object, Object> getSomePair();
You can only return one value in Java, so the neatest way is like this:
return new Pair<Integer>(number1, number2);
Here's an updated version of your code:
public class Scratch
{
// Function code
public static Pair<Integer> something() {
int number1 = 1;
int number2 = 2;
return new Pair<Integer>(number1, number2);
}
// Main class code
public static void main(String[] args) {
Pair<Integer> pair = something();
System.out.println(pair.first() + pair.second());
}
}
class Pair<T> {
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<String, Float> 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(){
List<Integer> list = new ArrayList<Integer>();
int number1 = 1;
int number2 = 2;
list.add(number1);
list.add(number2);
return list;
}
// Main class code
public static void main(String[] args) {
something();
List<Integer> numList = 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<ar.length;i++)
System.out.println("return values are: " + ar[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, T2> {
T1 getLeft();
T2 getRight();
}
private Pair<Integer, Integer> rollDiceWithReturnType() {
double dice1 = (Math.random() * 6);
double dice2 = (Math.random() * 6);
return new Pair<Integer, Integer>() {
#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();
Pair<Integer, Integer> result = 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);
});
}
}
You don't need to create your own class to return two different values. Just use a HashMap like this:
private HashMap<Toy, GameLevel> getToyAndLevelOfSpatial(Spatial spatial)
{
Toy toyWithSpatial = firstValue;
GameLevel levelToyFound = secondValue;
HashMap<Toy,GameLevel> hm=new HashMap<>();
hm.put(toyWithSpatial, levelToyFound);
return hm;
}
private void findStuff()
{
HashMap<Toy, GameLevel> hm = getToyAndLevelOfSpatial(spatial);
Toy firstValue = hm.keySet().iterator().next();
GameLevel secondValue = hm.get(firstValue);
}
You even have the benefit of type safety.
Return an Array Of Objects
private static Object[] f ()
{
double x =1.0;
int y= 2 ;
return new Object[]{Double.valueOf(x),Integer.valueOf(y)};
}
In my opinion the best is to create a new class which constructor is the function you need, e.g.:
public class pairReturn{
//name your parameters:
public int sth1;
public double sth2;
public pairReturn(int param){
//place the code of your function, e.g.:
sth1=param*5;
sth2=param*10;
}
}
Then simply use the constructor as you would use the function:
pairReturn pR = new pairReturn(15);
and you can use pR.sth1, pR.sth2 as "2 results of the function"
You also can send in mutable objects as parameters, if you use methods to modify them then they will be modified when you return from the function. It won't work on stuff like Float, since it is immutable.
public class HelloWorld{
public static void main(String []args){
HelloWorld world = new HelloWorld();
world.run();
}
private class Dog
{
private String name;
public void setName(String s)
{
name = s;
}
public String getName() { return name;}
public Dog(String name)
{
setName(name);
}
}
public void run()
{
Dog newDog = new Dog("John");
nameThatDog(newDog);
System.out.println(newDog.getName());
}
public void nameThatDog(Dog dog)
{
dog.setName("Rutger");
}
}
The result is:
Rutger
You can create a record (available since Java 14) to return the values with type safety, naming and brevity.
public record MyResult(int number1, int number2) {
}
public static MyResult something() {
int number1 = 1;
int number2 = 2;
return new MyResult(number1, number2);
}
public static void main(String[] args) {
MyResult result = something();
System.out.println(result.number1() + result.number2());
}
First, it would be better if Java had tuples for returning multiple values.
Second, code the simplest possible Pair class, or use an array.
But, if you do need to return a pair, consider what concept it represents (starting with its field names, then class name) - and whether it plays a larger role than you thought, and if it would help your overall design to have an explicit abstraction for it. Maybe it's a code hint...
Please Note: I'm not dogmatically saying it will help, but just to look, to see if it does... or if it does not.