Wednesday, 29 June 2016

Strings in switch Statements

 Since: Jdk 1.7
public class SwitchStringExample {

      public static void main(String[] args) {
           
            String day = callSwich("Monday");
            System.out.println(day);
     
            /** NullPointerException */
            day = callSwich(null);
            System.out.println(day);
      }


      private static String callSwich(String day) {
           String typeOfDay;
           switch (day) {
               case "Monday":
                   typeOfDay = "Start of work week";
                   break;
               case "Tuesday":
               case "Wednesday":
               case "Thursday":
                   typeOfDay = "Midweek";
                   break;
               case "Friday":
                   typeOfDay = "End of work week";
                   break;
               case "Saturday":
               case "Sunday":
                   typeOfDay = "Weekend";
                   break;
               default:
                   throw new IllegalArgumentException("Invalid day" + day);
           }
           return typeOfDay;
      }
}

The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method; consequently, the comparison of String objects in switch statements is case sensitive. The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.

Note:
Make sure to add a NULL check to avoid NullPointerException.

Tuesday, 28 June 2016

How to Delete a Directory/Folder in Java using Recursion


package com.java.io;

import java.io.File;

/** To delete folders recursively. */
public class DeleteDirectory {

     public static void main(String[] args) {
           String folder = "C:/temp/Dir";

           /** delete directory recursively */
           recurDelete(newFile(folder));
     }

     public static void recurDelete(File file) {
           /** recursive loop termination. */
           if (!file.exists()) {
                return;
           }

           /** if directory, go inside and call recursively */
           if (file.isDirectory()) {
                for (File tFile : file.listFiles()) {
                     /** recursive call */
                     recurDelete(tFile);
                }
           }
          
           /** To delete files and empty directory */
           boolean isFileDeleted = file.delete();

           if(isFileDeleted) {
                System.out.println("File deleted: "+file.getAbsolutePath());
           }
     }
}

AutoCloseable and Closeable interface in Java : Since: JDK 1.7

java.lang interface AutoCloseable

Closeable extends AutoCloseable, and is specifically dedicated to IO streams.

Implementing AutoCloseable (or Closeable) allows a class to be used as a resource of the try-with-resources construct introduced in Java 7, which allows closing such resources automatically at the end of a block, without having to add a finally block which closes the resource explicitly.

try(open file or resource here) {
      //...
}
//after try block, file will close automatically.

void close() throws Exception

This method is invoked automatically on objects managed by the try-with-resourcesstatement.

While this interface method is declared to throw Exception, implementer are strongly encouraged to declare concrete implementations of the close method to throw more specific exceptions, or to throw no exception at all if the close operation cannot fail.
Throws: Exception - if this resource cannot be closed.

Example of AutoCloseable

class Resource implementsAutoCloseable {
     
      private String value;
     
      publicResource(String value) {
            this.value = value;
      }
     
      @Override
      public void close() throws Exception {
            /* De-reference the unused resource */
            this.value = null;
            System.out.println("Resource closed !!");
      }
     
      public String getValue() {
            return value;
      }
}

public class Demo {
      public static void main(String[] args) {

            try(Resource res =new Resource("Resource opened !!")) {
                  String str = res.getValue();
                  System.out.println(str+"\n");
            } catch (Exception e) {
            }
      }
}
Output:
Resource opened !!
Resource closed !!

try with resource Statement in Java

In Java 6, we open a file in a try block, and close the file in the finally block
try {
      //open file or resources
} catch(IOException) {
      //handle exception
} finally {
      //close file or resources
}

Disadvantages:
1. You'd have to check if your resource is null before closing it.
2. The closing itself can throw exceptions so finally had to contain another try – catch.
3. Programmers tend to forget to close their resources.

In 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.

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it.

The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

Example:

importjava.util.Scanner;

class Demo {
     public static voidmain(String[] args) {

           try(Scanner scan=new Scanner(System.in)) {
                String str = scan.next();
                System.out.println(str);
           }
     }
}

Benefits of using try with resources
1. Automatic resource management.
2. More readable code and number of lines of code is reduced.
3. No need to have finally block just to close the resources.
4. We can open multiple resources in try-with-resources statement separated by a semicolon.

try (BufferedReader br = newBufferedReader(new FileReader("file.txt"));Scanner scan=new Scanner(System.in))) {
      System.out.println(br.readLine());
} catch (IOException e) {
      e.printStackTrace();
}

5. When multiple resources are opened in try-with-resources, it closes them in the reverse order to avoid any dependency issue.

Note@5: We can extend the resource program to prove that.

Sunday, 26 June 2016

Calculate the power in log(n) complexity in Java

Using divide and conquer:


public classPowerUsingDnC {
     public static voidmain(String[] args) {
           int x = 5;
           int n = 7;

           /** To calculate the power of x^n. */
           int result = power(x,n);
          
           System.out.println(result);
     }

     private static int power(int x, int n) {
           int temp = 1;

           if(n==0) {
                return 1;
           }

           int result = 1;

           /** divide using original power function. */
           temp = power(x, n/2);

           /** conquer using temp value. */
           if(n%2==0) {
                result = temp*temp;
           } else {
                result = temp*temp*x;
           }
           return result;
     }
}
Related Posts Plugin for WordPress, Blogger...