Posts

Showing posts from May, 2009

Simple JDBC tutorial

Simple JDBC tutorial .  load jdbc driver  Class.forName("oracle.jdbc.OracleDriver"); create a connection to database  Connection conn = java.sql.DriverManager.getConnection(url, username, password); url is jdbc:oracle:thin:@localhost:1521:orcl create statement Statement  stmt = this.conn.createStatement(); execute query stmt.executeUpdate(query); iterate over ResultSet

Loggers in JAVA

This tip shows how to use Logger in any java application. Logger needs to configure Formatter and Handler. There are many types of handlers and formatters present . In this example FileHandler is used to store all the log messages in a log file. And Simple formatter is used to format the log messages in human readable form. package  MyProject; import  java.io.IOException; import  java.util.logging.FileHandler; import  java.util.logging.Level; import  java.util.logging.Logger; import  java.util.logging.SimpleFormatter; public  class   MyLogger  {    public static  void  main ( String []  args ) {      Logger logger = Logger.getLogger ( "MyLog" ) ;      FileHandler fh;      try  {        // This block configure the logger with handler and fo...

Strings in Java

Image
To create string there are two ways 1. String s3= new String("hello");     String s4= new String ("hello"); 2. String s1= "hello";     String s2="hello"; which method is better ?  second method Because the content is same s1 and s2 refer to the same object where as s3 and s4 do not refer to the same object. The 'new' key word creates new objects for s3 and s4 which is expensive. StringBuffer and StringBuilder StringBuffer is used to store character strings that will be changed ( String objects cannot be changed). It automatically expands as needed. Related classes: String, CharSequence. it is synchronized . StringBuilder was added in Java 5. It is identical in all respects to StringBuffer except that it is not synchronized , which means that if multiple threads are accessing it at the same time, there could be trouble. For single-threaded programs, the most common case, avoiding the overhead ...