2

Why we can't call println() method with help of PrintStream class where out is object of this class?

import java.io.*;

class Demo {
    public static void main(String[] args) {
        PrintStream.out.println("Hello");
    }
}
Adrian Toman
  • 11,316
  • 5
  • 48
  • 62
Java Criminal
  • 37
  • 1
  • 4

2 Answers2

7

Why we can't call println() method with help of PrintStream class where out is object of this class:

 PrintStream.out.println("Hello");

Three reasons:

a) it's not static - you need an instance of the PrintStream class

b) it's got protected visibility - so its not accessibe.

c) the out variable is actually an OutputStream - so it doesn't have a println method.

To use a PrintStream, you want to do something like this:

final PrintStream ps = new PrintStream(new FileOutputStream(new File(filename)));
ps.println("Now is the time for all good men to come to the aid of their party.");
ps.close();

Consult the Javadoc for more information.

Greg Kopff
  • 15,945
  • 12
  • 55
  • 78
  • if we make instance of ti\his class then it is possible? – Java Criminal May 20 '12 at 03:50
  • No, you can't access the `out` variable directly -- the `protected` visibility prevents this -- you want to invoke one of the `public` methods on the `PrintStream` class. See also Thihara's answer - to print to the console, you can use `System.out.println("foo")`. – Greg Kopff May 20 '12 at 03:55
  • 1
    And a third reason: PrintStream.out is of type OutputStream, not PrintStream, so it doesn't have a println() method. The entire construction makes no sense. – user207421 May 20 '12 at 04:46
  • Yes this implementation is CRIMINAL :-D But I guess he already know that, hence the name ;-) – Thihara May 20 '12 at 04:53
  • "protected"? i dont think so – Arun Raaj Aug 03 '18 at 00:30
1

Yep what Greg says. Also if you want to print to the console you can just use System.out.println("Manga Bunga");

And if you want to use PrintStream use the println() method after instantiating a PrintStreat object.

Thihara
  • 7,031
  • 2
  • 29
  • 56