-1

Program 1:

public class ValAndRefTypes {

public static void main(String[] args) {
    int x=5;
    addOneTo(x);
    System.out.println(x);

}

static int addOneTo(int num){
    num=num++;
    return(num);//Outputs 5
}

Program 2:

public class ValAndRefType1 {

public static void main(String[] args) {
    int a=2,b=3;
    System.out.println("The sum is: " + Add(a,b));
}

 static int Add(int num,int num1){
    num++;
    num1++;
    return(num+num1); //Outputs 7
}

Why does the first program not output the incremented value of the variable 'x', but the second program outputs the incremented value of variables 'a' and 'b'?

I also would like to ask whether this has any relation with Value types and Reference types.

TIA for the answer!

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
Chethan
  • 11
  • 3

3 Answers3

1

Two reasons:

First:

In the first program, the addOneTo function is adding the value and returning the new value (well, attempting to, but we'll get to that below), but that returned value is ignored:

addOneTo(x);

You don't assign the new value to anything. Assign it back to the variable:

x = addOneTo(x);

Whereas in the second program this works because you are using the returned value. You're including it as part of the output:

System.out.println("The sum is: " + Add(a,b));

Second:

This line is very misleading, and is confusing the logic being implemented:

num=num++;

num++ increments num, but evaluates to the previous value of num. So the assignment results in assigning back that previous value. This could work instead:

num = ++num;

Though that's still clouding the logic for no reason. Just increment directly:

num++;

or if you prefer being more explicit:

num = num + 1;

In the second example, that's how you increment:

num++;
num1++;
David
  • 208,112
  • 36
  • 198
  • 279
0

In your first program, you are printing "x" which has value 5. Only calling a function does not change the value of "x". If you want to print incremented value the program looks like this:

public class ValAndRefTypes {

public static void main(String[] args) {
int x=5;
System.out.println(addOneTo(x));

}

static int addOneTo(int num){ num=num++; return(num);//It returns 6 not 5 }

bpp
  • 1
-1

Let me make a small change to program 1. You can't mutate a primitive.

public static void main(String[] args) {
    int x=5;
    int y = addOneTo(x);
    System.out.println(y);
}

static int addOneTo(int num){
    num=num++;
    return(num);
}
bcr666
  • 2,157
  • 1
  • 12
  • 23
  • I believe the idea was to have the code explained as is, not to change it so it makes more sense. – Bernhard Barker Mar 12 '17 at 18:18
  • This seems kind of misleading. You certainly *can* assign the result of `addOneTo(x)` back to `x`. – David Mar 12 '17 at 18:19
  • Can you explain in detail? By just assigning the returned value of the function to another variable the output changes? – Chethan Mar 12 '17 at 18:20