1

What is difference between creating object and then passing it to parameter vs declaring an object as an argument in the constructor of class. Like what is difference between 1) and 2)?

1)

InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);

2)

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

1 Answer 1

2

Two differences come to mind:

  1. In theory, with the all-in-one construction, if the outer constructor threw an exception, you'd have an instance of the inner object lying around that you never call close on (because you don't have a reference to it that you can use to do that), so it won't get closed until finalization (if then). In practice, I don't think BufferedReader's constructor can throw an exception, but...

    This is part of what Java's new try-with-resources statement is designed to help with:

    try (
        InputStreamReader isr=new InputStreamReader(System.in);
        BufferedReader br=new BufferedReader(isr);
    )
    {
        // do your stuff here
    }
    

    Using try-with-resources, you can be sure that even if the second constructor throws, the first object gets closed correctly.

    Note that when you use try-with-resources with multiple declarations as above, close is called in the reverse order in which they appear, which is usually exactly what you want (in this case, br.close() is called before isr.close()).

  2. With the all-in-one construction, you're assuming that the outer object will close the object you pass it when you close it (because, again, you have no reference to the inner object to use to close it). This is true of BufferedReader, but may not be universally true. Again try-with-resources helps there, by ensuring that close is called.

If you're dealing with objects that don't need close or similar, there's not much difference between the two at all. It's easier to single-step over the separate statements when debugging than it is the all-in-one construction, but other than that, there's not much in it.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.