• 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
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Jj Roberts
  • Tim Holloway
  • Piet Souris
  • Himai Minh
  • Carey Brown
  • salvin francis

Passing OutputStream as a parameter

Ranch Hand
Posts: 638
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a method that create a output stream

I have  a method that calls it

At System.out.println(); output contains data.
But when I call handleRequest

output.toString() returns a null.

outputStream is an object, so I though I could treat it as one when passing it around as an object.

Thanks for any help
Posts: 9615
Mac OS X Linux Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java uses something called Pass By Value.  This means that when you pass an object to a method, the method receives a copy of the reference to the object, not the original reference to the object in the caller.  Changing the "output" reference in handleRequest does not change the value of "output" where you called it.  What you can do is change the contents of output in handleRequest.  Since the two references point to the same instance of OutputStream, you would get the desired result.  
I think it is a better practice to use a return value rather than to change a method parameter (that's why Java is Pass By Value in the first place).  It is easier to see where changes are taking place in the code and has less of a chance for unintended side effects.
Posts: 4734
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the second example output.toString() will throw a NullPointerException, not return a null.

In the first example, the System.out line will print nothing at all.
rubbery bacon. crispy tiny ad:
the value of filler advertising in 2020
    Bookmark Topic Watch Topic
  • New Topic