-5
public static int someFunc(int a, int b){
    while(a <=b){
        a+= 1;
        return a;
    }
    return b;
}

so i was expecting it to return the new value over and over but it didnt, once i executed the code and saw for myself that, i realised it had something to do with pass by value or by reference which is something i dont really understand! can someone explain?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Reddevil
  • 125
  • 3
  • 12
  • Why would it _return a new value over and over_? Do you understand what a `return` statement is and does? – Sotirios Delimanolis May 22 '15 at 18:21
  • 3
    I'm editing it out because it is not meaningful to the question. Please don't edit it back in. If you don't agree, you can flag for review or post on meta. Don't put noise into your questions. Read the Help Center. – Sotirios Delimanolis May 22 '15 at 18:23
  • @SotiriosDelimanolis i believe i do but since we have a while loop i got confused since the condition of the while loop is still true therefore i was expecting the the body of the while loop to get executed over and over – Reddevil May 22 '15 at 18:32
  • A `return` statement stops execution of the method it appears in. – Sotirios Delimanolis May 22 '15 at 18:33
  • @SotiriosDelimanolis so if i had written the following someFunc( int a, int b) { if (a<=b)return a+b; return b;} it wouldve done the same right? i know its write buy why does it do that? – Reddevil May 22 '15 at 18:35
  • https://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html – Sotirios Delimanolis May 22 '15 at 18:39

2 Answers2

3

The immediate problem is that return returns! Nothing after it can be executed. You can't have a meaningful loop with an unconditional return in it.

As far as the other, no. That's not the issue as you return the new value of a. The a you passed in remains unchanged which is the pass by reference/value you speak of. Java is pass by value.

public class JHelp {

    public static void main(String...args) {
        JHelp j = new JHelp();
        int a = 1;
        System.out.print(j.f(a));
        System.out.print(a);
    }

    int f(int a ) {
        a += 1;
        return a;
    }
}

Will give you an output of:

21

ChiefTwoPencils
  • 13,548
  • 8
  • 49
  • 75
-2

because the return instruction exits the code hence the methods done its job it doenst need to iterate again once it reaches the return instruction, i however would have done it if the return instruction wasnt reached.

Reddevil
  • 125
  • 3
  • 12