Click here to Skip to main content
15,891,976 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
import java.io.* ;
public class i2
{
public static void main(String[] args)
{
InputStreamReader e = new InputStreamReader ( System.in) ;

int x=12 ; // statement 1

try{
x = e.read() ;
}
catch (IOException p)
{

System.out.println(" caught ");
}

System.out.println(x); // statement 2

}

}


When x is not initialized at statement 1 to any value then it gives compile time error at statement 2 and says x is not initialized .

But I think x should be initialized when read is invoked since read () returns an Integer .
If not then what is the Concept behind this ? Please help .

What I have tried:

I have run this on netbeans .
Posted
Updated 23-Apr-17 4:17am

1 solution

Because there is a path through the code where x has no value when your try to print it: if an exception is thrown in e.read execution will immediately continue from the catch block and x is not assigned a value.
 
Share this answer
 
Comments
toomanydoubts. 23-Apr-17 10:23am    
Then why does it work with BufferedReader ?
OriginalGriff 23-Apr-17 10:32am    
:laugh:
How would I know? I can't see your code using that!
toomanydoubts. 23-Apr-17 11:45am    
I got it , thanks !
OriginalGriff 23-Apr-17 11:49am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900