This week's book giveaway is in the Programmer Certification forum.
We're giving away four copies of OCP Oracle Certified Professional Java SE 11 Programmer I Study Guide: Exam 1Z0-815 and have Jeanne Boyarsky & Scott Selikoff on-line!
See this thread for details.
Win a copy of OCP Oracle Certified Professional Java SE 11 Programmer I Study Guide: Exam 1Z0-815 this week in the Programmer Certification forum!
  • 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
  • Liutauras Vilda
  • Junilu Lacar
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Paweł Baczyński
  • Piet Souris
  • Vijitha Kumara

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.
 
The only taste of success some people get is to take a bite out of you. Or this tiny ad:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!