hello frndz,
i was doing this program and then i encountered this strange problem...
it is a program in which i want to open two text files and then compare it..
It is giving me two errors:
1)variable f1 might not be initialised.
2)variable f2 might not be initialised.
and when i include a return statement in the catch blocks,it works....i cant understand why is it so
because it doesnt throw any exception...plz help...thanks

/*
Project 10-1
Compare two files.
To use this program, specify the names
of the files to be compared
on the command line.
java CompFile FIRST.TXT SECOND.TXT
*/



import java.io.*;
class compare_files
{
   public static void main(String p[]) 
   {
      int i=0,j=0;
	  FileInputStream f1,f2;
      try
	  {
	     try
		 {
		    f1=new FileInputStream(p[0]);
		 }
		 catch(IOException e)
		 {
		    System.out.println("Can't open the file!");
			
		 }
		 try
		 {
		    f2=new FileInputStream(p[1]);
		 }
		 catch(IOException e)
		 {
		    System.out.println("Can't open the file!");
			
		 }
	  }
      catch(ArrayIndexOutOfBoundsException e)
	  {
	     System.out.println("Array out of bounds!");
		 
	  }
	  try
	  {
	  do
	  {
	     i=f1.read();
		 j=f2.read();
		 if(i!=j)
		 break;
	  }while(i!=-1||j!=-1);
	  }
	  catch(IOException e)
	  {
	     System.out.println("I/O Exception!");
		 
	  }
	  if(i==j)
	  System.out.println("Both files are same");
	  else
	  System.out.println("Both files are different");
   }
}

Recommended Answers

All 4 Replies

Suppose f1=new FileInputStream(p[0]); fails. You will go to the catch block, print a message and continue. Eventually you get to i=f1.read(); but f1 will not have been initialised. That's the circumstance the compiler complained about.
Now if you have a return; in the catch block you will not continue after new FileInputStream fails, so you won't ever get to i=f1.read();, so there's nothing to complain about.
Same applies to f2.

yeah,i got it...thanx a ton mate

so,basically here the return statement sends the control out of main?

Not just the main() method. It returns to any method's caller.
The main() method is (usually) the one called by the java command.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.