What is the difference between - = e = -?

16

In java and other languages I have seen in some projects things like:

saldo -= 100 and sometimes saldo =- 100 , but I could never understand the difference between these two types, if there is any difference.

After all, is there a difference between performing an operation with -= and =- ?

    
asked by anonymous 13.03.2018 / 15:51

4 answers

21

saldo -= 100 is the same as saldo = saldo - 100 .

saldo =- 100 is assigning -100 to variable saldo . It is clearer to visualize like this:

saldo = -100

    
13.03.2018 / 16:00
13

The -= operator in java is used when we want to assign the value of a variable to the subtraction of a second value to the current value of this variable.

See this example:

int a -= b;

is the same as doing:

int a = a - b;

Already =- is not an operator, it is simply an assignment giving a negative sign to the value to be assigned to the right.

    
13.03.2018 / 16:00
12

Hello! I know your question has been healed by your friends. I'll just share one more explanation about it, because that's what I usually get when someone asks me the same thing. So it goes as "a complement" to the above answers.

See:

saldo = 500;
saldo -= 100;

System.out.println(saldo);

Output window prints:

run:
400

In this next logic, the first assignment of 500 is no longer valid for balance variable and the account owner still has a negative balance.

saldo = 500;
saldo =- 100;

System.out.println(saldo);

Output window prints:

run:
-100

Remembering that the account owner will also have a negative balance if it is done as follows:

saldo = 500;
saldo -= 600;

System.out.println(saldo);

Output window prints:

run:
-100
    
14.03.2018 / 01:12
0

I think you understood the concept of increment and decrement wrong, you see, in the first case you are actually decreasing the balance variable at -100, however; in the second case you are assigning the value -100 to the variable.

See the example below for a decrease:

class Teste {
    public static void main(String[] args) {
        int saldo = 14000;
        int i = 0;
        for(i=0; i < 5; i++) {
            saldo -= 100; //Aqui tem um decremento
            System.out.println("saldo : "+ saldo);
        }
    }
}

Your result is:

saldo : 13900
saldo : 13800
saldo : 13700
saldo : 13600
saldo : 13500

Now notice if you do the inverse, which is to put the signal - after the assignment signal =, getting sando =- 100

class Teste {
    public static void main(String[] args) {
        int saldo = 14000;
        int i = 0;
        for(i=0; i < 5; i++) {
            saldo =- 100; //Aqui tem uma atribuição, isto é, mesma coisa que saldo = -100;
            System.out.println("saldo : "+ saldo);
        }
    }
}

Result, it was -100 at all, because at each loop the balance variable was assigned the value of -100:

saldo : -100
saldo : -100
saldo : -100
saldo : -100
saldo : -100
    
05.04.2018 / 14:58