Reputation: 699
I'm a Java newbie and stuck with this:
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
and
InputStreamReader ISR = new InputStreamReader(System.in);
BufferedReader BR = new BufferedReader(ISR);
What is the difference between them?
Also, is it compulsory to throw IOException when i'm getting inputs from user?
thanks.
Upvotes: 1
Views: 657
Reputation: 35572
Well, The question has been answered comprehensively. Yet, I would like to stress to use the first syntax since you can avoid the extra reference allocated. Moreover, allocating the extra reference has the potential of making the garbage collector in delaying its job. It does not necessarily mean that it would not garbage collect, but still it poses a slight overhead.
So, the answer would be try to use the first syntax at all times except that you need to do some manipulations with ISR variable later.
Upvotes: 0
Reputation: 41127
No difference, just first form is more compact and efficient if you might say because no extra reference for InputStreamReader
is created.
Upvotes: 0
Reputation: 2437
- Answer to 1st question There is absolutely no difference except that you will create a reference to InputStreamReader also which again you can avoid....I personally prefer avoiding it
- Answer to 2nd question
I/O Exceptions are checked exceptions i.e exceptions are checked at compile time while we have unchecked exceptions also in Java which are checked at run time
For more on checked and unchecked exceptions you can refer here
Upvotes: 2
Reputation: 2895
They will result in the same thing. a BufferedReader based on System.in in BR and br1.
If you need the ISR later on for some other reason then you would go with that version first. Just a matter of preference really, shorthand vs verbose.
Upvotes: 0
Reputation: 5363
Upvotes: 0
Reputation: 799500
There's no real difference between the two other than the fact that the first does not allow you to distinguish between exceptions from the instantiation of the two objects without careful inspection of the exception.
Upvotes: 0
Reputation: 625447
The only difference is that the second form explicitly saves the reference to the InputStreamReader to a variable, which may or may not be useful depending on if you do something with it afterwards.
Upvotes: 6
Reputation: 817208
The difference is that the second one is more verbose and uses a temporary variable for the InputStreamReader
. You get the first version by substituting ISR
with new InputStreamReader(System.in)
.
But both do the same thing. Advantage of the the later one is that you can still access the InputStreamReader
later in your code through the variable ISR
(if you have/want to).
Upvotes: 3
Reputation: 309008
No difference, just a matter of preference.
Those methods throw checked exceptions, so you're obliged to either handle them if you can or throw to the calling method.
Upvotes: 3