0

so in the below code if exampleVar when first printed out would be zero then once printed out again, would be two yes? I am trying not to use a global variable and other than this, I cannot think of another way.

public int method ... {
        int exampleVar = 0;
        System.out.println(exampleVar); // would be zero
        pmethod(exampleVar,);
        System.out.println(exampleVar); // would be two?
        }

        private int pmethod(int exampleVar) {
            exampleVar++;
            if(exampleVar != 2){
               pmethod(exampleVar);
            }
        }

the answer people are saying this one is a duiplicate of is not valid, as that answer although correct is far too noisy. using foo examples which are completely abstract and confusing. I have rejected that question as a Java novice as it isn't a clean and clear answer.

1 Answers1

0

your second statement would print '0' because 'exampleVar' has local scope to first method.

codebee
  • 824
  • 1
  • 9
  • 22
  • so me passing exampleVar into the private method and adding to it, will not change the value of exampleVar in the public method? – Christopher Jakob Feb 01 '16 at 03:01
  • even if that method was 'public', it wouldn't change it's value in first 'public' method because that's a local variable local to first method. To get the value from second method, you can return the value and assign in to 'exampleVar' in first method. Basically, you're not sharing variables, unless it's global. – codebee Feb 01 '16 at 03:04
  • i see so I would have to modify the code so that at some point we see example var = pmethod(...) with a return statement in pmethod – Christopher Jakob Feb 01 '16 at 03:06