+ 1
why is the output 14 case 1 but 15 in case 2?
//case 1 public class Main { public static void main(String[] args) { int x=14; System.out.println(x++); } } //case 2 public class Main { public static void main(String[] args) { int x=14; x++; System.out.println(x); } }
5 ответов
+ 4
Hello kushal
In case 1 you are using post increment inside the print method. So x got printed and after that incremented. If you would print x again you would get 15.
Or you can use pre increment.
System.out.println(++x); should give you 15.
In case 2 you just increment x. And in another statement you print x.
Since you have two different statements here, they will be processed one after the other.
In the first case you are doing two things in one statement and the order is defined by post increment.
+ 1
Read about post increment/decrement operators ..
Use search bar .it is answered lot of times ...
1st one. x++ does like value of x is used in instruction first then increments. so it first prints x value then increments..
2nd also doing same but you printing value as in next instruction after incrementation.
edit: for about post increment/decrement, may this help you ,similar one
https://www.sololearn.com/Discuss/1690694/?ref=app
+ 1
x++ means x is increased after "usage", so in case 1 it becomes 15 only after the printing
+ 1
++ x is pre-increment, that is, the value of x is first incremented and then assigned to x.
x ++ is post-increment, that is, the value of x is first assigned and then incremented.
0
Case 1
First it will print and then increment.
Case 2
First it will increment and then it will print.