Mariin5
Mariin5

Reputation: 19

Why are these results different between two types code of Java?

First of all, my mother language is not English.

Now I study Increment(++) ande Decrement(--) operators of Java. I tried an issue. But the result of mu code differents from my expectation.

Issue

My code I wrotea code like this ;

public class Main{
    public static void main(String[] args){
        int x = 19;
        int inc = x++;
        int dec = x--;

        System.out.println(inc);
        System.out.println(dec);

    }
}

My Expectation I expected the result will be "20" and "19".

Result However, running result was "19" and "20". I still can't understand why the result was "19" and "20".

The thing I want to know

  1. Why the result of running my code was "19" and "20".
  2. If the result of running my code will be "20" and "19", where should I fix my code?

Upvotes: 1

Views: 67

Answers (2)

MuhammedMurad97
MuhammedMurad97

Reputation: 9

When you are using the x++ you are doing a postincrement which means the variable value (in your case x's value) is used first and then incremented after the expression. When you are using the ++x you are doing a preincrement which means the variable value is incremented and uses the new value inc in the expression.

so use preincrement for both and the output shall look like your expectations.

Upvotes: 0

So actually x++ and x-- returns x and then increment x by 1. If you want to firstly increase value by 1 and only then return a value you can use ++x and --x:

int x = 19;
int inc = ++x;
int dec = --x;

System.out.println(inc);
System.out.println(dec);

Upvotes: 0

Related Questions