• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Expanations os scjp code

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,

The out put of the below code is 10 & 40 can any explain me how it is 10 and 40.

public class Pass{
static int j=20;
public static void main(String argv[]){
int i=10;
Pass p = new Pass();
p.amethod(i);
System.out.println(i);
System.out.println(j);
}

public void amethod(int x){
x=x*2;
j=j*2;
}
}
 
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you passing i (which is 10 at that moment) to the p.amethod(i); method, you realy passing a copy of bit-pattern of i.
(00000000000000000000000000001010) - bin

So, next, inside p.amethod(i); you do x=x*2;. The value of x was 10 and now it became 20 as you can guess. But, "i" still has value of 10, couse x is just a copy of i, remember?

Next, j=j*2;. Well, j was 20 now it is 40. Simple. You accessing static variable (j) from instance method and, for example, IntelliJ IDEA will complain about it, but it's legal.

Next, p.amethod(i); is over - this meens:
- x variable is gone
- j has value of 40
- i has value of 10

So, the output is just like it should be, yeah?

[ July 08, 2005: Message edited by: George Bolyuba ]
[ July 08, 2005: Message edited by: George Bolyuba ]
 
It was the best of times. It was the worst of times. It was a tiny ad.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic