Java Help

(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true))))

I am taking a Java class and somebody told me to use this one time on this forum, I am curious as to how this work, is it applying multiple classes to a variable?

It is combining several constructors.

The PrintWriter constructor requires a BufferedWriter, which requires a FileWriter, which requires a string and boolean.

Instead of creating separate variables of these classes, you can do it without giving every single one of them a variable name.

So they are dependent classes of another?

Yes they are all different classes.

Its like creating a variable, but there is no reference to it that you can use later on.

So all of these objects still exist in memory (the BufferedWriter, FileWriter, etc) but you can't reference them, only the PrintWriter.

Try it, write in your program 'new FileWriter("myFile.txt", true);'
But don't give it a variable name/type, just type that on its own line.
It still gets executed, and a FileWriter is created, but there is no way for you to access it directly.

More easily: in place where is (new FooBarClass()) an instance of FooBarClass will "appear".
It (code in OP post) does it a couple times for constructors, so it will:

  1. create a new FileWriter instance
  2. create new BufferedWriter with said FileWriter instance
  3. create new PrintWriter with said BufferedWriter instance
  4. assign said PrintWriter to variable out

in this order.

These are called anonymous objects because they are created and immediately passed to another function, not assigned to a variable so there is no name for them, therefore they are anonymous. It is important to note that you have no way of accessing an anonymous object after it is created so use them only when you know that you will not need them for anything else. They are great for simplifying code but hard to understand if you have never seen them before.

It's the 'Decorator design pattern' if you want to read on it more. All of the streams implement OutputStream, also they can be constructed using each other and internally they use each others interfaces. That means that data goes through multiple layers of streams and gets useful features added in a sort of a chain.

FileWriter -> BufferedWriter -> PrintWriter <= you use the most outer one - PrintWriter

So it works like this: you say you want to print an integer or something, PrintWriter has the methods to do it and to format so it goes ahead and does that, then it passes it's results to the OutputStream that it has in itself - BufferredWriter. This one keeps a buffer of data, to make writing more efficient, then when it's time to write for it, it passes it's buffer to FileWriter, which is responsible for writing the actual data to a file. That's it that's basically what's going on here.