0

I understand the concept of taking an int value into a method which is effectively a copy of the int value, rather than the actual value and memory location.

Is there a way of changing the main integer value based on the result of the method?

If I return the int value to main can I do something like int num = int numIn where int numIn is the returned value. If yes the can it be used for multiple methods returns, so that the main int value changes after each consecutive method return ?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Damo42
  • 9
  • 2
  • What? Do you mean like `int num = someIntFunction(someOtherInt);`? Or reassigning, like `someOtherInt = someIntFunction(someOtherInt);`? – Dave Newton Mar 31 '14 at 20:15
  • `int x = 10; x = computeNewValueFromOld(x);` – Jason C Mar 31 '14 at 20:15
  • possible duplicate of [Changing the values of variables in methods, Java](http://stackoverflow.com/questions/489913/changing-the-values-of-variables-in-methods-java) – Jason C Mar 31 '14 at 20:16
  • Welcome to stack overflow. Basic questions like this are better suited for google searches but yet, just reassign the value to the return value of your function... e.g. `x = myFunction(7); x = myNextFunction(8);` etc – Display Name is missing Mar 31 '14 at 20:16
  • See also the official tutorial on [Classes and Objects](http://docs.oracle.com/javase/tutorial/java/javaOO/index.html), in particular the sections "Passing Information to a Method" and "Returning a Value From a Method". The tutorial is concise and well-written and will give you all the concepts you need to answer your question here. – Jason C Mar 31 '14 at 20:17
  • Ok folk's I have a lot of research to do however thank you for your input. I maybe should have clarified I want to achieve this only using methods and not objects / classes, but all of your replies have given me lots of areas to investigate and learn. I am just coming to end of !st year of computer science so forgive my ignorance Thank you again – Damo42 Mar 31 '14 at 21:16
  • Dave Newton Thanks for your question.. The question actually refocused my brain Thanks again.. Not sure if that is a common thing when learning java but it worked for me.... opened a new door of ideas Thanks – Damo42 Mar 31 '14 at 21:53

1 Answers1

2

You must begin here.

int i = 10;

private int add(int x, int y){
    return x + y;
}

Initially the value of i is 10. But if you call-

i = add( 5, 10 );

The new value of i is now 15.

Sajal Dutta
  • 18,272
  • 11
  • 52
  • 74