0

Why does x also increase when we print y?

public class Program { public static void main(String[] args) { int x = 34; int y = ++x; System.out.println(y); } } If I was to print x why does that also increase. It only makes sense for y to increase?

11th Jul 2018, 4:07 PM
Chris Welham
Chris Welham - avatar
5 Respuestas
+ 1
ok i got it. ++x changes the value of x to x+1 and then it gets stored in variable y. So, x become x+1. If you don't want x to change you should do x+1 instead of ++x.
11th Jul 2018, 4:28 PM
Satyam
+ 1
I dont know about Java much but doesn't ++x increment the value of x by 1? so it increases.
11th Jul 2018, 4:18 PM
Satyam
+ 1
Chris Welham first ++x changes x into x+1. This then gets stored in y.
12th Jul 2018, 2:23 PM
Satyam
0
Well the way i see it is i set y to be x + 1 but shouldnt x stay as 34
11th Jul 2018, 4:19 PM
Chris Welham
Chris Welham - avatar
0
So y is just x and x is ++x
11th Jul 2018, 4:30 PM
Chris Welham
Chris Welham - avatar