We have seen the use of increment and decrement operators in Java.
And also how to use the assignment operators: +=, -=, *=, /= and %=
However, some care must be taken in their use, for example, the difference between this assignments
a=b++ and a=++b
You already studied and tested the alone use of:
a++ and ++a there is no difference.
However, take care at the time of assignment.
Come on, our 'hacker test':
Let b = 2;
Just looking and thinking, you would be able to find out how much it would be 'a' in each case:
a = b++;
a = ++b;
Explanataions
1. a = b++
Again, it is a shortcut in Java, a simpler way to write the following lines:
a = b;
b++;
2. a = ++b
Similarly, that is the shortcut that Java programmers use to represent the following lines of code:b++;
a = b;
'I'll have to memorize all these shortcuts in Java then? Damn, Java! '
No. You are a programmer, you do not decorate, you think.
I put 'hacker test' to make you think. Just use your brain and you will discover by looking.
In both cases, 'b' is incremented. The difference is that 'a' is assigned the value of 'b' before the increase in one and after the increase in another.
As I said, in Java, you can find out just by looking and thinking a bit.
See:
In the first example: a = b++
What order, 'b' or increment?
First the 'b'. After the increment occurs, '+ +'.
So, 'a' will receive the value of 'b' first, so a = 2
Only after 'b' will be incremented and will become b = 3.
In the second example: a = ++b
What to order: 'b' or increment?
The first increment, ' ++', just after appears the letter 'b'.
Thus, the first increment occurs, so b = 3.
Only after that is assigned this value to 'a', so a=3
As the bible of Java programmer: compile and see the truth.
Here's the code:
public class Increment {
public static void main(String[] args) {
int a,
b=1;
System.out.println("b = " + b);
System.out.println("a = b++ ");
a = b++;
System.out.println("So: a = " + a);
System.out.println();
System.out.println("b = " + b);
System.out.println("a = ++b ");
a = ++b;
System.out.println("So: a = " + a);
}
}
No comments:
Post a Comment