Java Programming - Objects and Collections - Discussion

10. 

/* Missing Statement ? */
public class foo 
{
    public static void main(String[]args)throws Exception 
    {
        java.io.PrintWriter out = new java.io.PrintWriter(); 
        new java.io.OutputStreamWriter(System.out,true); 
        out.println("Hello"); 
    } 
}
What line of code should replace the missing statement to make this program compile?

[A]. No statement required.
[B]. import java.io.*;
[C]. include java.io.*;
[D]. import java.io.PrintWriter;

Answer: Option A

Explanation:

The usual method for using/importing the java packages/classes is by using an import statement at the top of your code. However it is possible to explicitly import the specific class that you want to use as you use it which is shown in the code above. The disadvantage of this however is that every time you create a new object you will have to use the class path in the case "java.io" then the class name in the long run leading to a lot more typing.


Ala said: (Feb 23, 2012)  
It doesn't compile for me in NetBeans 6.7.1. It says "cannot find symbol constructor PrintWriter()"

Oversteer said: (Jul 31, 2012)  
This is totally wrong, there's no constructor for either PrintWriter or OutputStreamWriter and you also need System.out.println unless you have a static import in place.

Ankit337Ce said: (Oct 30, 2014)  
This code is not compile there are no suitable constructor found for PrintWriter().

Savita said: (Mar 4, 2015)  
Yes all you are right. Same error coming in my eclipse.

Raja said: (Apr 3, 2015)  
So, what is the correct answer?

Mac said: (May 10, 2015)  
Hey all!

Its true that here no need to import package but written code is incorrect and there is many way to correct the code.

Amarjit said: (Aug 17, 2015)  
Static import is needed because you are using out.println() without System.

Amarjit said: (Aug 17, 2015)  
Static import is needed because you are using out.println() without System.

Enrique said: (Jan 9, 2016)  
The statement is incomplete. It should state

java.io.PrintWriter out = new java.io.PrintWriter(new java.io.OutputStreamWriter(System.out), true);

It is to state that the auto flush is on for the PrintWriter that is using as a stream of characters the standard output.

Sorry, I am writing with my mobile phone.

Shree said: (Oct 25, 2016)  
Is that code is correct? Anyone describe it in detail.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.