Win a copy of Five Lines of Code this week in the OO, Patterns, UML and Refactoring forum!
  • 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 ...
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
  • Piet Souris
  • Frits Walraven
  • Carey Brown

static method invocation problem

Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the below mentioned code why on Line 2 i am getting the o/p 300 instead of 100.

class Foo {
private int x;
public Foo(int x) {this.x=x; }
public void setX( int x) { this.x = x; }
public int getX() { return x; }

public class Gamma {

static Foo fooBar( Foo foo) {
foo = new Foo( 100);
return foo;

public static void main( String[] args) {
Foo foo = new Foo( 300);
System.out.print( foo.getX() + "-"); // Line 1

Foo fooFoo = fooBar( foo);
System.out.print( foo.getX() + "-"); // Line 2
System.out.print( fooFoo.getX() + "-"); // Line 3

foo = fooBar( fooFoo);
System.out.print( foo.getX() + "-"); // Line 4
System.out.print( fooFoo.getX()); // Line 5

Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
first you created an object of class Foo and uing its constructor method you assigned the value as 300.
then you created another object calded fooFoo usng the static methdo fooBar.
now fooFoo holding the new object which has the x values as 100.

i think that is the reson
Ranch Hand
Posts: 368
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Not sure why are you expecting the output of line 2 to be 100. In java, the parameters are passed by value. Hence anything you do inside the method fooBar has only an impact on the copy of foo passed to it. In "line 2" you are printing the value of original "foo" and not the copy. Hence the output is 300(as it was set for the original).

Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
These are changed based on local variables on methods do one thing draw a variables and object relational diagrams on stack and heap and then easily determine how the values are assigned.
all the best
We must storm this mad man's lab and destroy his villanous bomb! Are you with me tiny ad?
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
    Bookmark Topic Watch Topic
  • New Topic