0

I'm trying to do Class.Method()++ but it won't work.

Simple example :

Person Class

public class person {
    private int age;

    public void age(int value) {
        this.age = value;
    }
    public int age() {
        return this.age;
    }
}

In Main Class

Following statements get an error about p1.age()++ :

public static void main(String[] args) {
     person p1 = new person();
     p1.age(p1.age()++); // Get an error
}

But below works fine :

public static void main(String[] args) {
         person p1 = new person();
         p1.age(p1.age()+1); // It works fine
    }

The main question :

Why p1.age()++ get error but p1.age()+1 doesn't ?

P.S :

I know i can do this :

person p1 = new person();
    int myAge = p1.age();
    p1.age(myAge++);
Hamed Kamrava
  • 12,359
  • 34
  • 87
  • 125

4 Answers4

6

Because

x++;

is short for

x = x + 1;

and in your case would be

p1.age() = p1.age() + 1; // ERROR

and you can't have a method call on the left hand side of an assignment.

jlordo
  • 37,490
  • 6
  • 58
  • 83
  • 5
    Not quite `x = x+1` would evaluate to the new value of `x`, `x++` evaluates to the old value of `x`. – sepp2k Jul 23 '13 at 19:50
  • `x++` and `x = x + 1` are *not* completely equivalent. There are cases where the first compiles and the second doesn't. – arshajii Jul 23 '13 at 19:51
  • When you use x++ in a statement, you can treat it as returning x and then incrementing the variable x by 1. You can't increment a constant (like a method return) by 1. – ameed Jul 23 '13 at 19:53
3

method()++ means method() = method() + 1

which is wrong because you can't assign a value to method

Ankit
  • 6,554
  • 6
  • 49
  • 71
0

++, the way you used, is a postfix operator. It will use the value, then increment it.

A method returns a value. Is not a value.

From Java Language Specification:

The result of the postfix expression must be a variable of a type that is convertible (§5.1.8) to a numeric type, or a compile-time error occurs.

Jean Waghetti
  • 4,711
  • 1
  • 18
  • 28
0

p1.age returns a value, but the increment operator ++ reads the value and tries to assign it. Methods cannot take assignments in Java, so you get the compiler error.

user3001
  • 3,437
  • 5
  • 28
  • 54