Tuesday, August 28, 2012

Top 10 JDBC Best Practices for Java Programmer

Java JDBC Best practices
JDBC Best Practices are some coding practices which Java programmer should follow while writing JDBC code. As discussed in how to connect to Oracle database from Java, JDBC API is used to connect and interact with a Database management System.  We have touched some of the JDBC best practices in our last article 4 JDBC Performance tips, On which we have discussed simple tips to improve performance of Java application with database. By using JDBC you can execute DDL, DML and Stored Procedures. JDBC Best practices is probably most significant set of coding practices in Java because it significantly affect performance of Java application. I have seen substantial performance gain by simply following common JDBC best practices like running queries with auto commit mode disable. One of the query which we used in our example of JDBC Batch update was taking almost 30 second to finish with auto commit mode enabled but it just took under one second with auto commit mode disable and using explicit commit. This JDBC tutorial is collection of such practices which help you to write better JDBC code and in most cases result in improved performance.

Friday, August 24, 2012

How to delete empty files directories in Unix Linux Server

Deleting empty file and directory in Unix
Many times we need to find and delete empty files or directories in UNIX/Linux. Since there is no single command in Unix/Linux which allows you to remove empty files or empty directories rather we need to rely on find command and xargs command. In this UNIX and linux example we will see How to delete empty files and directories. Before removing empty files and directories we need to find those files and there are lots of option available to search for empty directories like find, grep , awk etc. You just need to know correct option. Like in any other operating system empty files and directories in Unix are those whose size is zero. Empty files doesn't contains any content while empty directories does not contain anything at all e.g files or sub-directories. As discussed in previous post 10 frequently used  find command examples we can also use find command to search and delete empty files and directories as it provides searching files based on size as well.

Thursday, August 23, 2012

How to Convert Collection to String in Java - Spring Framework Example

How to convert Collection to String in Java
Many times we need to convert any Collection like Set or List into String like comma separated or any other delimiter delimited String. Though this is quite a trivial job for a Java programmer as you just need to Iterate through the loop and create a big String where individual String are separated by a delimiter, you still need to handle cases like the last element should not have delimiter or at a bare minimum you need to test that code. I like Joshua Bloch advice on Effective Java to use libraries for those common tasks let it be an internal proprietary library or any open source library as used in previous examples of  Spring, Apache Commons or Google’s Guava but point is that you should avoid converting ArrayList to String like common task by yourself on application code.

Saturday, August 18, 2012

How to write parametrized Generic class and method in Java Example

Parameterized Generic class and method in Java
Writing Generic parametrized class and method in Java is easy and should be used as much as possible. Generic in Java was introduced in version 1.5  along with Autoboxing, Enum, varargs and static import. Most of the new code development in Java uses type-safe Generic collection i.e. HashSet in place of HashSet but still Generic is underused in terms of writing own parametrized classes and method. I agree that most Java programmers has started using Generic while working with the Java collection framework but they are still not sure how Generic can allow you to write Template kind of classes which can work with any Type just like the parametrized ArrayList in Java which can store any Type of element. In the last couple of article  about Generics we have seen How Generic works in Java and  explored wild cards of Generic in Java and In this part of Java Generic example we will see How to write parametrized Generic Class and method in Java.

Sunday, August 12, 2012

What is JSESSIONID in J2EE Web application - JSP Servlet?

What is JSESSIONID in JSP-Servlet
JSESSIONID is a cookie generated by Servlet containers like Tomcat or Jetty and used for session management in J2EE web application for HTTP protocol. Since HTTP is a stateless protocol there is no way for Web Server to relate two separate requests coming from the same client and Session management is the process to track user session using different session management techniques like Cookies and URL Rewriting. If a Web server is using a cookie for session management it creates and sends JSESSIONID cookie to the client and then the client sends it back to the server in subsequent HTTP requests. JSESSIONID and session management is a not only a popular Servlet interview question but also appear in various JSP interviews. Along with What is JSESSIONID interviewer are also interested in when and how JSESSIONID is created in Servlet and JSP which we will see in next section.

Saturday, August 11, 2012

Best Practices to write JUnit test cases in Java

JUnit best practices in Java
No doubt writing good JUnit test cases is a rare skill just like writing good Code. A good, well thought and well-written JUnit test can prevent several production issues during initial development or later maintenance in Java application. Though one can only be perfect in writing JUnit test by practice and a level of business knowledge which is important to envision different scenarios on which a method gets called, some best practices or experience of another developer may help to guide other programs. In this Java article, I am sharing some JUnit tips and JUnit best practices which I have learned and follow while writing unit tests using JUnit for Java programs. One of the books which helped me a lot is Pragmatic Unit Testing in Java with JUnit by Andrew Hunt and Dave Thomas,  This book shares a lot of JUnit best practices which are worth reading and learning if you are serious about Unit testing using JUnit

Wednesday, August 8, 2012

How to format String in Java – String format Example

String format and printf Example
How to format String in Java is most common problem developer encounter because of classic System.out.println() doesn’t support formatting of String while printing on console. For those who doesn’t  know What is formatted String? here is a simple definition,  Formatted String is a String which not only displays contents but also displays it in a format which is widely accepted like including comma while displaying large numbers e.g. 100,000,000 etc. Displaying formatted String is one of the needs for modern GUI application and thankfully Java has good support for formatting String and all other types like Integers, Double, and Date. How to format a String in Java is never as easy as it has been since Java 1.5 which along with front line features like Generics, Enum, Autoboxing and Varargs also introduce several utility methods to support rich formatting of String in Java

Monday, August 6, 2012

How to get environment variables in Java- Example Tutorial

Environment variables in Java
There are two ways to get environment variable in Java, by using System properties or by using System.getEnv(). System properties provides only limited set of predefined environment variables like java.classpath, for retrieving Java Classpath or java.username  to get User Id which is used to run Java program etc but a more robust and platform independent way of getting environment variable in Java program on the other hand System.getEnv() method provide access to all environment variables inside Java program but subject to introduce platform dependency if program relies on a particular environment variable. System.getEnv() is overloaded method in Java API and if invoked without parameter it returns an unmodifiable String map which contains all environment variables and there values available to this Java process while System.getEnv(String name) returns value of environment variable if exists or null. In our earlier posts we have seen How to get current directory in Java and  How to run shell command from Java program and in this Java tutorial we will see how to access environment variable in Java.

How to get environment variables in Java - Example

How to get value of environment variable in Java - example tutorialHere is a quick example on How to get environment variable in Java using System.getEnv() and System.getProperty(). Remember System.getEnv() return String map of all environment variables while System.getEnv(String name) only return value of named environment variable like JAVA_HOME will return PATH of your JDK installation directory.

 * Java program to demonstrate How to get value of environment variables in Java.
 * Don't confuse between System property and Environment variable and there is separate
 * way to get value of System property than environment variable in Java, as shown in this
 * example.
 * @author Javin Paul

public class EnvironmentVariableDemo {  

    public static void main(String args[]){
      //getting username using System.getProperty in Java
       String user = System.getProperty("user.name") ;
       System.out.println("Username using system property: "  + user);
     //getting username as environment variable in java, only works in windows
       String userWindows = System.getenv("USERNAME");
       System.out.println("Username using environment variable in windows : "  + userWindows);
     //name and value of all environment variable in Java  program
      Map<String, String> env = System.getenv();
        for (String envName : env.keySet()) {
            System.out.format("%s=%s%n", envName, env.get(envName));


Username using system property: harry
Username using environment variable in windows : harry
USERPROFILE=C:\Documents and Settings\harry
JAVA_HOME=C:\Program Files\Java\jdk1.6.0_20\

Getting environment variable in Java – Things to remember
Java is platform independent language but there are many things which can make a Java program platform dependent e.g. using a native library. Since environment variables also vary from one platform to another e.g. from windows to Unix you need to be bit careful while directly accessing environment variable inside Java program. Here are few points which is worth noting :

1) Use system properties if value of environment variable is available via system property e.g. Username which is available using "user.name" system property. If you access it using environment variable directly you may need to ask for different variable as it may be different in Windows  e.g. USERNAME and Unix as USER.

2) Environment variables are case sensitive in Unix while case insensitive in Windows so relying on that can again make your Java program platform dependent.

3) System.getEnv() was deprecated in release JDK 1.3 in support of using System.getProperty() but reinstated again in JDK 1.5.

That's all on how to get environment variable in Java. Though you have convenient method like System.getEnv() which can return value of environment variable, its better to use System.getProperty() to get that value in a platform independent way, if that environment variable is available as system property in Java.

Other How to tutorials from Javarevisited Blog

Friday, August 3, 2012

5 ways to convert InputStream to String in Java

InputStream to String Conversion Example
Converting InputStream to String in Java has become very easy after introduction of Scanner class in Java 5 and due to development of several open source libraries like Apache commons IOUtils and Google Open source guava-libraries which provides excellent support to convert InputStream to String in Java program. we often need to convert InputStream to String  while working in Java for example if you are reading XML files from InputStream and later performing XSLT transformation on it or if InputStream is reading data from text file or text input Source and we either want to log  Strings in log file or want to operate on whole String. Before Java 5 you would have to write lots of boiler plate code to read String line by line or byte by byte depending upon whether you are using either BufferedReader or not but as I said since JDK 5 added Scanner for reading input, its fairly easy to convert InputStream into String.