Saturday, May 16, 2015

Android ContentObserver Tutorial for dummies

Hi all,

The ContentObserver it is the most easiest way to get a notification about changes according Uri.

Here is a step by step tutorial How to implement ContentObserver in Android:

1. Create an interface for ContentObserver callback methods:

 public interface ContentObserverCallback {  
   void update();  
 }  

2. Create a class with ContentObserver logic:

 public class MyContentObserver extends ContentObserver {  
   private static final String LOG_TAG = "MyContentObserver";  
   private ContentObserverCallback contentObserverCallback;  
   public MyContentObserver(ContentObserverCallback contentObserverCallback) {  
     // null is totally fine here  
     super(null);  
     this.contentObserverCallback = contentObserverCallback;  
   }  
   @Override  
   public void onChange(boolean selfChange) {  
     this.onChange(selfChange, null);  
   }  
   @Override  
   public void onChange(boolean selfChange, Uri uri) {  
     // this is NOT UI thread, this is a BACKGROUND thread  
     Log.i(LOG_TAG, "Received onChange");  
     contentObserverCallback.update();  
   }  
 }  

3. Create an Activity or a Fragment with implementation of a ContentObserver callback interface:

 public class MainActivityFragment extends Fragment   
        implements ContentObserverCallback { ... }  

4. Implement method for a ContentObserver callback:

   /**  
    * this is a callback method for a content observer  
    * runs NOT in UI thread  
    */  
   @Override  
   public void update() {  
     getActivity().runOnUiThread(new Runnable() {  
       @Override  
       public void run() {  
         // TODO add here any needed logic  
         // set a count number to a TextView  
         txtCount.setText(String.valueOf(++count));  
       }  
     });  
   }  

5.  Register Content Observer object for some Uri. Do it in onResume:

   @Override  
   public void onResume() {  
     super.onResume();  
     if (myContentObserver == null) {  
       myContentObserver = new MyContentObserver(this);  
     }  
     // register ContentObserver in onResume  
     getActivity().getContentResolver().  
         registerContentObserver(  
             // observable uri  
             MyContentProvider.uriTest,  
             true,  
             myContentObserver);  
   }  

6. Unregister Content Observer object. Do it always in onPause to prevent memory leak:

   @Override  
   public void onPause() {  
     super.onPause();  
     // always call unregisterContentObserver in onPause  
     // skipping this call will produce memory leak  
     getActivity().getContentResolver().unregisterContentObserver(myContentObserver);  
   }  

7. Inside ContentProvider in methods like update(), insert() or delete() call notifyChange()

   @Override  
   public int update(Uri uri, ContentValues values, String selection,  
            String[] selectionArgs) {  
     // send update notification to observer  
     getContext().getContentResolver().notifyChange(uri, null);  
     return 1;  
   }  


That's all! Next time any changes with an observable Uri will send notification to your ContentObserver implementation.

Here is a link to the GitHub repository with full code example: ContentObserverTutorial


Thank you

Sunday, August 28, 2011

Enforce the singleton property with a private constructor or an enum type


singleton is simply a class that is instantiated exactly once. Singletons typically represent a system component that is intrinsically unique, such as the window manager or file system. Making a class a singleton can make it difficult to test its clients, as it’s impossible to substitute a mock implementation for a singleton unless it implements an interface that serves as its type.

Before release 1.5, there were two ways to implement singletons. Both are based on keeping the constructor private and exporting a public static member to provide access to the sole instance. In one approach, the member is a final field:

// Singleton with public final field 
public class Elvis {
    public static final Elvis INSTANCE = new Elvis();
    private Elvis() { }

    public void leaveTheBuilding() {
        
    }
}

The private constructor is called only once, to initialize the public static final field Elvis.INSTANCE. The lack of a public or protected constructor guarantees a “monoelvistic” universe: exactly one Elvis instance will exist once the Elvis class is initialized—no more, no less. Nothing that a client does can change this, with one caveat: a privileged client can invoke the private constructor reflectively with the aid of the AccessibleObject.setAccessible method. If you need to defend against this attack, modify the constructor to make it throw an exception if it’s asked to create a second instance.

In the second approach to implementing singletons, the public member is a static factory method:

// Singleton with static factory 
public class Elvis {
    private static final Elvis INSTANCE = new Elvis();
    private Elvis() { }
    public static Elvis getInstance() { return INSTANCE; }

    public void leaveTheBuilding() {
        
    }
}

All calls to Elvis.getInstance return the same object reference, and no other Elvis instance will ever be created (with the same caveat mentioned above).

The main advantage of the public field approach is that the declarations make it clear that the class is a singleton: the public static field is final, so it will always contain the same object reference. There is no longer any performance advantage to the public field approach: modern Java virtual machine (JVM) implementations are almost certain to inline the call to the static factory method.

One advantage of the factory-method approach is that it gives you the flexibility to change your mind about whether the class should be a singleton without changing its API. The factory method returns the sole instance but could easily be modified to return, say, a unique instance for each thread that invokes it. A second advantage, concerning generic types. Often neither of these advantages is relevant, and the final-field approach is simpler.

To make a singleton class that is implemented using either of the previous approaches serializable, it is not sufficient merely to add implements Serializable to its declaration. To maintain the singleton guarantee, you have to declare all instance fields transient and provide a readResolve method. Otherwise, each time a serialized instance is deserialized, a new instance will be created, leading, in the case of our example, to spurious Elvis sightings. To prevent this, add this readResolve method to the Elvis class:

    private Object readResolve() {
        // Return the one true Elvis and let the garbage collector
        // take care of the Elvis impersonator.
        return INSTANCE;
    }

As of release 1.5, there is a third approach to implementing singletons. Simply make an enum type with one element:

// Enum singleton - the preferred approach
public enum Elvis {
    INSTANCE;

    public void leaveTheBuilding() {
        System.out.println("Whoa baby, I'm outta here!");
    }

    // This code would normally appear outside the class!
    public static void main(String[] args) {
        Elvis elvis = Elvis.INSTANCE;
        elvis.leaveTheBuilding();
    }
}

This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

Consider a builder when faced with many constructor parameters


Static factories and constructors share a limitation: they do not scale well to large numbers of optional parameters. Consider the case of a class representing the Nutrition Facts label that appears on packaged foods. These labels have a few required fields—serving size, servings per container, and calories per serving— and over twenty optional fields—total fat, saturated fat, trans fat, cholesterol, sodium, and so on. Most products have nonzero values for only a few of these optional fields.

What sort of constructors or static factories should you write for such a class? Traditionally, programmers have used the telescoping constructor pattern, in which you provide a constructor with only the required parameters, another with a single optional parameter, a third with two optional parameters, and so on, culminating in a constructor with all the optional parameters. Here’s how it looks in practice. For brevity’s sake, only four optional fields are shown:

// Telescoping constructor pattern - does not scale well!
public class NutritionFacts {
    private final int servingSize;   // (mL)            required
    private final int servings;      // (per container) required
    private final int calories;      //                 optional
    private final int fat;           // (g)             optional
    private final int sodium;        // (mg)            optional
    private final int carbohydrate;  // (g)             optional

    public NutritionFacts(int servingSize, int servings) {
        this(servingSize, servings, 0);
    }

    public NutritionFacts(int servingSize, int servings,
            int calories) {
        this(servingSize, servings, calories, 0);
    }

    public NutritionFacts(int servingSize, int servings,
            int calories, int fat) {
        this(servingSize, servings, calories, fat, 0);
    }

    public NutritionFacts(int servingSize, int servings,
            int calories, int fat, int sodium) {
        this(servingSize, servings, calories, fat, sodium, 0);
    }

    public NutritionFacts(int servingSize, int servings,
           int calories, int fat, int sodium, int carbohydrate) {
        this.servingSize  = servingSize;
        this.servings     = servings;
        this.calories     = calories;
        this.fat          = fat;
        this.sodium       = sodium;
        this.carbohydrate = carbohydrate;
    }
}

When you want to create an instance, you use the constructor with the shortest parameter list containing all the parameters you want to set:

NutritionFacts cocaCola =
            new NutritionFacts(240, 8, 100, 0, 35, 27);

Typically this constructor invocation will require many parameters that you don’t want to set, but you’re forced to pass a value for them anyway. In this case, we passed a value of 0 for fat. With “only” six parameters this may not seem so bad, but it quickly gets out of hand as the number of parameters increases.

In short, the telescoping constructor pattern works, but it is hard to write client code when there are many parameters, and harder still to read it. The reader is left wondering what all those values mean and must carefully count parameters to find out. Long sequences of identically typed parameters can cause subtle bugs. If the client accidentally reverses two such parameters, the compiler won’t complain, but the program will misbehave at runtime.

A second alternative when you are faced with many constructor parameters is the JavaBeans pattern, in which you call a parameterless constructor to create the object and then call setter methods to set each required parameter and each optional parameter of interest:

// JavaBeans Pattern - allows inconsistency, mandates mutability 

public class NutritionFacts {
    // Parameters initialized to default values (if any)
    private int servingSize  = -1;  // Required; no default value
    private int servings     = -1;  //     "     "     "      "
    private int calories     = 0;
    private int fat          = 0;
    private int sodium       = 0;
    private int carbohydrate = 0;

    public NutritionFacts() { }

    // Setters
    public void setServingSize(int val)  { servingSize = val; }
    public void setServings(int val)     { servings = val; }
    public void setCalories(int val)     { calories = val; }
    public void setFat(int val)          { fat = val; }
    public void setSodium(int val)       { sodium = val; }
    public void setCarbohydrate(int val) { carbohydrate = val; }
}

This pattern has none of the disadvantages of the telescoping constructor pattern. It is easy, if a bit wordy, to create instances, and easy to read the resulting code:

 NutritionFacts cocaCola = new NutritionFacts();
        cocaCola.setServingSize(240);
        cocaCola.setServings(8);
        cocaCola.setCalories(100);
        cocaCola.setSodium(35);
        cocaCola.setCarbohydrate(27);

Unfortunately, the JavaBeans pattern has serious disadvantages of its own. Because construction is split across multiple calls, a JavaBean may be in an inconsistent state partway through its construction. The class does not have the option of enforcing consistency merely by checking the validity of the con- structor parameters. Attempting to use an object when it’s in an inconsistent state may cause failures that are far removed from the code containing the bug, hence difficult to debug. A related disadvantage is that the JavaBeans pattern precludes the possibility of making a class immutable, and requires added effort on the part of the programmer to ensure thread safety.

It is possible to reduce these disadvantages by manually “freezing” the object when its construction is complete and not allowing it to be used until frozen, but this variant is unwieldy and rarely used in practice. Moreover, it can cause errors at runtime, as the compiler cannot ensure that the programmer calls the freeze method on an object before using it.

Luckily, there is a third alternative that combines the safety of the telescoping constructor pattern with the readability of the JavaBeans pattern. It is a form of the Builder pattern. Instead of making the desired object directly, the client calls a constructor (or static factory) with all of the required parameters and gets a builder object. Then the client calls setter-like methods on the builder object to set each optional parameter of interest. Finally, the client calls a parameterless build method to generate the object, which is immutable. The builder is a static member class of the class it builds. Here’s how it looks in practice:

// Builder Pattern

public class NutritionFacts {
    private final int servingSize;
    private final int servings;
    private final int calories;
    private final int fat;
    private final int sodium;
    private final int carbohydrate;

    public static class Builder {
        // Required parameters
        private final int servingSize;
        private final int servings;

        // Optional parameters - initialized to default values
        private int calories      = 0;
        private int fat           = 0;
        private int carbohydrate  = 0;
        private int sodium        = 0;

        public Builder(int servingSize, int servings) {
            this.servingSize = servingSize;
            this.servings    = servings;
        }

        public Builder calories(int val)
            { calories = val;      return this; }
        public Builder fat(int val)
            { fat = val;           return this; }
        public Builder carbohydrate(int val)
            { carbohydrate = val;  return this; }
        public Builder sodium(int val)
            { sodium = val;        return this; }

        public NutritionFacts build() {
            return new NutritionFacts(this);
        }
    }

    private NutritionFacts(Builder builder) {
        servingSize  = builder.servingSize;
        servings     = builder.servings;
        calories     = builder.calories;
        fat          = builder.fat;
        sodium       = builder.sodium;
        carbohydrate = builder.carbohydrate;
    }
}

Note that NutritionFacts is immutable, and that all parameter default values are in a single location. The builder’s setter methods return the builder itself so that invocations can be chained. Here’s how the client code looks:

NutritionFacts cocaCola = new NutritionFacts.Builder(240,8).calories(100).sodium(35).carbohydrate(27).build();

This client code is easy to write and, more importantly, to read. The Builder pat- tern simulates named optional parameters as found in Ada and Python.

Like a constructor, a builder can impose invariants on its parameters. The build method can check these invariants. It is critical that they be checked after copying the parameters from the builder to the object, and that they be checked on the object fields rather than the builder fields. If any invariants are violated, the build method should throw an IllegalStateException. The exception’s detail method should indicate which invariant is violated.

Another way to impose invariants involving multiple parameters is to have setter methods take entire groups of parameters on which some invariant must hold. If the invariant isn’t satisfied, the setter method throws an IllegalArgumentException. This has the advantage of detecting the invariant failure as soon as the invalid parameters are passed, instead of waiting for build to be invoked.

A minor advantage of builders over constructors is that builders can have multiple varargs parameters. Constructors, like methods, can have only one varargs parameter. Because builders use separate methods to set each parameter, they can have as many varargs parameters as you like, up to one per setter method.
The Builder pattern is flexible. A single builder can be used to build multiple objects. The parameters of the builder can be tweaked between object creations to vary the objects. The builder can fill in some fields automatically, such as a serial number that automatically increases each time an object is created.

A builder whose parameters have been set makes a fine Abstract Factory. In other words, a client can pass such a builder to a method to enable the method to create one or more objects for the client. To enable this usage, you need a type to represent the builder. If you are using release 1.5 or a later release, a single generic type suffices for all builders, no matter what type of object they’re building:

// A builder for objects of type T 
public interface Builder<T> {
     public T build();
}

Note that our NutritionFacts.Builder class could be declared to implement Builder<NutritionFacts>.
Methods that take a Builder instance would typically constrain the builder’s type parameter using a bounded wildcard type. For example, here is a method that builds a tree using a client-provided Builder instance to build each node:

Tree buildTree(Builder<? extends Node> nodeBuilder) { ... }

The traditional Abstract Factory implementation in Java has been the Class object, with the newInstance method playing the part of the build method. This usage is fraught with problems. The newInstance method always attempts to invoke the class’s parameterless constructor, which may not even exist. You don’t get a compile-time error if the class has no accessible parameterless constructor. Instead, the client code must cope with InstantiationException or IllegalAccessException at runtime, which is ugly and inconvenient. Also, the newIn- stance method propagates any exceptions thrown by the parameterless constructor, even though newInstance lacks the corresponding throws clauses. In other words, Class.newInstance breaks compile-time exception checking. The Builder interface, shown above, corrects these deficiencies.

The Builder pattern does have disadvantages of its own. In order to create an object, you must first create its builder. While the cost of creating the builder is unlikely to be noticeable in practice, it could be a problem in some performance critical situations. Also, the Builder pattern is more verbose than the telescoping constructor pattern, so it should be used only if there are enough parameters, say, four or more. But keep in mind that you may want to add parameters in the future. If you start out with constructors or static factories, and add a builder when the class evolves to the point where the number of parameters starts to get out of hand, the obsolete constructors or static factories will stick out like a sore thumb. Therefore, it’s often better to start with a builder in the first place.

In summary, the Builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters, especially if most of those parameters are optional. Client code is much easier to read and write with builders than with the traditional telescoping constructor pattern, and builders are much safer than JavaBeans.

Consider static factory methods instead of constructors

The normal way for a class to allow a client to obtain an instance of itself is to provide a public constructor. There is another technique that should be a part of every programmer’s toolkit. A class can provide a public static factory method, which is simply a static method that returns an instance of the class. Here’s a simple example from Boolean (the boxed primitive class for the primitive type boolean). This method translates a boolean primitive value into a Boolean object reference: 

public static Boolean valueOf(boolean b) { 
     return b ? Boolean.TRUE : Boolean.FALSE; 
}

Note that a static factory method is not the same as the Factory Method pattern from Design Patterns. The static factory method described in this item has no direct equivalent in Design Patterns. 

A class can provide its clients with static factory methods instead of, or in addition to, constructors. Providing a static factory method instead of a public constructor has both advantages and disadvantages. 

One advantage of static factory methods is that, unlike constructors, they have names. If the parameters to a constructor do not, in and of themselves, describe the object being returned, a static factory with a well-chosen name is easier to use and the resulting client code easier to read. For example, the constructor BigInteger(int, int, Random), which returns a BigInteger that is probably prime, would have been better expressed as a static factory method named BigInteger.probablePrime. (This method was eventually added in the 1.4 release.) 

A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they’re invoked. This allows immutable classes to use pre-constructed instances, or to cache instances as they’re constructed, and dispense them repeatedly to avoid creating unnecessary duplicate objects. The Boolean.valueOf(boolean) method illustrates this technique: it never creates an object. This technique is similar to the Flyweight pattern. It can greatly improve performance if equivalent objects are requested often, especially if they are expensive to create. 

The ability of static factory methods to return the same object from repeated invocations allows classes to maintain strict control over what instances exist at any time. Classes that do this are said to be instance-controlled. There are several reasons to write instance-controlled classes. Instance control allows a class to guarantee that it is a singleton or noninstantiable. Also, it allows an immutable class to make the guarantee that no two equal instances exist: a.equals(b) if and only if a==b. If a class makes this guarantee, then its clients can use the == operator instead of the equals(Object) method, which may result in improved performance. Enum types provide this guarantee. 

A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type. This gives you great flexibility in choosing the class of the returned object. 

One application of this flexibility is that an API can return objects without making their classes public. Hiding implementation classes in this fashion leads to a very compact API. This technique lends itself to interface-based frameworks, where interfaces provide natural return types for static factory methods. Interfaces can’t have static methods, so by convention, static factory methods for an interface named Type are put in a noninstantiable class named Types. 

Not only can the class of an object returned by a public static factory method be nonpublic, but the class can vary from invocation to invocation depending on the values of the parameters to the static factory. Any class that is a subtype of the declared return type is permissible. The class of the returned object can also vary from release to release for enhanced software maintainability and performance. 

The class java.util.EnumSet, introduced in release 1.5, has no public constructors, only static factories. They return one of two implementations, depending on the size of the underlying enum type: if it has sixty-four or fewer elements, as most enum types do, the static factories return a RegularEnumSet instance, which is backed by a single long; if the enum type has sixty-five or more elements, the factories return a JumboEnumSet instance, backed by a long array. 

A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances. Unfortunately, you must specify the type parameters when you invoke the constructor of a parameterized class even if they’re obvious from context. This typically requires you to provide the type parameters twice in quick succession: 

Map<String, List<String>> m = new HashMap<String, List<String>>();

This redundant specification quickly becomes painful as the length and complexity of the type parameters increase. With static factories, however, the compiler can figure out the type parameters for you. This is known as type inference. For example, suppose that HashMap provided this static factory: 

public static HashMap<K, V> newInstance() { 
     return new HashMap<K, V>();
}


Then you could replace the wordy declaration above with this succinct alternative:

Map<String, List<String>> m = HashMap.newInstance();

Someday the language may perform this sort of type inference on constructor invocations as well as method invocations, but as of release 1.6, it does not. 

Unfortunately, the standard collection implementations such as HashMap do not have factory methods as of release 1.6, but you can put these methods in your own utility class. More importantly, you can provide such static factories in your own parameterized classes. 

The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed. The same is true for nonpublic classes returned by public static factories. For example, it is impossible to subclass any of the convenience implementation classes in the Collections Framework. Arguably this can be a blessing in disguise, as it encourages programmers to use composition instead of inheritance. 

A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods. They do not stand out in API documentation in the way that constructors do, so it can be difficult to figure out how to instantiate a class that provides static factory methods instead of constructors. The Javadoc tool may someday draw attention to static factory methods. In the meantime, you can reduce this disadvantage by drawing attention to static factories in class or interface comments, and by adhering to common naming conventions. Here are some common names for static factory methods: 

  • valueOf—Returns an instance that has, loosely speaking, the same value as its parameters. Such static factories are effectively type-conversion methods. 
  • of—A concise alternative to valueOf, popularized by EnumSet. 
  • getInstance—Returns an instance that is described by the parameters but cannot be said to have the same value. In the case of a singleton, getInstance takes no parameters and returns the sole instance. 
  • newInstance—Like getInstance, except that newInstance guarantees that each instance returned is distinct from all others. 
  • getType—Like getInstance, but used when the factory method is in a different class. Type indicates the type of object returned by the factory method. 
  • newType—Like newInstance, but used when the factory method is in a different class. Type indicates the type of object returned by the factory method. 
In summary, static factory methods and public constructors both have their uses, and it pays to understand their relative merits. Often static factories are preferable, so avoid the reflex to provide public constructors without first considering static factories.

Friday, August 26, 2011

String.intern()

String it is fundamental part of any modern programing language and just sa important as a number. That why can propose that Java programers must have strong knowledge about String, but, unfortunately not all programers.

Today I started read news and saw an interesting string, that very confused me.

protected final static String fVersionSymbol = "version".intern();

Next I found more strings declared like that. What is intern()? You know, exists two different way to compare objects in Java. You can use operator ==, or you can use method equals(). Operator == compare link is two link on one object, and equals() compare is two object contains the same data.

One of the first lessons, what you get when you start learn about String in Java is that for compare two strings you should use equals() and no ==. If compare new String("Hello")==new String("Hello") you get in result false, because this is two different object with the same data. if you use equals(), you get true. Unfortunately equals() can be more slowest than ==, because it does string compare by characters.

Operator == check identity, all what it must do is compare two index and obviously it will much faster than equals(). That if you want compare the same string manu times, you can get a significant performance advantage through the use of checking the identity of objects instead of comparing characters.

intern() main algorithm:

  1. Create a hash set strings 
  2. Check, that string (like characters sequence), with which we working, already in hash set 
  3. If yes, use string from hash set
  4. Otherwise, add this string in hash set and after use it 

Using this algorithm you guaranteed, that if two strings are identical sequences characters, they are one instance of a class. It's mean that you can easy compare strings using == instead of equals(), get a significant performance advantage when repetitive comparison.

Fortunately Java already includes implementation of this algorithm. This method intern() in class java.lang.String. Expresion new String("Hello").intern() == new String("Hello").intern() return true, otherwise with out intern() return false.

Method intern() simply before creating a String object check exist or not exist this object in String pool and return this object. Otherwise create new object in the pool.

All strings in Java already interned. That why "Hel" + "lo" == "Hello" return true.

How start work with Java? (MS Windows)

You should download JDK (Java Development Kit). You can find it here --> Java SDK. Go to link and download JDK for your platform.

