• 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
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

Passing OutputStream as a parameter

 
Ranch Hand
Posts: 681
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Bartender
Posts: 9626
16
Mac OS X Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Rancher
Posts: 4801
50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Yeah, but does being a ninja come with a dental plan? And what about this tiny ad?
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic