+ 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); } }

22nd Jun 2021, 2:37 PM
kushal
6 odpowiedzi
+ 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.
22nd Jun 2021, 2:49 PM
Denise Roßberg
Denise Roßberg - avatar
+ 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
22nd Jun 2021, 2:42 PM
Jayakrishna 🇮🇳
+ 1
x++ means x is increased after "usage", so in case 1 it becomes 15 only after the printing
22nd Jun 2021, 2:42 PM
Lisa
Lisa - avatar
+ 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.
22nd Jun 2021, 2:43 PM
SammE
SammE - avatar
0
Case 1 First it will print and then increment. Case 2 First it will increment and then it will print.
23rd Jun 2021, 8:05 AM
Java Developer
Java Developer - avatar