The new feature of Java 7 is to add support for the String in the switch code block. Although it is only added to the String, it is much better than the previous version that only supports Integer, this function is supported in C #1.0 and is not only String, but all objects can be used in switch blocks (correct: C #2.0 switch can only use bool, char, integer, in The enum and string types and corresponding null values, A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type ).
The try-with-resource Statement
This new feature of Java 7 is no longer familiar to C #2.0 programmers. When coding resources that need to be released in a timely manner, the general practice is to call close () in the finally block () A Class One method is released, while C # provides a simple method to implement the same function. The Code is as follows:
The following is a code snippet:
Using (SqlConnection conn = new SqlConnection ("ConnectionStringHere ")){
// Do something
}
The above code is equivalent:
The following is a code snippet:
SqlConnection conn = new SqlConnection ("ConnectionStringHere ");
Try {
Conn. open ();
// Do somethind
} Finally {
Conn. close ();
}
Java 7 Implements similar functions, but uses try instead of using. The Code is as follows:
The following is a code snippet:
Try (BufferedReader br = new BufferedReader (new FileReader (path ))){
Return br. readLine ();
}
For C #, the use of using must meet a condition that the object declared in using implements the interface System. IDisposable. In this way, the code in the finally block can automatically call the Dispose ()
To release resources. The same requirement for java 7 is that the object must implement the java. lang. AutoCloseable interface or java. io. Closeable interface.
The For-Each Loop
Java 7 has finally implemented the for-each loop function. Although it is a syntax enhancement in Java 5, Java 6 does not have syntax updates, So I listed this enhancement as a new feature of Java 7. However, I don't understand why I still use for as a keyword, rather than directly introducing the foreach keyword like C #. Is it easier to understand. The for-each code for Java is as follows:
The following is a code snippet:
Void cancelAll (Collection c ){
For (TimerTask t: c)
T. cancel ();
}
For C #, the Code is as follows:
The following is a code snippet:
Void CancelAll (Collection c ){
Foreach (TimerTask t in c)
T. Cancel ();
}
It can be seen that there is no big difference between the implementation of the two, which is also concise and clear, but has a wide range of applicability. Java7 seems to be only able to implement in the collection (including the traditional array and generic set ), C # can be used in any System. IEnumerable or its generic version System. in the IEnumerable object.