2

When I pass the array "bucky" to the change function and in the change function if I use an enhanced for loop, the variable counter gives the error "The value of the local variable counter is not used"

But if I put the body of the for loop in an System.out.println(counter+=5) the error does not appear

class apples{
 public static void main(String[] args) {
  int bucky[]={3,4,5,6,7};

  change(bucky);
  }

  public static void change(int x[]){
    for(int counter: x){
     counter+=5;
    }
  }
}

Why does this code give the error I mentioned above since I'm using the counter variable in the enhanced for loop?

Edit - my objective is to change values of the array inside the "change" function and return it back to main.

12
  • 1
    Try and print the content of bucky in your main after calling change. You'll see why it thinks counter is not used. Commented Jul 12, 2022 at 9:36
  • You're "using" but without effect, counter is just a local variable that'll take thev values or the array one by one, but won't change the array values. It you're printing it then you need the variable, but for now there is on real use of having that variable Commented Jul 12, 2022 at 9:40
  • 1
    @ThulithaGurusinghe basically you don't. You use a normal loop. Commented Jul 12, 2022 at 9:44
  • 2
    I suggest you read Is Java "pass-by-reference" or "pass-by-value"? to have a more informed understanding on what you can and can't do with arrays and reference types more generally. Commented Jul 12, 2022 at 9:46
  • 1
    @ThulithaGurusinghe , shared answer. please check and confirm Commented Jul 12, 2022 at 10:01

1 Answer 1

2

Question is about updating original array values, then you have to use normal for loop so that each index values can be updated:

class apples{
 public static void main(String[] args) {
  int bucky[]={3,4,5,6,7};

  bucky = change(bucky);
  for(int b:bucky) {
        System.out.println(b);
    }
  }

  public static void change(int x[]){
    for (int i = 0; i < x.length; i++) {
        x[i]=x[i]+5;
    }
    return x;
  }
}
Sign up to request clarification or add additional context in comments.

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.