try-with-resources
In Java, normally we open a file in a try block, and close the file in the finally block, see following :
Since JDK 7, a new “try-with-resources” approach is introduced. When a try block is end, it will close or release your opened file automatically.
try{
//open file or resources
}catch(IOException){
//handle exception
}finally{
//close file or resources
}
Since JDK 7, a new “try-with-resources” approach is introduced. When a try block is end, it will close or release your opened file automatically.
try(open file or resource here){
//...
}
//after try block, file will close automatically.
finally is no longer required. The file will be closed automatically after try block.
package com.opensourzesupport;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Example2 {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
{
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
String in Switch
public static void tradingOptionChooser(String day) {
switch (trading) {
case "Monday":
System.out.println("You selected Monday");
break;
case "Sunday":
System.out.println(" You selected Sunday");
break;
default:
throw new IllegalArgumentException();
}
}
No comments:
Post a Comment