1

what would be the output of

1).

     int j=0;
     for (int i=0; i<100; i++) j=j++;
     System.out.println(j);

I thought j=j++; will be equal to

 int j2 = j;
    j = j+1;

so I was expecting the out put would be 99. but when I compiled on eclipse output was 0.

2). and I could not understand what is the logic behind

  ((int)(char)(byte) -1)

When ran it on eclipse I got output as 65535.

tom
  • 8,189
  • 12
  • 51
  • 70
Learner
  • 544
  • 1
  • 8
  • 19
  • it should go in code.stackexchange – Pramod S. Nikam Sep 18 '14 at 08:40
  • 1
    1. One question per question please. 2. Try to give your question a name that describes the problem. – Keppil Sep 18 '14 at 08:44
  • Duplicates: 1. http://stackoverflow.com/q/2750216/1343161 2. http://stackoverflow.com/q/7500523/1343161 – Keppil Sep 18 '14 at 08:46
  • J++ is the same as j = j +1 – Luis Alves Sep 18 '14 at 08:46
  • I do not want to be rude, but I think most of these things are nicely explained in the Internet, and in most programming books. If you want to learn a programming language, it is definitely helpful to read a related book. StackOverflow's is a place to discuss more serious (or should I say, advanced) matters. Learn the basics and try again. You may find programmers.stackexchange.com also useful. You should also check the terms of use in the help center for both programmers and SO – Ivaylo Slavov Sep 18 '14 at 08:56
  • Surely..I will keep that in mind. – Learner Sep 18 '14 at 09:41

2 Answers2

5
j=j++;

is functionally equal to

int xxx = j;
j++;
j = xxx;

So the value of j stays the same. (Because the right side is evaluated first, including the increment, then the result is assigned to j)

As for ((int)(char)(byte) -1), a char is 16bit in size and unsigned, so the bit pattern of -1 results in 65535.

Erich Kitzmueller
  • 36,381
  • 5
  • 80
  • 102
1

This is because the ++ works as follows:
a = 0;
a = a++; // a will get the assignment of the current value of a before the increment occurs so a = 0 in here

However, in the next case here:
a = 0;
a = ++a; // a will get the assignment of the incremented value of a so a = 1 in here

Multithreader
  • 878
  • 6
  • 14