Select the execution result of the following program
java.java
public class Main{
public static void main(String[] args){
int a = 10;
int b = a++ + a + a-- - a-- + ++a;
System.out.println(b);
}
}
A.7 is displayed B.32 C.33 D.43 E. A compile error occurs F. Exception is thrown at runtime
The answer is b. There is a problem with the behavior of the prefix and suffix increment operators.
In ++ a, a = a + 1 is set before the operation is performed. In a ++, a = a + 1 is added after the operation. Therefore a = 10; b = a++ + a + a-- - a-- + ++a;
a = 11; b = 10 + a + a-- - a-- + ++a;
a = 11; b = 10 + 11 + a-- - a-- + ++a;
a = 10; b = 10 + 11 + 11 - a-- + ++a;
a = 9; b = 10 + 11 + 11 - 10 + ++a;
a = 10; b = 10 + 11 + 11 - 10 +10;
The resulting answer is 32.
If you do this with TypeScript
TypeScript.ts
var a:number = 10;
var b:number = a++ + a + a-- - a-- + ++a;
console.log(b);
It looks like this. The behavior of operators such as increment is roughly the same between languages, so you can use them in the same way.
Recommended Posts