Answer to Question #171076 in Java | JSP | JSF for David

Question #171076

Write four different Java statements that each add 1 to integer variable x.


1
Expert's answer
2021-03-11T23:24:20-0500

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

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog