Tuesday, April 17, 2012

Observer Pattern


Observer Pattern:-
Here in this pattern, if one object changes it state then all its dependents are notified and updated automatically on each event.
Sample:
MyObservable:
import java.io.File;
import java.util.Observable;
public class MyObservable extends Observable {
      public void findFiles(File file) {
            if (file != null) {
                  if (file.isFile()) {
                        setChanged();
                        notifyObservers(file.getAbsolutePath());
                  } else {
                        File[] fileList = file.listFiles();
                        if (fileList != null) {
                              for (File f : fileList) {
                                    findFiles(f);
                              }
                        }
                  }
            }
      }
}
MyObserver:

import java.util.Observable;
import java.util.Observer; 
public class MyObserver implements Observer {
      public void update(Observable obj, Object arg) {
            System.out.println("\nReceived Response: " + arg);
      }
}
ObserverPattern:
import java.io.File;
public class ObserverPattern {
      public static void main(String[] args) {
        final MyObservable observable = new MyObservable();
        final MyObserver observer = new MyObserver();
       
        observable.addObserver(observer);
        observable.findFiles(new File("."));
      }
}

Monday, April 16, 2012

File Reader and File Writer

FileReader and FileWriter
This will helps you to understand the reading and writing concept of file.
Sample:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

public class FileReaderAndWriter {

      public static void main(String args[]) throws Exception {
            String path = "D:/Hello.txt";
            File file = new File(path);
            writeFile(file, " Write this.", true);
            readFile(file);
      }

      public static void readFile(File file) throws Exception {
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            String s = null;
            while ((s = br.readLine()) != null) {
                  System.out.println(s);
            }
            br.close();
            fr.close();
      }
     
      public static void writeFile(File file, String text, boolean append) throws Exception {
            FileWriter fw = new FileWriter(file, append);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(text);
            bw.close();
            fw.close();
      }    
}

JDK 7 : Features added in Java Programming

1. Binary Literals:
Now onwards numbers can also be expressed using the binary number system using prefix 0b or 0B.
Sample:
public class BinaryLiterals {
      public static void main(String[] args){
            // An 8-bit 'byte' value:
            byte aByte = (byte)0b00100001;
            System.out.println(aByte);
            // A 16-bit 'short' value:
            short aShort = (short)0b1010000101000101;
            System.out.println(aShort);
            char aChar = (char) 0b001100001;
            System.out.println(aChar);
            // Some 32-bit 'int' values:
            int anInt1 = 0b10100001010001011010000101000101;
            // The B can be upper or lower case.
            int anInt2 = 0B101; 
            System.out.println(anInt1);
            System.out.println(anInt2);
            // A 64-bit 'long' value. Note the "L" suffix:
            long aLong = 0b1010000101000101101000010100010101L;
            System.out.println(aLong);
      }
}
2. Strings in Switch Statements:
Now onwards you can use a String object in the expression of a switch statement.
Sample:
public class StringInSwitch {

    public static int getDayNumber(String day) {
        int dayNumber = 0;
       
        if (day == null) {
            return dayNumber;
        }

        switch (day.toLowerCase()) {
            case "sunday":
                dayNumber = 1;
                break;
            case "monday":
                dayNumber = 2;
                break;
            case "tuesday":
                dayNumber = 3;
                break;
            case "wednesday":
                dayNumber = 4;
                break;
            case "thursday":
                dayNumber = 5;
                break;
            case "friday":
                dayNumber = 6;
                break;
            case "saturday":
                dayNumber = 7;
                break;           
            default:
                dayNumber = 0;
                break;
        }
        return dayNumber;
    }

    public static void main(String[] args) {

        String day = "Tuesday";

        int returnedDayNumber = StringInSwitch.getDayNumber(day);

        if (returnedDayNumber == 0) {
            System.out.println("Invalid Day");
        } else {
            System.out.println(returnedDayNumber);
        }
    }
}
3. Try with resources :
The try-with-resources statement ensures that each resource is closed regardless of where the statement completes normally or abruptly.
Sample:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class TryWithResources {

      public static void main(String[] args) throws Exception{
            String path = "D:/TryWithResources.java";
            readFromFile(path);
      }
     
      public static void readFromFile(String path) throws Exception {

            try (BufferedReader br = new BufferedReader(new FileReader(new File(path)))) {
                  String s = null;
                  while((s=br.readLine())!=null){
                        System.out.println(s);
                  }
            }
      }
}
4. Handling more than one exception:
Now onwards a single catch block can handle more than one type of exception.
Sample: 
public class HMOE {

