0

Is

new PrintWriter(ExampleStream).print("Just Something");

same as

PrintWriter pw = new PrintWriter(ExampleStream);
pw.print("Just Something");
pw.close();

So will the PrintWriter close?

Cœur
  • 37,241
  • 25
  • 195
  • 267
nickkoro
  • 374
  • 3
  • 15

2 Answers2

1

No.

And technically the term anonymous in Java refers to creating a local class without a name. What you did is just creating an instance of a class without assigning it to a variable.

johnnyaug
  • 887
  • 8
  • 24
1

No, They both are not the same case

In the second example of your, question PrintWritter will get close immediately the moment pw.close() will get executed. while

In the first case of your question, printwriter will not get closed immediately. After calling --> new PrintWriter(ExampleStream).print() since you do not have any reference to its object thus you cannot use this same object again which means that it is eligible to be removed by garbage collector. As we cannot say when garbage collector will run that's why there is no certainty over when this object will be removed. one more important thing to keep in mind is that even though this object might be removed by garbage collector but that process is not same as pw.close()

siddhartha jain
  • 1,006
  • 10
  • 16