After installing check that in your PATH variable added catalog with java.exe and javac.exe if not, add to it directory path with java.exe and javac.exe files. For example, my path is D:\JavaTools\jdk_1.7\bin. If you does not have PATH variable - create it. And create variable with name JAVA_HOME, and its value will be path to directory where you installed JDK (example, D:\JavaTools\jdk_1.7). To check is all good you can run consol (Windows+R) and input line - java. You must get this result: 

Usage: java [-options] class [args...]
          (to execute a class)
or  java [-options] -jar jarfile [args...]
          (to execute a jar file)
where options include:
   -client       to select the "client" VM
   -server       to select the "server" VM
   -hotspot      is a synonym for the "client" VM  [deprecated]
                 The default VM is client.

It's mean that virtual machine was found but you called it with wrong arguments. If you get message «’java’ is not recognized as an internal or an external command, operable program or batch file»,  you did something wrong.

Open Notepad and save file HelloWorld.java:

public class HelloWorld
{
  public static void main(String[] args)
  {
    HelloWorld hw = new HelloWorld(); 
    hw.showString();
  }
  public void showString()
  {
    System.out.println("Hello, World!");
  }
}


Open console and go to directory with you file, input javac HelloWorld.java . You file was compiled!

After compilation you get file HelloWorld.class. Now you can start your application input string java HelloWorld

Monday, August 22, 2011

Working with JDBC PreparedStatement


As you know, the PreparedStatement interface extends the Statement interface. Its added functionality also gives it a couple of advantages over a generic Statementobject.

First, it gives you the flexibility of supplying arguments dynamically. Although you can use the Statement object to build and execute your SQL statements on the fly, the PreparedStatement object reduces your work.

Second, when you create a PreparedStatement object JDBC "prepares" the SQL statement for execution by sending it to the database, which then parses, compiles, and builds a query execution plan. This parsed statement lives in memory and remains ready to use during your database session or until you close the PreparedStatementobject.

Creating PreparedStatement Object: Just as a Connection object creates theStatement object, it also creates a PreparedStatement object. The following code snippet shows how to employ its prepareStatement() method to instantiate aPreparedStatement object:
  1. Connection conn = DriverManager.getConnection(url, "scott", "tiger");
  2. String SQL = "Update employees SET salary = ? WHERE ename = ?";
  3. PreparedStatement prepStmt = conn.prepareStatement(SQL);

Using PreparedStatement Object: To bind values to parameters you use thesetXXX() methods. JDBC uses the setXXX methods to convert the Java data type to the
appropriate SQL data type for your target database, as shown in the following code snippet:
  1. String SQL = "UPDATE employees SET salary = ? WHERE ename = ?";
  2. PreparedStatement pstmt = conn.prepareStatement(SQL);
  3. //bind variables
  4. pstmt.setInt(1,100000);
  5. pstmt.setString(2,"Tousif Khan");
  6. pstmt.executeUpdate();
Let's now look at an example to see the use of PreparedStatement Object.
  1. import java.sql.*;
  2. public class PreparedStatementDemo {
  3. public static void main(String s[]) throws Exception {
  4. Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
  5. Connection con= DriverManager.getConnection (
  6. "jdbc:oracle:thin:@mysys:1521:khan","scott","tiger");
  7. String query="insert into employee values (?,?,?)";
  8. //Step1: Get PreparedStatement
  9. PreparedStatement ps=con.prepareStatement (query);
  10. //Step2: set parameters
  11. ps.setString(1,"abc1");
  12. ps.setInt(2,38);
  13. ps.setDouble(3,158.75);
  14. //Step3: execute the query
  15. int i=ps.executeUpdate();
  16. System.out.println("record inserted count:"+i);
  17. //To execute the query once again
  18. ps.setString(1,"abc2");
  19. ps.setInt(2,39);
  20. ps.setDouble(3,158.75);
  21. i=ps.executeUpdate();
  22. System.out.println("Second time count: "+i);
  23. con.close();
  24. }//main
  25. }//class
TipsChecking the update count value can be a sanity check when you’re executing your SQL statements. If you update a row by its primary key then you should always receive an update count of 1. Any other value may indicate an error.