• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Jj Roberts
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Himai Minh
  • Carey Brown
  • salvin francis

java.io quesion

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • 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
  • 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.
 
Hold that thought. Tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic