Possible Duplicate:
“using” keyword in java
I'm transitioning from C# to java, so please bear with me...
When reading a file in C#, you simply wrap it all in a big 'using' block, so that if you have an exception, the file will still be closed. Like so (maybe inaccurate but you get the idea):
using(FileStream fs = new FileStream("c:\\myfile.txt")) {
// Any exceptions while reading the file here won't leave the file open
}
Is there a convenient equivalent in java 5 or 6? I get the impression that lately java has been 'borrowing' some of the syntactic sugar from c# (such as foreach) and so i wouldn't be surprised if there's a java equivalent of using these days.
Or do i just have to use a try..finally block? 'Using' is just so much nicer i think...
C is a middle-level language as it binds the bridges between machine-level and high-level languages. Java is a high-level language as the translation of Java code takes place into machine language, using a compiler or interpreter. C is only compiled and not interpreted. Java is both compiled and interpreted.
The very first Java compiler was developed by Sun Microsystems and was written in C using some libraries from C++. Today, the Java compiler is written in Java, while the JRE is written in C.
As Java was inspired by C and C++, its syntax is similar to these languages. C++ is both a procedural and object-oriented programing language. Hence, C++ has features specific to procedural languages as well as features of object-oriented programming language. Java is a completely object-oriented programming language.
C is normally faster than Java, if it is written efficiently, but it always depends on the compiler. Some compilers support optimization on the compile time, to produce more efficient code, by removing redundant code and other unnecessary artefacts.
There's no equivalent syntax sugar using statements in Java 5 or 6. However, a proposal for automatic resource management which adds a familiar Disposable interface seems to have been accepted for Java 7 . Until then, you have to manually code a try...finally.
Have to use try .. finally
P.S. foreach (iteration over a collection) is not an invention of C#
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With