Sunday, August 24, 2014
Java Networking APIs provide a set of classes to interact with the internet. The primary classes include URL, URLConnection and HttpURLConnection. This tutorial provides examples to construct URLs and to access internet resources. 

Read properties of URL

URL represents the Uniform Resource Locator a resource on the world wide web. 
URL url1 = new URL("http", "www.sourcetricks.com", 
              8080, "p/java-tutorials.html");
System.out.println(url1.toString());

This program produces the following output printing the URL as string.
http://www.sourcetricks.com:8080p/java-tutorials.html

Class URL provides functions to retrieve the properties of an URL object including protocol, host, port, path etc. Following program demonstrates reading the properties of an URL.

public static void main(String[] args) throws Exception {
  URL url = new URL("http://www.sourcetricks.com/p/java-tutorials.html");
  System.out.println(url.getHost());
  System.out.println(url.getPort());
  System.out.println(url.getProtocol());
  System.out.println(url.getPath());
}

This program produces the following output printing the URL properties.
www.sourcetricks.com
-1
http
/p/java-tutorials.html

Using URLConnection

URLConnection is used for accessing remote resources. We can examine the attributes of a remote resource specified as an URL and also get the contents locally.

public static void main(String[] args) throws Exception {
  URL url = new URL("http://www.sourcetricks.com/p/java-tutorials.html");
  URLConnection connection = url.openConnection();
  BufferedReader reader = new BufferedReader
     (new InputStreamReader(connection.getInputStream()));
  String line = null;
  while ( ( line = reader.readLine() ) != null ) {
    System.out.println(line);
  }
  reader.close();  
}

Using HttpURLConnection

HttpURLConnection is a sub-class of URLConnection class and includes support for handling HTTP connections. HttpURLConnection class has additional methods like HTTP request method, HTTP response code, HTTP redirect handling etc.

In the example below we make a HttpURLConnection to get a page contents. Please note that additional methods specific to HTTP can be used on the connection object.

public static void main(String[] args) throws Exception {
  URL url = new URL("http://www.sourcetricks.com/p/java-tutorials.html");
  HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
  System.out.println(httpConnection.getRequestMethod());
  System.out.println(httpConnection.getResponseCode());
  System.out.println(httpConnection.getResponseMessage());
  BufferedReader reader1 = new BufferedReader
     (new InputStreamReader(httpConnection.getInputStream()));
  String line1 = null;
  while ( ( line1 = reader1.readLine() ) != null ) {
    System.out.println(line1);
  }
  reader1.close();
  httpConnection.disconnect();
}

This program produces the following output displaying the HTTP request type (GET), HTTP response code (200) and HTTP response message (OK). Finally it prints the page contents.

GET
200
OK
Page contents ...

Continue to read other java tutorials from here.
Saturday, August 23, 2014
Annotations is a form of meta-data to the Java code and doesn't directly impact the behavior of the code. This article covers key concepts around annotations in Java with examples.

Basic format of Annotation

The at sign @ indicates start of annotation. In the example below we use an annotation @SuppressWarnings with value of "deprecation". This annotation tells the compiler to suppress the display of specific warnings in this case deprecated.

@SuppressWarnings("deprecation")
public static void main(String[] args) {
  Employee e = new Employee();
  e.setId("100");
  e.setName("Employee1");
}

Predefined annotations in Java

Java defined few predefined annotations. These include @Deprecated, @SuppressWarnings and @Override.

@Deprecated annotation is used to mark an element as deprecated. When a element annotated as deprecated is used in a program compiler generates a warning.

@Deprecated
public void setId(String id) {
  this.id = id;
}

When a deprecated method is used in a program the compiler generates a warning as below.

The method setId(String) from the type Employee is deprecated

@SuppressWarnings annotation is used to suppress warnings which the compiler generates. For example, to suppress the deprecation warning generated by the previous example we could use this annotation.

@SuppressWarnings("deprecation")
public static void main(String[] args) {
  Employee e = new Employee();
  e.setId("100");
  e.setName("Employee1");
}

@Override annotation is used to indicate to the compiler that the element is overriding an element declared in a super class. Using @Override is not mandatory but helps to prevent errors like the case where super class method is not overridden correctly.

@Override
public void print() {
}

Custom annotations in Java

In Java it is possible to define our own custom annotation types. Annotation type definitions in Java are similar to interface type definitions except that the interface keyword is preceded with a @ (AT) sign.

Let us consider a quick example to create a class details annotation. To define this annotation we would do as below. Note that we can specify default values for elements as well in the annotation definition.

package com.sourcetricks.annotations;

@interface ClassDetails {
   String creator();
   String date();
   String revision() default "1.0";
}

To use the ClassDetails annotation with the required parameters on a Class we would do as below.

@ClassDetails(creator = "SourceTricks", date = "8/23/2014", revision = "1.0")
public class TestAnnotations {
}

Meta annotations in Java

Java also supports meta annotations. These are annotations that apply to other annotations. Let us look at some examples to understand this better.

@Retention annotation indicates how the marked element is stored. In this example we create a MethodNotes annotation with RetentionPolicy as RunTime. This would allow to examine the annotations in RunTime using reflection.

package com.sourcetricks.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface MethodNotes {
   public String notes();
}

Let us create a simple Employee class and apply the MethodNotes annotation to functions in the class.

package com.sourcetricks.annotations;

public class Employee {

   private String id;
   private String name;

   public Employee(String id, String name) {
     this.id = id;
     this.setName(name);
   } 

   @MethodNotes(notes="Getter")
   public String id() { return id; }

   @MethodNotes(notes="Setter")
   public void setId(String id) {
     this.id = id;
   }
 
   @MethodNotes(notes="Getter")
   public String getName() {
     return name;
   }
 
   @MethodNotes(notes="Setter")
   public void setName(String name) {
     this.name = name;
   } 
 
   @MethodNotes(notes="print")
   public void print() { 
     System.out.println(id + ", " + name);
   }
}

Since we have added RunTime RetentionPolicy for MetaNotes annotation, we should be able to access the annotation notes in RunTime. In the code snippet below we print the annotation value using Reflection.

public class TestAnnotations {

   public static void main(String[] args) { 
      Employee e1 = new Employee("Emp100", "John");
      for ( Method m  : e1.getClass().getDeclaredMethods() ) {
         if ( m.isAnnotationPresent(MethodNotes.class) ) {
            MethodNotes methodNotes = m.getAnnotation(MethodNotes.class);
     System.out.println(m.getName() + " = " + methodNotes.notes());
 }
      }
   }
}

@Target annotation is used to restrict what type of elements the specific annotation can be applied to. In the example below we restrict the MethodNotes annotation only to ElementType of Method.

@Target(value = { ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodNotes {
 public String notes();
}

@Inherited is another meta annotation type. This applies only for class declarations. @Inherited indicates that annotation can be inherited from the super class.

@Documented meta annotation type is used to indicate to the JavaDoc tool that the element needs to be documented.

Continue to read other java tutorials from here.
Saturday, August 2, 2014
Transaction is a set of one or more statements executed as a unit. The intent is that multiple statements which are part of a unit are executed together to make it meaningful. This article provides a quick introduction to handling transactions in JDBC.

Here are some key points to remember when dealing with transactions using JDBC.
  • When a DB connection is created it is by default put in auto commit mode. The key to handle transactions is to disable auto commit mode so that the application can have better control when to commit.
  • connection.setAutoCommit(false);
  • Since auto commit is disabled when working with transactions it is necessary to perform an explicit commit when all the statements that are part of a transaction are completed.
  • connect.commit();
    
  • To undo the effects of a transaction the rollback method could be used to restore the values before the attempted transaction.
  • connection.rollback();
  • JDBC also supports to set save points and then rollback to the specified save point. The following method could be used to define save points.
  • SavePoint savePoint1 = connection.setSavePoint();
    
  • Rollback a transaction to an already defined save point using rollback call with an argument.
  • connection.rollback(savePoint1);
    

JDBC Transaction Example

Let us consider a simple example of a stock trading application where we have to update two tables one for individual transactions and another for total transactions in a day.

We are using a PostgreSQL database here. Refer to these tutorials to get started.
JDBC Quick Start with PostgreSQL
JDBC Database Access Examples 

Table1: Stock Trades

CREATE TABLE stock_trades
(
  trade_id numeric(6,0) NOT NULL,
  script character(10),
  num_units integer,
  CONSTRAINT stock_trades_pkey PRIMARY KEY (trade_id)
)

Table2: Total Trades

CREATE TABLE total_trades
(
  script character(10) NOT NULL,
  total_units integer,
  CONSTRAINT total_trades_pkey PRIMARY KEY (script)
)

Now let us perform a transaction where we need to update both the stock trades and total trades table.

public static void performTransaction(Connection connection, int id, String script, int units) {
  PreparedStatement insertStockTrades = null;
  PreparedStatement updateTotalTrades = null;
  
  String insertStockSql = "INSERT INTO stock_trades VALUES(?, ?, ?)";
  String updateStockSql = "UPDATE total_trades set total_units = total_units + ? where script = ?";
  
  try {
    connection.setAutoCommit(false);
    
    insertStockTrades = connection.prepareStatement(insertStockSql);
    insertStockTrades.setInt(1, id);
    insertStockTrades.setString(2, script);
    insertStockTrades.setInt(3, units);
    insertStockTrades.executeUpdate();
    
    updateTotalTrades = connection.prepareStatement(updateStockSql);
    updateTotalTrades.setInt(1, units);
    updateTotalTrades.setString(2, script);
    updateTotalTrades.executeUpdate();
    
    connection.commit();
  } catch ( SQLException  e ) {
    e.printStackTrace();
    try {
      connection.rollback();
    } catch (SQLException e1) {
      e1.printStackTrace();
    }
  } finally {
    try {
      connection.setAutoCommit(true);
    } catch (SQLException e2) {
      e2.printStackTrace();
    }
  }
}
Monday, July 28, 2014
This article provides a list of key examples which we would commonly encounter when implementing a Java application requiring database access. For purpose of these examples the assumption is that PostgreSQL database is already setup and necessary database driver is downloaded and added to the CLASSPATH. Refer to this article JDBC Quick Start for a quick introduction to get started.

Create Table using JDBC

Let us consider a simple car loan EMI table with 3 columns EMI Number, EMI Amount and Interest Amount. To create this table on a PostgreSQL database we would do the following. The Statement object is used for executing a static SQL statement.

public static void createTable(Connection connection) {
  try ( Statement stmt = connection.createStatement(); ) {
    String sql = "CREATE TABLE car_loan_emi (\r\n" + 
          "    emi_number      numeric(2) PRIMARY KEY,\r\n" + 
          "    emi_amount      integer,\r\n" + 
          "    interest_amount integer\r\n" + 
          ");";
    stmt.execute(sql);   
  } catch (SQLException e) {
    e.printStackTrace();
  } 
}

Insert records using JDBC

Let us consider the case where we need to populate our car loan EMI table with the values for 12 months. First let us consider the simple case of inserting a record in the table.

public static void insertSingle(Connection connection) {
  try ( Statement stmt = connection.createStatement(); ) {
    String sql = "INSERT INTO car_loan_emi values(1, '10000', '990');";
    stmt.execute(sql);   
  } catch (SQLException e) {
    e.printStackTrace();
  } 
}

Let us say we want to insert EMI values for 12 months into the car loan EMI table. In this case we can leverage PreparedStatement object for sending SQL queries to the database. The advantage of using PreparedStatement is that we use the same object and we supply it with different values when it is executed.

public static void insertMultiple(Connection connection) {
  String sql = "INSERT INTO car_loan_emi values(?, ?, ?);";
  try {
    connection.setAutoCommit(false);
  } catch (SQLException e2) {
    e2.printStackTrace();
  }
  try ( PreparedStatement stmt = connection.prepareStatement(sql); ) {
    for ( int month = 1; month <= 12; month++ ) {
      stmt.setInt(1, month);
      stmt.setInt(2, 10000);
      // ignore this formula
      int interest = (int)((100000 - ((month - 1) * 10000)) * 0.12);
      stmt.setInt(3, interest);
      stmt.executeUpdate();
    }
    connection.commit();
  } catch (SQLException e) {
    e.printStackTrace();
  } finally {
    try {
      connection.setAutoCommit(true);
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}

Select records using JDBC

To select records from the car loan EMI table we use a ResultSet which is usually generated by querying the database with a Statement. The ResultSet object provides getter methods for retrieving the values.

public static void selectRecords(Connection connection) {
  try ( Statement stmt = connection.createStatement(); ) {
    ResultSet rs = stmt.executeQuery("SELECT * from car_loan_emi");
    while ( rs.next() ) {
      System.out.println(rs.getInt(1)); 
      System.out.println(rs.getInt(2));
      System.out.println(rs.getInt(3));
    }
  } catch (SQLException e) {
    e.printStackTrace();
  } 
}

Update records using JDBC

To update records in a table we can either execute an SQL statement (or) update using ResultSet. There are 3 types of ResultSet types.
  1. TYPE_FORWARD_ONLY: The result set cannot be scrolled and the cursor can be moved forward only.
  2. TYPE_SCROLL_INSENSITIVE: The result set can be scrolled and the cursor can be moved both forward and backward. The result set is insensitive to changes made in the underlying data source.
  3. TYPE_SCROLL_SENSITIVE: The result set can be scrolled and the cursor can be moved both forward and backward. The result set reflects the changes made in the underlying data source.
We update the car loan EMI table for a specific month using SQL query.

public static void updateRows(Connection connection) {
  try ( Statement stmt = connection.createStatement(); ) {
    String sql = "UPDATE car_loan_emi SET emi_amount = 9000 WHERE emi_number = 6;"; 
    stmt.execute(sql);
  } catch (SQLException e) {
    e.printStackTrace();
  } 
}

We update the car loan EMI table for a specific month using the result set.

public static void updateRows(Connection connection) {
  try ( Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
              ResultSet.CONCUR_UPDATABLE); ) {
    String sql = "SELECT emi_number, emi_amount from car_loan_emi WHERE emi_number = 6;"; 
    ResultSet rs = stmt.executeQuery(sql);
    while ( rs.next() ) {
      int value = rs.getInt("emi_amount");    
      rs.updateInt("emi_amount", value - 1000);
      rs.updateRow();
    }
  } catch (SQLException e) {
    e.printStackTrace();
  } 
}
Saturday, July 19, 2014
Generics is a key element in the Java programming language and a solid understanding is essential for any Java programmer. This article provides an introduction to the concepts around Generics in Java.

Generics Introduction

Generics provide the ability to create classes, methods and interfaces to be used with different types of data in a type-safe manner. Generics by adding type safety to the code enables bugs to be detected at compile time rather than at run time. This provides stability to the implementation. The Collections Framework is a great example for understanding Generics. Collections classes like Lists and Maps can used in a type-safe manner by using Generics.

Generalized classes with Object type

Java has the capability to create generalized classes, method and interfaces by using Object types. Let us consider a quick example of creating a stack class using Object type. In this example, we use an ArrayList of objects to hold the data.

package com.sourcetricks.generics;

import java.util.ArrayList;
import java.util.List;

public class ObjectStack {
   private List<Object> data = new ArrayList<Object>();
 
   public void push(Object item) {
     data.add(item);
   }
 
   public Object pop() {
     if ( data.size() > 0 ) {
        Object val = data.get(data.size()-1);
        data.remove(data.size()-1);
        return val;
     }
     return null;
   }
}

To use this stack our main would something like below. Please note that we need to do the type casting every time we pop an element from the stack. Assuming the intent is to create a stack of String if someone my mistake puts in a integer type then it would result in a ClassCastException. Note that it is not possible to detect these mistakes at compile time. Run-time issues are hard to debug for large projects.

public class JavaGenerics {
   public static void main(String[] args) {
     ObjectStack st = new ObjectStack();
     st.push("string");
     st.push(10);
     int i = (Integer) st.pop();
     String s = (String) st.pop();   
  }
}

Generalized classes with Generic types

Generic types add the type safety that is lacking in the previous example. There is also no need to cast an Object type into the actual data type. Let us redo the previous example using generic types. Note that we have replaced Object type with type parameter T in this example.

public class Stack<T> {
    private List<T> data = new ArrayList<T>();
 
    public void push(T item) {
       data.add(item);
    }
 
    public T pop() {
      if ( data.size() > 0 ) {
        T val = data.get(data.size()-1);
        data.remove(data.size()-1);
        return val;
      }
      return null;
    }
}

To use this stack our main would something like below. Please note when we instantiate the class we specify the concrete type to be used. If we try to add to the stack any type other than String then we would get a compile time error.

public class JavaGenerics {
   public static void main(String[] args) {
     Stack<String> st = new Stack<String>();
     st.push("string1");
     st.push("string2");
     String s1 = st.pop();
     String s2 = st.pop();   
   }
}

Raw types

A raw type is the name of a generic class or interface without any type arguments. We can rewrite our main as below. This approach again makes the code unsafe and using of raw types should be avoided.

public class JavaGenerics {
   public static void main(String[] args) {
     Stack st = new Stack();
     st.push("string1");
     st.push("string2");
     String s1 = (String) st.pop();
     String s2 = (String) st.pop();     
   }
}

The Diamond

In Java 7, we can replace the type arguments required to invoke the constructor with empty <>. The compiler infers the type from the context. Using <> is called diamond. We can rewrite the previous example as below.

public class JavaGenerics {
   public static void main(String[] args) {
     Stack<String> st = new Stack<>();
     st.push("string1");
     st.push("string2");
     String s1 = st.pop();
     String s2 = st.pop();   
   }
}

Generic methods

Generics can be used with methods as well. We can declare generic methods that uses one or more type parameters.

public static <T> boolean myfunc(T a, T b) {
  if ( a == b ) return true;
  return false;
}

Bounded type parameters

When specifying a type parameter we can specify an upper bound from which all type arguments should be derived.

The previous example doesn't make sense for String type. We can restrict the method to be limited to Number type by specifying the superclass as Number.

public static <T extends Number> boolean myfunc(T a, T b) {
  if ( a == b ) return true;
  return false;
}

Generic Wildcards

In generic code, the question mark (?) referred as wildcard represents an unknown type.

  • Upper bounded wildcards are used to relax the restrictions on a variable. To declare an upper bounded wildcard, use the wildcard(?) followed by the extends keywords and the upper bound.
  • The unbounded wildcard type is specified using the wildcard character (?).
  • Lower bounded wildcard restricts the unknown type to be a specific type or a super type of that type. To declare a lower bounded wildcard is expressed using the wildcard character(?), followed by the super keyword, followed by its lower bound.

The Java documentation provides guidelines on when to use upper bound and lower bound wildcards. Please refer this page.

package com.sourcetricks.generics;

import java.util.ArrayList;
import java.util.List;

public class JavaGenerics {
 
 // Upper bounded wildcard
 public static double addMyList(List<? extends Number> list) {
  double sum = 0.0;
  for ( Number elem : list ) {
   sum += elem.doubleValue();
  }
  return sum;
 }
 
 // Unbounded wildcard
 public static void printMyList(List<?> list) {
  for ( Object elem : list ) {
   System.out.println(elem);
  }
 }
 
 // Lower bounded wildcard
 public static void fillMyList(List<? super Integer> list) {
  for ( int i = 1; i <= 5; i++ )
   list.add(i);
 }
 
 // Lower bounded wildcard
 public static void main(String[] args) {
  List<Integer> list1 = new ArrayList<>();
  fillMyList(list1);
  System.out.println(addMyList(list1));
  printMyList(list1);
 }
}
Sunday, July 13, 2014
  • Enum type enables a variable to be set with predefined constants. Examples include days of week, directions etc.
  • In Java Enum type is defined using the keyword enum.
  • In Java Enum types are treated as class types and they are more powerful than other languages.
  • Enum types can have constructor, instance variables and methods.
  • One primary difference compared to classes is Enum types are not created using new() unlike class types.
  • Each enumeration constant is treated as an object.
  • Constructor would be called for each Enum constant.

Java Enum Type Example

public enum DefectStates {
 NEW(10), ASSIGNED(20), OPEN(30), RESOLVED(40), CLOSED(50);
 
 private int val;
 DefectStates(int val) {
  this.val = val;
  System.out.println("Constructor: " + val);
 }
 public int getVal() { return val; }
 public static void main(String[] args) {
  DefectStates ds = DefectStates.New;
 }
}

Output:-
Constructor: 10
Constructor: 20
Constructor: 30
Constructor: 40
Constructor: 50

Iterate Enum type values

Enum has static values method that returns an array containing all of the values of the enum in the order they are declared. This method can be used to iterate over the values of an enum type.

public class JavaEnumTest {
   public static void main(String[] args) {
     for ( DefectStates state : DefectStates.values() ) {
       System.out.println(state)
     }
   }
}

Output:-
NEW
ASSIGNED
OPEN
RESOLVED
CLOSED

Enum approach for creating singleton objects

The most simplest approach to implementing Singleton's is the enum approach. Leverages the guarantee from Java that an enum value is initialized only once and is thread safe.

The example below shows a sample implementation with Enum approach.

public enum EnumTest {
 INSTANCE;
 
 // Test code
 public static void main(String[] args) {
  
  // First thread
  Thread t1 = new Thread(new Runnable() {
   @Override
   public void run() {
    EnumTest obj = EnumTest.INSTANCE;
   }   
  });
  t1.start();
  
  // Second thread
  Thread t2 = new Thread(new Runnable() {
   @Override
   public void run() {
    EnumTest obj = EnumTest.INSTANCE;
   }   
  });
  t2.start();
 }
}

Understanding Synchronization

In a multi-threaded program, when 2 or more threads try to access a common resource there needs to be a way to ensure that only one thread uses the resource at a time. The process by which this is achieved is called synchronization. Java provides language constructs to achieve using synchronized keyword.

To understand synchronization better it is necessary to learn the concept of monitor. Monitor is an object that acts as a mutually exclusive lock. Only one thread can own a monitor at a time. A thread acquires a lock on the monitor to access a shared resource. All other threads attempting to access the shared resource will wait until first thread exits the monitor.

Synchronized Methods

Synchronized methods is one the two synchronization idioms available in Java. In synchronized methods synchronized keyword is added at the method level. It is not possible for two invocations of the synchronized methods on the same object to interleave. When one thread is executing a synchronized method all other threads that invoke the synchronized methods block. Synchronized methods also ensures that state of the changes in the object is visible to all threads (happens before relationship) when the methods exits.

public class ThreadSync {

 class MyCounter {
  int count = 0;
  MyCounter() {   
  }
  public synchronized void increment() {
   count = count + 1;
  }
 }
 
 class MyThread extends Thread {
  MyCounter counter = null;
  MyThread(MyCounter counter) {
   this.counter = counter;
  }
  public void run() {
   counter.increment();
  }
 }
 
 public static void main(String[] args) {
  ThreadSync ts = new ThreadSync();
  MyCounter counter = ts.new MyCounter();
  Thread t1 = ts.new MyThread(counter);
  Thread t2 = ts.new MyThread(counter);
  t1.start();
  t2.start();
 }
}

Synchronized Statements

Synchronized statements is another approach of achieving synchronization in Java. This approach needs an object that provides the lock.

There are 2 scenarios where synchronized statements would be useful.

  1. When we are working with third party libraries which are not multi-threaded and we don't have access to source code then synchronized statement blocks could be used to achieve thread safety.
  2. Synchronized statements are also useful for improving concurrency with fine-grained synchronization where the entire method need not be synchronized but only certain lines of the method.

public class ThreadSync {

 class MyCounter {
  private int count = 0;
  private Object lock = new Object();
  MyCounter() {}
  public void increment() {
   synchronized(lock) {
    count = count + 1;
   }
  }
 }
 
 class MyThread extends Thread {
  MyCounter counter = null;
  MyThread(MyCounter counter) {
   this.counter = counter;
  }
  public void run() {
   counter.increment();
  }
 }
 
 public static void main(String[] args) {
  ThreadSync ts = new ThreadSync();
  MyCounter counter = ts.new MyCounter();
  Thread t1 = ts.new MyThread(counter);
  Thread t2 = ts.new MyThread(counter);
  t1.start();
  t2.start();
 }
}

Reentrant synchronization

Consider an example of a synchronized method which is called recursively by a thread. In this case the thread acquires the lock which it already owns. Allowing a thread to acquire the same lock more than once is called re-entrant synchronization.

Trending

Contact Form

Name

Email *

Message *

Back to Top