      public static void main(String[] args) throws Exception{
            try{
                  Class c = Class.forName("HMOE");
                  HMOE test = (HMOE) c.newInstance();
                  test.fun();
            }catch(ClassNotFoundException e){
                  System.out.println("Exception in loading a class.");
            }catch(InstantiationException|IllegalAccessException e){
                  System.out.println("Excpetion in creating instance.");
            }
      }

      public void fun(){
            System.out.println("fun");
      }
}
5. Rethorwing Exceptions with more inclusive type checking:
Now onwards compiler performs more precise analysis of rethrown exceptions than earlier releases of Java SE. This enables you to specify more specific exception types in the throws clause of a method declaration.
Sample:
public class RethrowingExceptions{
      public static void main(String[] args) throws Exception{
            rethrowException("First");
      }

 public static void rethrowException(String exceptionName) throws FirstException,SecondException {
    try {
      if (exceptionName.equals("First")) {
        throw new FirstException();
      } else {
        throw new SecondException();
      }
    } catch (Exception e) {
      throw e;
    }
  }
}

class FirstException extends Exception { }
class SecondException extends Exception { }
6. Underscores in numbers:
Now onwards you can put underscores between the numbers.
Sample:
public class UnderScoresInNumbers {
      public static void main(String[] args) throws Exception{
            long creditCardNumber = 1234_5678_9012_3456L;
            long socialSecurityNumber = 999_99_9999L;
            float pi = 3.14_15F;
            long hexBytes = 0xFF_EC_DE_5E;
            long hexWords = 0xCAFE_BABE;
            long maxLong = 0x7fff_ffff_ffff_ffffL;
            byte nybbles = 0b0010_0101;
            long bytes = 0b11010010_01101001_10010100_10010010;
            System.out.println(creditCardNumber);
            System.out.println(socialSecurityNumber);
            System.out.println(pi);
            System.out.println(creditCardNumber);
            System.out.println(hexBytes);
            System.out.println(maxLong);
            System.out.println(nybbles);
            System.out.println(bytes);
           
            //Valid:
            // OK (decimal literal)
            int v1 = 5_2;             
            // OK (decimal literal)
            int v2 = 5_______2;       
            // OK (hexadecimal literal)
            int v3 = 0x5_2;           
            // OK (octal literal)
            int v4 = 0_52;            
            // OK (octal literal)
            int v5 = 05_2;           
           
            //Invalid
            // Invalid; cannot put underscores adjacent to a decimal point
            float iv1 = 3_.1415F;
            // Invalid; cannot put underscores adjacent to a decimal point
            float iv2 = 3._1415F;     
             // Invalid; cannot put underscores prior to an L suffix
            long iv3 = 999_99_9999_L;
            // This is an identifier, not a numeric literal
            int iv4 = _52;            
             // Invalid; cannot put underscores at the end of a literal
            int iv5 = 52_;                     
            // Invalid; cannot put underscores in the 0x radix prefix
            int iv6 = 0_x52;           
            // Invalid; cannot put underscores at the beginning of a number
            int iv7 = 0x_52;                   
            // Invalid; cannot put underscores at the end of a number
            int iv8 = 0x52_;           
            // Invalid; cannot put underscores at the end of a number
            int iv9 = 052_;           
           
      }
}
7. Type inference for generic instance creation:
You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.
Sample:
import java.util.Map;
import java.util.HashMap;
import java.util.List;
public class Generics{
      public static void main(String[] args) throws Exception{
            //ealier jdk7 versions
            Map<String, List<String >> earlier = new HashMap<String, List<String>>();
            //in jdk7
            Map < String, List <String > >  now = new HashMap <>();
      }
}