File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes If conditional not branching correctly Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "If conditional not branching correctly" Watch "If conditional not branching correctly" New topic
Author

If conditional not branching correctly

Nikhil Pujari
Greenhorn

Joined: Oct 31, 2011
Posts: 21

The program below was taken from the official SunJava tutorial. It demonstrates how the ByteStream classes like FileInputStream and FileOutputStream work. The program reads characters from one file and puts them into another file. I made the input file - xanadu.txt - unavailable (i.e., did not create the file). This results in an exception at line 10 and control immediately jumps to the finally block.

My problem is with the two if statements in the finally block. The second if statement - if(out!=null) - evaluates to true and "out.close()" is executed even though "out" is equal to null. The problem, however, corrects itself when I put the if(out!=null) statement above the if(in!=null) statement. Why is the result changing based on the placement of the if statement?

Here's the code:



Einstein: A problem cannot be solved in the same state of mind in which it was created.
More motivation: http://www.youtube.com/watch?v=_7xfyDjCFqs
John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
welcome to the ranch

irrespective of where ever you place the if condition, the null check will return false for the variable out and the close() will not get executed.

Did you try using System.out.println() inside the if condition that checks out != null? If so are you sure the File not found exception occurs every time?
Harsha Smith
Ranch Hand

Joined: Jul 18, 2011
Posts: 287
That won't happen Nikhil!
Nikhil Pujari
Greenhorn

Joined: Oct 31, 2011
Posts: 21

@John Jai: Thanks, I'm happy to be here

Its strange. I tried using System.out.print inside " if(out!=null) ". It (System.out.print) was not executed, but the out.close() line was. This happened even though both those statements were within a block:

if(out!=null)
{
System.out.print("hello");//was skipped over
out.close();//was executed
}

btw, I am using NetBeans.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19784
    
  20

How do you know that out.close() was executed? If the creation of the InputStream indeed caused an exception, out would have remained null and the entire block would be skipped.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Nikhil Pujari
Greenhorn

Joined: Oct 31, 2011
Posts: 21

I used the line-by-line debugger in Netbeans.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: If conditional not branching correctly