• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

java.io quesion

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi!
why the below code gives an error (variable fin not inetialized.) if i comment lines marked //(1) and //(2) .
======================================
import java.io.*;
class filerd
{
public static void main(String s[]) throws IOException
{

FileInputStream fin ;
int i;
try
{
fin = new FileInputStream(s[0]);
}
catch(FileNotFoundException e)
{
System.out.println("file not found");
return;// (1)
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Usage: filerd filename");
return;// (2)
}

do
{
i = fin.read();
if ( i != -1 ) System.out.print( (char) i );
}
while ( i != -1);
}
}
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If an exception gets thrown in the try-block and the return statements on lines 1 and 2 are commented out, it is possible (actually sure) that the variable "fin" might not have been initialized. The compiler is complaining because you are using that variable later in the do-block and you cannot use an uninitialized variable. To remedy to this, you should initialize fin to null when declaring it before the try-block.
If the return statements are not commented out, you can be sure that if no exception happen, fin will be initialize to some value and that if an exception occurs, the method will return and the do-block will never be executed, and thus, the variable "fin" won't be used, so there is no problem with the compiler.
 
Hey, I'm supposed to be the guide! Wait up! No fair! You have the tiny ad!
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic