I would like to know how I can get the return value of a method and use it in another directly following it. For instance let's say I did this:
public Integer multiply(Integer n1, Integer n2){
return n1 * n2;
}
//I know this is wrong but I don't know what params to put
public Integer add(Integer n1, Integer n2){
return n1 + n2;
}
multiply(2, 2).add(???????);
In this I want to end up using the 4 from the multiply method as a value, then use the add method to add whatever value I give it to the result of the multiply which is four.
Note: I understand I could do:
add(multiply(2, 2), 3);
but I want to know how to use this format.
What I want to accomplish is:
Integer i = multiply(2, 2).add(5);
System.out.print(i);
to where when I run this the output will be 9 because 2 * 2 = 4 + 5 = 9. Please explain this to me :)
here when you do
it returns an
integer
and using that return typeInteger
, you are trying to call `add() method.but
add() method
is not available insideInteger
class with whatever the signature and intended you are trying to do.so it complains like
add()
is not available insideInteger
class.so to achieve it make
multiple(2,2)
to return your own class and have a result in it.and then call that
add()
method using that object easily in the way you want.The way how you could achive the same is like below