P
P
progforgood2016-11-28 19:07:20
Java
progforgood, 2016-11-28 19:07:20

Incomprehensible display of the results of several successive in(de)crementations?

class  temp{
  public static void main(String args[]){
    int t = 011;
    System.out.println(t);    //9
    System.out.println(t++);  //выводится на экран 9, почему не 10?
    System.out.println(t++);  //10
    System.out.println(t++);  //11
  }
}

The output I expected was:
9
10
11
12

and got:
9
9
10
11

Please explain why I have what I have?
PS: taking this opportunity, question number two: how to display numbers not in decimal form, but in octal form, so that the output would start with the octal number 12, or does incrementation in this example mean: first transfer to decimal and then ++?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Денис Загаевский, 2016-11-28
@progforgood

A post-increment (i++) differs from a pre-increment in that it returns the value it had before the increment, changing the value of the variable itself. This is clearly seen in the C++ example . The semantics in the languages ​​is the same.
To convert to octal, you can use the Integer.toOctalString(int) method;

I
Igor, 2016-11-28
@DMGarikk

try writing System.out.println(++t);

V
Vasily Melnikov, 2016-12-01
@BacCM

There is already a correct answer, so I'll just give advice :).
Avoid using unary operators in expressions and function calls. Compilers are good at optimizing

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question