Write four different Java statements that each add 1 to integer variable x.
Hi, this is the code.
public static void main(String[] args) {
int x = 0;
x=x+1;
System.out.println("Way 1: x+1 = " + x);
x=0;
x++;
System.out.println("Way 2: x++ = " + x);
x=0;
++x;
System.out.println("Way 3: ++x = " + x);
x=0;
AtomicInteger xAtomic = new AtomicInteger(x);
xAtomic.incrementAndGet();
x = xAtomic.intValue();
System.out.println("Way 4: xAtomic.incrementAndGet() = " + x);
}
The output is:
Way 1: x+1 = 1
Way 2: x++ = 1
Way 3: ++x = 1
Way 4: xAtomic.incrementAndGet() = 1
Comments
Leave a comment