• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Bear Bibeault
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Piet Souris
  • salvin francis
  • Stephan van Hulst
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Jj Roberts

Increment Operator

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Guys i am currently preparing for OCA 1Z0 -808 exam
i have a doubt in the below code . I assume that the output will be
1111
2222
(explaination:
int m = 1111;

   {
       m = m++; // the value is 1111}
and when it comes here
int methodOfY()
   {
       return m-- + --m;// the value will be 1112 + 1110
   })

But the output that i get is
1111
2220

Could someone please help me understand the logic behind this code

class X
{
   int m = 1111;

   {
       m = m++;

       System.out.println(m);
   }
}

class Y extends X
{
   {
       System.out.println(methodOfY());
   }

   int methodOfY()
   {
       return m-- + --m;
   }
}

public class MainClass
{
   public static void main(String[] args)
   {
       Y y = new Y();
   }
}
 
Saloon Keeper
Posts: 12493
269
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's because the following statement:
does something else than what you're expecting it to do, which is just:
 
Marshal
Posts: 71070
292
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Priyanka Leo wrote:. . .. . .

Where did you get 1112 from? Because of the error you had in the first part of the code, that comment should read,So frequently do we see questions about...that we have an FAQ about it. Scroll down about half a page.

Please always use the code button when posting blocks of code.
 
Priyanka Leo
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for the clarification guys!!
 
Campbell Ritchie
Marshal
Posts: 71070
292
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's a pleasure
 
Blood pressure normal? What do I change to get "magnificent"? Maybe this tiny ad?
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic