Sunday, February 2, 2014

PriorityQueue Sorted By String Length

Source:
import java.util.Comparator;
import java.util.PriorityQueue;

public class MyPriorityQueue {
   public static void main(String[] args) {
      Comparator<String> com = new MyComparator();
      PriorityQueue<String> q = new PriorityQueue<String>(10, com);
      q.add("a");
      q.add("zz zz zz zz zz");
      q.add("cc cc cc");
      q.add("The cat in the hat");
      q.add("dddd");
      while (q.size() != 0) {
         System.out.println(q.remove());
      }
   }
}

// sort by string length of string
class MyComparator implements Comparator<String> {
   public int compare(String x, String y) {
      if (x.length() < y.length()) {
         return -1;
      }
      if (x.length() > y.length()) {
         return 1;
      }
      return 0;
   }
}

Output:
   $ java MyPriorityQueue 
   a
   dddd
   cc cc cc
   zz zz zz zz zz
   The cat in the hat

Test is a file is a symbolic link

Source:
import java.nio.file.*;
 
public class SymbolicLink {
 
   public static void main(String[] args) {
 
      Path path = Paths.get("./file.txt");
 
      if (Files.isSymbolicLink(path)) {
         System.out.println("file.txt is a symbolic link");
      } else {
         System.out.println("file.txt is note a symbolic link");
      }
 
   }
}

Output:
   $ java SymbolicLink 
   file.txt is a symbolic link

   $ file file.txt 
   file.txt: symbolic link to `foo.txt'

   $ ls -l file.txt 
   lrwxrwxrwx 1 dennis dennis 7 Feb  2 08:53 file.txt -> foo.txt

Check if two paths using symbolic links are the same file

Source:
import java.io.*;
import java.nio.file.*;

public class TestFile {

   public static void main(String[] args) throws IOException {

      Path p1 = Paths.get("./file1");
      Path p2 = Paths.get("./file2");

      if (p1.equals(2)) {
         System.out.println("Same paths");
      } else {
         System.out.println("Different Paths");
      }

      if (Files.isSameFile(p1, p2)) {
         System.out.println("Same File");
      } else {
         System.out.println("Different File");
      }

   }
}

Output:
   $ java TestFile 
   Different Paths
   Same File

   $ ls -l file2
   lrwxrwxrwx 1 dennis dennis 5 Feb  2 07:52 file2 -> file1

Java example using try-with-resources

Source:
import java.io.*;
 
public class TryWithResources {
 
   public static void main( String[] args ) {
 
      String path = "/tmp/file.txt";

      // No need to close the BufferedReader
      try (BufferedReader br = new BufferedReader(new FileReader(path))) {
         String line;
         while ((line = br.readLine()) != null) {
            System.out.println(line);
         }
      } catch(IOException e) {
      }
 
   }
}

Output:
   $ java TryWithResources 
   The cat in the hat
   
   $ cat /tmp/file.txt 
   The cat in the hat

Saturday, February 1, 2014

Example of a NullPointerException

Source:
public class NullPointerExample {
   public static void main(String[] args) {
      String str = "This is a string";
      System.out.println(str);
      System.out.println(str.length());

      str = null;
      System.out.println(str);

      // Should trigger NullPointerException
      System.out.println(str.length());
   }
}

Output:
   $ java NullPointerExample 
   This is a string
   16
   null
   Exception in thread "main" java.lang.NullPointerException
       at Foo.main(Foo.java:11)

How do I check if a file exists?

Source:
import java.io.File;
 
public class FileExists {
   public static void main(String[] args) {
 
      String str = "/etc/hostname";
      File f = new File(str);
      if(f.exists()) { 
         System.out.println("File " + str + " exist.");
      }
   }
}

Output:
   $ java FileExists 
   File /etc/hostname exist.

Try Catch Exception Matching

Source:
public class ExceptionMatching {
 
   public static void main(String[] args) {
      try {
         method();
      } catch (NullPointerException e) {
         System.out.println("Exception match: NullPointerException");
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception match: ArrayIndexOutOfBoundsException");
      } catch (Exception e) {
         System.out.println("Exception not matched " + e.toString());
      }
 
   }
 
   public static void method() {
      int x[] = new int[10];
 
      // this should throw an ArrayIndexOutOfBoundsException
      int y = x[21];
   }
}

Output:
   $ java ExceptionMatching 
   Exception match: ArrayIndexOutOfBoundsException

Example of a try catch finally block where finally is not run.

Source:
// Example of finally clause that does not run
public class FinallyNotRun {
   public static void main(String[] args) {
      try {
        System.out.println("Inside try");

        // should throw exception
        int x = 10 / 0;

      } catch (Exception e) {
        System.out.println("Inside catch");

        // Lets pretend to crash
        System.exit(0);

      } finally {
        // Will not run
        System.out.println("Inside finally");
      }
   }
}

Output:
   $ java FinallyNotRun 
   Inside try
   Inside catch

Example of a Shut Down Hook

Source:
public class ShutDownHook {

   public static void main(String[] args) {

      // try and run before shutdown
      Runtime.getRuntime().addShutdownHook(new Thread() {
         public void run() {
            System.out.println("Shutdown Hook is running....");
         }
      });

      try {
        System.out.println("Inside try");

        // throw  an exception
        int x = 10 / 0;

      } catch (Exception e) {
        System.out.println("Inside catch");
        // Shut down and test hook
        System.exit(0);

      } finally {
        // should not run
        System.out.println("Inside finally");
      }
   }
}

Output:
   $ java ShutDownHook 
   Inside try
   Inside catch
   Shutdown Hook is running....

Using Try Catch Finally blocks without Catch

Source:
// Using a try block without catch clause
public class TryFinally {
   public static void main(String[] args) {
      try {
        System.out.println("Inside try");
      } finally {
        System.out.println("Inside finally");
      }
   }
}

Output:
   $ java TryFinally 
   Inside try
   Inside finally