Reputation: 1815
import java.io.*;
interface MyIOAction
{
void ioAction(Reader rdr) throws IOException;
}
class MyClass
{
public static void main(String args[]) throws IOException
{
Reader rdr1;
int read = rdr1.read(); //Statement 1
MyIOAction myIO = (rdr2) ->
{
int ch = rdr2.read(); //Statement 2
};
}
}
In the above code, Statement 1
produces the following error
Variable
rdr1
might not have been initialized
Whereas Statement 2
compiles successfully.
So, why the same error as in Statement 1
is not produced in the Statement 2
?
Upvotes: 0
Views: 34
Reputation: 2820
Local variables(variables declared inside a method body) rdr1
should be initialized before use . However this rule
does not applies to class variables(instance variables).They get their default type value.
As far as rdr2
is concerned , it is Initialised when the method is called. More info about Lambda Exp here
public static void main(String args[]) throws IOException
{
Reader rdr1; // local variable should be initialized before use
int read = rdr1.read(); //Statement 1
MyIOAction myIO = (rdr2) -> // initialized when method is called.Lambda Exp.
{
int ch = rdr2.read(); //Statement 2
};
}
Upvotes: 0
Reputation: 234847
In statement 2, rdr2
is in essence a formal argument to a method. It is initialized when the method is invoked. See the Lambda Quick Start or Lambda Expressions tutorials for more information about what's going on with statement 2.
Upvotes: 1