Friday, 30 December 2011

Issues in configuring settings.xml in maven

As you know, maven is build tool for software java projects. Most of the developers have uses maven over ant these days because of maven resolve their dependencies.

settings.xml in maven is used to configure enviornment specific settings such as repositries(Local and remote repositories) and proxy configuration and server credetials.

what is repository in Maven:-

As you know, in java application, there are a lot of dependencies such as log4j,apache libraries. These are called dependencies to your project. you have to define all your dependecies in pom.xml.

This libraries are avilable in apache repositories. so you have to download all these files when we don't use maven in your project.
If we have used maven to your project, these libraries(jar files) are downloaded to your local repository for the first to your company host.

Local repository contain java libraries downloaded from different libraries repositories.

This settings.xml is created in your {user's m2 folder}/.m2/settings.xml by default.
Read More

What is final keyword in java?

final keyword in java

java final keyword
final is one of the Java keywords which can be applied to variables, method, and class and the meaning is once final is applied, it's value or state cannot be changed

what is final keywords for variables:-

if we apply the final keyword to fields or member variables, the variables are tread as constants, that means once created, and assigned the value, The value can not be changed
final int value=20;
// Gives compile time error for the below line of code

So you have to use the fields as final whenever the value of the field cannot be changed once it is initialized.

what are final keywords for methods

methods also can be declared as final. A final method cannot be overridden in a subclass

following is the usage of final method
class SuperClass {
 public final void method1() {


 public int method2() {
  return 0;


class SubClass extends SuperClass {
 // the following method throws Compile time exception as this method has
 // been declared in Superclass.Final methods ca
 public final void method1() {


 // This works fine
 public int method2() {
  return 0;


what are final keywords in a class

if we mark the class as final, the class can not be extended by other class. This makes the class as some specific class which is secure.
Most of the classes in java.lang.Math classes are final classes.
The compiler will throws error if we extends the final class.

Here is the example for final class
public final class SuperClass {


// the following class throws Compile time exception as the Superclass declared
// as final

class SubClass extends SuperClass {


Final as argument to the method

You can also pass the final keyword to the parameters to the methods. That means the parameters can not be changed and local to the method

public void getValue(final int i){

Please click on +1 button if you like this post
Read More

Wednesday, 28 December 2011

Top 10 Examples of SVN Commands

Top ten Examples of SVN Commands

SVN commands are used by most of the developers when there is project development involves multiple locations by different teams.

I am listing down the some of the frequently used commands

How to find the SVN version?

E:\techrocksz>svn --version
svn, version 1.6.12 (r955767)
   compiled Jun 21 2010, 16:00:59

Copyright (C) 2000-2009 CollabNet.

This will display the current svn client version

 How to find different commands available in the SVN tool?

E:\techrocksz>svn help
usage: svn  [options] [args]
Subversion command-line client, version 1.6.12.
Type 'svn help ' for help on a specific subcommand.
Type 'svn --version' to see the program version and RA modules
  or 'svn --version --quiet' to see just the version number.

Most subcommands take file and/or directory arguments, recursing
on the directories.  If no arguments are supplied to such a
command, it recurses on the current directory (inclusive) by default.

Available subcommands:
   blame (praise, annotate, ann)
   changelist (cl)
   checkout (co)
   commit (ci)
   copy (cp)
   delete (del, remove, rm)
   diff (di)
   help (?, h)
   list (ls)
   move (mv, rename, ren)
   propdel (pdel, pd)
   propedit (pedit, pe)
   propget (pget, pg)
   proplist (plist, pl)
   propset (pset, ps)
   status (stat, st)
   switch (sw)
   update (up)

Subversion is a tool for version control.

This command will list down all the available commands (Add, checkout etc..) in svn client tool.

How to Checkout from SVN

Checkout means creation a local workable copy of your project retrieved from the remote repository.

Let us say you have a project located in a repository created at URL location
so you have to check out myproject into your local system assuming myrepo is a public repository.

svn co

It will copy all your files located in myproject to the current directory.

if you want to checkout the directory which is not located in public repository i.e private repository which is specific to your company. Then you have to give one more option--username and --password

svn co --username admin --password admin
Read More

Tuesday, 27 December 2011

How to Install Subversion or SVN Client on Windows?

SVN installation on windows

SVN client is mostly used by software developers to do the svn based operations(creating a branch, Checkout and committing code etc..).
This task is mostly done daily to make code changes on java projects.

First, try to get the required installation exe file CollabNet Subversion Client v1.6.12 (for Windows) from collab's site.
Once you downloaded the exe file, following the following steps to install the svn client on windows

1. click on CollabNet Subversion Command-Line Client v1.5.12.exe file and follow the instructions to install the client on your local box.
This will install to the default folder in program files i.e Drive:\Program Files\CollabNet\Subversion Server.

2. After installing the svn client, go to Environment Variables in System properties, please make sure that "Drive:\Program Files\CollabNet\Subversion Server" value is added to PATH variable.
if PATH is not set, please add "%PATH%;.;Drive:\Program Files\CollabNet\Subversion Server" as value for the key "PATH".

3. Svn version Command

 Now SVN client is installed and read to use.
Please open a command prompt and type the following command in the command prompt to test the svn client is properly installed or not

svn --version

here is the result of the above command.

Command results the correct version 1.6.12. so you are ready to use svn client for doing more operations.

Please click on +1 button if you like this post.
Read More

Monday, 26 December 2011

How to Convert BigInteger to String?

How to Convert BigInteger to String?

Coversion of BigInteger to String is one of the day to day task for java programmer.
Few days back i have the need to convert the BigInteger to Integer in my programming
It is simple task to do the same

BigInteger is commonly used for storing the numerica values by result of arbituary arthamatic calculations.
In My Previous Post, we have discussed about the conversion of BigInteger to Integer or viceverse. we can also do the same for conversiton to String

We have two cases 1. BigInteger to String 2. String to BigInteger

Covert BigInteger to String object:-

We can do this in many ways

One of the way is to use the BigInteger.toString() method or String.valueOf() in java.This is simple coding task to do.

BigInteger class constructor for passing String as parameter for BigInteger object creation

BigInteger bi=new BigInteger("123");

As you know every java class has toString method, To return the String object with for the BigInteger class.

Following is the line of code for returning String object

String str=bi.toString();

//The following case works without throwing exception
  BigInteger bigIntegerdemo = new BigInteger("123");

  //The following case doest not works and throws NumberFormatException
  BigInteger bigIntegerdemo1 = new BigInteger("123");

The disadvatanges with this approach is alwasy we need to pass the numeric value in the form of String for BigInteger constructor.
if String like "abc" is passed, it throws NumberFormatException.

The other way around to conversion to String is first convert BigInteger object to bytes using toByteArray() method and then passing array bytes to String's byte Constructor

BigInteger bigIntegerdemo2 = new BigInteger("123");
  byte b[]=bigIntegerdemo2.toByteArray();
  String s=new String(b);

Covert String to BigInteger object:-

Other way around is to use the BigInteger.toByteArray()
In this process, we are converting String to array of bytes using String.getBytes() method and then Bytes to BigInteger using toByteArray() method.
String msg = new String ("Hi Techrocksz!");
  BigInteger bi = new BigInteger(msg.getBytes());
  System.out.println(new String(bi.toByteArray())); // prints "Hi Techrocksz!"

Hoep you understand this. Please leave a comment if there are any more ways to convert this
Read More

Why main method is declared as static in java?

Why main method is declared as static in java?

As you know in simple java program, we declared the main method as following way

public static void main(String args[])

here the method name is main.

By using java javafilename command, JVM loads the java class into the memory and looks for the main class in the java file.

if main method is not found, it throws NoClassFoundError exception.
if main method is found, it will start the java exectuion code process.

if you want to access the any method, we can use method name with object (like object.method()),
For main method, we are declaring the method as static, means JVM can access the main method directly using the direct class name.That's why for being main method declared as static, object creation is not created.

Void in main method returns nothing.

public keyword means, any other outside all classes can be accessed.

Strings Args[]:- arguments are command line arguments for the java class. we can set arguments throug command line as part of java tool to send the some arguments while executing java program.

usage :- java javafilename argument1 argument2

arguments1,argument2 are available in string args[], once execution starts with the above command.

Hope you understand the basic usage of main method.

Please feel free to comment if you like this post, if you  have any questions.
Read More

How to convert BigInteger to Integer or Integer to BigInteger in java?

Conversion of Integer to BigInteger to Integer is a day to day task for java programmer.
A few days back I have the need to convert the BigInteger to Integer in my programming

It is a simple task to do the same

BigInteger is commonly used for storing the values beyond the range of 2 power 32 values. It is mostly used in arbitrary precession arithmetic operations.

Convert Integer to BigInteger object:

Conversion of integer to BigInteger is an easy task as the BigInteger object has provided one of the method BigInteger.valueOf(int value) method

int integerMaximumValue = 123;
BigInteger bigIntegerdemo = BigInteger.valueOf(integerMaximumValue);

Covert BigInteger to Integer object:

BigInteger has BigInteger.intValue() method to conver to Integer object.

BigInteger bigInteger =BigInteger.valueOf(123);
Read More

Sunday, 25 December 2011

BigInteger tutorial with example in java

What is Big Integer?:-

BigInteger is one of java object in java.math package in java as part of JDK1.6.

Integer Primitive stores the number values between the range of 2 power 31 -1 -2 power 31
Long Primitive stores the numerica values between the range of 2 power 63 -1 -2 power 63.

When we are doing the Arthematic operations with either integer or long, if the result of the arthematic operation is not accomadating the their range,
saves the lower order 32 bits for integer,64 bits for long and gives the lower range result

But if we use BigInteger, it gives the correct result

BigInteger can also be used in numerious bit operations and other mathematical functions which can be store the numeric values over 2 power 64 values.

Big Integer Example:-

import java.math.BigInteger;

public class BigIntegerDemo {
 public static void main(String args[]) {

  int integerMaximumValue = 2147483647;// This is maximum value for
  // integer type i.e 2 power 31

  System.out.println("Case=1     = " + integerMaximumValue);
  System.out.println("Case=2 = " + (integerMaximumValue + 1));
  System.out.println("Case=3 = " + (integerMaximumValue * 2));
  System.out.println("Case=4 = " + (integerMaximumValue * 4));
  // All the above cases expect Case=1 gives wrong value as overflow
  // occured

  // All the below cases gives expected values as BigInteger Object
  // accomdates more values
  BigInteger bigIntegerdemo = BigInteger.valueOf(integerMaximumValue);
  System.out.println("Case=5 " + bigIntegerdemo);
  System.out.println("Case=6 " + bigIntegerdemo.add(BigInteger.ONE));
  System.out.println("Case=7 "
    + bigIntegerdemo.multiply(BigInteger.valueOf(3)));
  System.out.println("Case=8 "
    + bigIntegerdemo.multiply(BigInteger.valueOf(4)));

and the following is the output

Case=1     = 2147483647
Case=2 = -2147483648
Case=3 = -2
Case=4 = -4

Case=5 2147483647
Case=6 2147483648
Case=7 6442450941
Case=8 8589934588

Attached is the methods available in BigInteger with using javap command.

This topic has been a very basic start to explore on BigInteger example. Hopefull you have enough information to get started.
If you have any questions, please feel free to leave a comment and I will get back to you.

Please click +1 button if you like this article.
Read More

Monday, 19 December 2011

How to Store unique objects to avoid the duplicates in java List?.

In real time scenarios, you encountered the cases having duplicate objects in a list.
To remove the duplicates, There are no java Collections implementations to solve this.
In Collections, List allows duplicate values and maintain the insertion order, where as Set does not allows duplicates,doesn't maintain order.

To achive this,We can do this in number of ways.


1. We can write our own set and list implementation by extending List implementation and Implementing Set interface
You can not consider implementing List as already Set is implementing. You can Consider for extending ArrayList as it is not final
For this you need to overide the Add method and hashcode method to achive without duplicates and order


apache common-collection API provided org.apache.commons.collections.list.SetUniqueList class to avoid duplicates in a list

You can use this class for the same functinality
Please leave a comment if you need more information on implementation
Read More

what is volatile keyword in java?

Volatile is keyword in java which is applicable to member variables only.

what does it mean if we declare a transient member variable in an object.

In the multithreaded applications, state of any object can be modified asynchronously by multple threads

This causes the consistency to the state among different concurrent threads.

To maintain the consistence between all the threads for that state of an object we can declare member variable as transient.

Whenever thread is going to execute the object, it tries to get the state of an object from memory, and save the state after thread execution is over, so that object's state can be consistent among concurent multiple threads.


private volatile String mState;
Read More

Sunday, 18 December 2011

What is a Subversion?

What is SVN or SubVersion :-
SVN is version configuration management system used in most of software projects to maintain the code at one of repository location.
SVN is implmented by apache framework and the current version is Apache Subversion 1.7.2

Subversion is same as like as CVS with additional features.

When we are creating any code base in subersion, First we need to create a repository. Repository is remote network folder which has all the code base as well as project related document.

Repository is located in remote server that can be windows based or linux based systems.

Clients or developers has to install the svn clients such as standalone Tortorise SVN clients or command based clients to get the code.

Once users are installed the svn clients they can copy the code from the repository to therir local systems, code chagnes can be modified in local copy, once the changes are done, again they save their code to the repositiroy. so that multiple users have synch to the repositiorys

SVN is used mainly to sync the code base that will be changed by mulitple teams in a project.

Most of java open source projects uses SVN as tool for maintaining the code base.

what is Checkout in SVN?:-

Checkout is cvs jargon used to create a local copy of the code base from the repository. This can be done either from the SVN GUI clients(Totorise SVN) or command based clients

what is commit in SVN?
commit is cvs jargon used to save the local copy of the code base to the repository code base, so that code in the local and repository is synch always.

What is Merge in SVN?Team A started work on code that is checkout from repository for the one project. Team b checkout the code from repositiory after Team A checkouts.

Team A finish their work for the local copy and commit their local changes to Repository.

But team b has their own local copy changes. when team B is going to commit their changes, SVN will do the merge process.
It will copy the all corresponding changes in local copy to repository.

while merge is happening, it will show conflicts for all the individual files, we need to see the difference between those conflict files and do the merge process

There are two types of merge in SVN

1. Automatic Merge :- Automatic means svn resolve the conflicts automatically. No changes are required from the developer
2. Manual Merge:- SVN provides the merge manager, in that we can compare the files that have conflicts and merge as per the code base.
We need to do this carefully as there is missing of code in if we have not done correctly

Advantages or benefits of Subversion:-
SVN is lightweight tool. Easy to learn and setup as well as for administration.
Full revision history of all the that are modified/added/delete/Renmated
Easyly integrated with other build tools to achive the Continuous Integration testing.

Maintaining the different version of code base in the repository by simple commands

This topic has been a very basic start to explore on SVN tutorial Hopefull you have enough information to get started.
If you have any questions, please feel free to leave a comment and I will get back to you.

Read More

Sunday, 11 December 2011

What is the use of javap command in java?

javap is the tool provided by java framework which was bundled with JDK software. This tool(javap is located in JAVA_HOME\bin location) which is used by many java developers to find the different member variables and methods for any java object.

We can also use -c options to with javap command to complie the source code and display the information about the object
Read More

Saturday, 10 December 2011

Add Google +1 button to your website or blog

Google +1 is a for making your friends aware about your liking content.

It is more or less like a facebook like button. It will effect the search engine rankings. so Please give it try to your blog or website.

Google +1 is not that much popular, by adding this, we will see traffic increase due to the fact that if someone clicked on +1, their friends see it on google.

here are the steps to add +1 button to your site:-
1.First get the java script code provided by google.
Click here to get the javascript code. you can select and customize the design of the buton

2.the code plusone code can be placed wherever you want the required +1 button.

3.Above script code should be loaded whenever page loads. so you have to places this just like a javasript placement or css location before tag.
To add +1 button to blog:-

1.Go to Design link on your manage blogs in your blogger home page.
2.Click on edit link where you want the +1 button. pop window is show by clicking on edit link

Please let us know if you have any questions.
Read More

Distribute File System VS Normal File System

Difference between Distribute File System and Normal File System

Distrubted File System is like a normal file system with different nodes where each node has the local file system to store the data. This multiple local file system will coordinate with some protocal to give the data to external clients.

The clients call this multiple machines with some protocal to get the data. Most of times communication protocal is tcp/ip. For accessing any information on Distirubute file system, you need client software.

Listing out the differences between Normal File System and Distrubted File System.

Normal File System:-

1. Data is maintained in Single system. if machine is down, we can not able to get the data and failover chances are more.
2.The time taken to read the data in this less as there are only read call to hardisk and the local processing time

Distributed File System:-

1.Data is replicated in different nodes. clients able to read the data, if any node is failed.Failover is less.
2.The time taken to read the data in this is more as we have network remote call and local data read to disc and coordiating the data from multiple systems

This topic has been a very basic start to explore on maven dependency example. Hopefull you have enough information to get started.
If you have any questions, please feel free to leave a comment and I will get back to you.

Read More

What is Hadoop?:Apache Hadoop Tutorials

Hadoop tutorial :-

Hadoop is a apache framework developed completely in java java with opensource brand.
Hadoop analyze and process large amount of data i.e peta bytes of data in parallel with less time located in distributed environment. Hadoop is not a single tool which contains combination of different sub frameworks called Hadoop Core,Map Reduce,HDFS,Pig,HBase. Hadoop is mostly used for OLTP transactions. Some big companies like facebook uses hadoop for OLAP transactions as well.Hadoop can be setup in clustered environment as well as single node environment.

HDFS is developed based on google file system (GFS)
Map Reduce is developed on google map reduce concept.
Pig framework is SQL wrapper for map reduce jobs

Basics of Hadoop HDFS :-

In Hadoop, data is stored in hadoop distributed file system (HDFS) software in the form blocks (chunk of size),data is replicated in different nodes (called machines) in clustered (many nodes) environment. In real time scenario, thousands of peta bytes data is stored in thousand of  nodes in distribute environment. The advantages with storing replicated data is data available when one of the node is down. With this, data available all the time for the clients apps. Do we need high end hardware for all these nodes? Answer is no, we can accommodate commodity hardware for all these nodes.

if data is grown rapidly, we can add nodes without fail over of the whole system and losing the data. This we can call it as scalable system in network terminology. This system handles the case of losing data while adding machines to the existing machines or after the machine add to the cluster.
As you know cluster has different nodes, if one node fails, hadoop handles the scenario without losing the data and serves the required work as expected.

HDFS stores the data in the files where this files uses the underlying operating system’s file structure.

HDFS is suitable for storing the large amount of data like peta and tera bytes of data which process the data using Map reduce for OLTP transaction.

Data storage in HDFS:-

In HDFS, set of data is called as blocks,each block of data is replicated in different node or machines. The number of nodes where this data is replicated is configured in hadoop system.

Basics of Hadoop Map Reduce :-

In hadoop system, peta bytes of data is distributed in thousands of nodes in cloud environment.To process the data stored in HDFS, We need a applications.
Map Reduce is a java framework  used to write programs, which are executed parallel  to process large amount of data in clustered environment.
Hadoop provides Map Reduce API’s to write map reduce programs. We have to make use of those API’s and customize our data analysis login in the code.
The map reduce piece of code fetchs and process the data in distributed environment

As we want to process the data stored in HDFS,For this we need to write programs using some langugage like java or python etc.

Map reduce has two different task 1.Mapper 2. Reducer

Map takes the input data and process this data in set of tasks with dividing input data. and out of this map is result of set of task, which are given to reducer. reducer process this data and combine the data output the data.

Basics of Hadoop Hive:-

Hive is apache framework which is SQL wrapper implementation of map reduce programs. Hive provides sql languages which understand by hadoop system.

Most of the times, data analysis done by database developers, so DB developer is not aware of the  java programs, in that case, hive tool is useful.

Database developer writes Hive Queries in hive tool for the result. This queries calls the underlying map reduce jobs, process the data, finally data is returned to hive tool.
Advantages with hive is no need of java programming code in hadoop environment.

In some cases, sql queries are not performing well, or some database feature (group by sql function) is not implemented in hive, then we have to write map reduce plugin and register this plugin to hive repository. This is one time tasks.

On top of all these, we have Hadoop Common which is core framework written for processing distributed large set of data to handling the hadoop features.

Hadoop Use case explained:-

Let me take scenario  before apache hadoop is introduced into software world

i am going to explain about the use cases of data processing for one big data company.
Retail company has 20000 stores in the world. Each store will have the data related to products in different regions.This data will be stored in different data sets including different popular databases in multi software environment. Data company would need licenses of different softwares including databases and hardware

For each month, if this company wants to process the data by store wise for finding the best product as well as loyal customer that means we need to process and calculate the data and findout the best customer as well as best selling product in each region to give better offers.
Assume that 2000 stores will have the data of all the products and customer details, and customer purchase information per each stores.

To target the the below use cases.

To find the popular product sold in the last year Christmas per the Store A, so that this year we can target the customers to give different discounts for this products
Top 10 Products sold
selecting the top 100 customers per each store to give more offers.

From the technical point of view, we have large data infrastructure to store this data as well as we need to process the data, for this we need data warehousing tools to process this normalized and unorganized which are costly. and also storing should have reliable as it will impact the data loss
Over this time data process is complex and license cost of maintain is more.

Suppose 10000 more stores added, data is grown, more nodes are added to current infrastructure, but overall performance system degrades as the  nodes are added

Apache hadoop  solve the above problems.

This topic has been a very basic start to explore on what is hadoop. Hopefull you have enough information to get started.

If you have any questions, please feel free to leave a comment and I will get back to you.

Read More

Sunday, 4 December 2011

Top 10 JDBC Interview Questions

1.what are different frequent JDBC classes or interfaces used in java code?


. 2.How do you load the JDBC driver class?.

Class.forName("DriverClass") is used load the driver class. whenever DriverClass is loaded with this, create a new instance of DriverClass and register the driver with DriverManager Class.Once Driver is registered, it is ready to create physical connections to database using Connection object.

3.What is connection pooling?.

as a creating a database connection is like a opening a socket connection to remote machine, so this call is expensive. whenever we have to do CRUD operations(create,read,update and delte) on data to database,Connection object is used for this. creating a connection for each operation is expensive. To avoid this, at the Initial state(application startup), creating a pool of connections which are created and connected to the database. whenever an database operation is to needed by application, the connection from pool of connections are reused,once the operation is over, the connection is returned instead of closing(in case of normal connection) connection, so that Database calls are reduced and nonperformance is increased.

Read More

Statement,PreparedStatement and CallableStatement

In JDBC, There are different statements to execute the sql queries in databases. We can send the simple SQL,complex SQL and PL/SQL queries using this statements There are three types of Statements. The following statements are returned from the connection object.before creating any statement object, connection should be presented. The connection object can be returned from the following lines of code
Connection con= DriverManager.getConnection("jdbc:odbc:orc", "scott", "tiger");
1.Statement :-
This is simple Statement to execute SQL queries like insert,update and delete operations. for this we can not know the input values. For each query, compilation and execution is done at database level.we can use this for static queries and input values are not accepted
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from employee where employee_id=11");
} catch (SQLException e) {
} finally {
Whenever this query is passed from jdbc application to database for getting the result,At Database level,query is complied first and execute the query and return the result. if we want to execute the multiple same queries with different employee_id, multiple compilation and multiple executions are happened. To avoid the multiple compilations, we have to use PreparedStatement.
2.PreparedStatement :-
This Statement is to be used to execute multiple SQL queries like insert,update and delete operations multiple times. for this, we will pass multiple different input values for the same query. if there are multiple queries with different input values, query is complied (parsed and create a plan) for the first time and execution will be happened for different values multiple times by using the same plan at database level.This improves the performances as compared to Statement .we can use this for dynamic queries and dynamic input values are accepted.Same query takes the values as placeholder(?,?,?).
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET name= ? WHERE employee_id = ?";
pstmt = con.prepareStatement(SQL);
} catch (SQLException e) {
} finally {
3.CallableStatement :-
This Statement is to be used to execute database stored procedures which resides at database.stored procedures are set of sql statements stored at database level under single name, thus improves the performance.
CallableStatement cstmt = null;
try {
String SQL = "{call procedureName (?, ?)}";
cstmt = conn.prepareCall (SQL);
. . .
catch (SQLException e) {
   . . .
finally {
. . .
SQL statement has the procedure name with place holders.
Here the placeholders are of type IN,OUT,INOUT parameters.
IN parameters means input parameters, we can set using setXXX methods. OUT or INOUT parameters should be used by having one more method registerOutParameters which are mapped the java datatypes to database column data types.
Please leave a comment if you have any questions.
Read More

Convert of String to Integer or Integer to String in java

As a developer, in day to day programming, we have encountered in number of situations to convert from String to Integer or vice verse.
convertion of String to Integer:-
There are number way to convert from String to integer. For this, String should holds valid int value. if an invalid numeric value is presented in string, then NumberFormatException is thrown by parseInt method.For this, you have to handle using try and catch blocks
one way is to create a Integer object which has Constructor of String type. This conversion happens at object creation.
String s="123";
Integer i=new Integer(s);
second way is to using parseInt method of Integer object To convert this to integer we have used Integer.parseInt method.
String s="123";
Integer i=Integer.parseInt(s);
and other way is using valueOf of Integer object
String s="123";
Integer i=Integer.valueOf(s);
Exception Handling:-
String s = "abc";
try {
Integer ii = Integer.valueOf(s);
} catch (NumberFormatException e) {
System.out.println("Invalid integer value in String " + s
     + "exception=" + e);
Read More

Jdbc Basic Example to connect to database in java

Following steps for writing a sample java program to connect to database and get the result. JDBC API is provided by sun framework which contains different interfaces and classes to connect to databases.
The below diagram depicts the steps to connect to any database.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class ConnDemo {
 public static void main(String args[]) throws Exception {
  // establish connection to database this includes loading driver
  // and fetching data.
  // first step is to register jbbc driver with driver manager
  // class.forName loads class which in this case is jdbc
  // implementation of interface Driver
  int rowcnt = 0;

  Connection con;
   con = DriverManager.getConnection("jdbc:odbc:orc","scott","tiger");
  // Once connected, we can execute any sql statement
  Statement stmt = con.createStatement();
  ResultSet rs = stmt.executeQuery("select * from employee");
  while ( {
  System.out.println("No Of Rows Fetched " + rowcnt);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");:- loads the JdbcOdbcDriver class into the jvm and avialble to ready to use.
DriverManager.getConnection("jdbc:odbc:orc","scott","tiger"); :-connection string has to be provided, which contains username,password,database name of oracle.
con.createStatement(); :- return the statement object which is used to get the result set using executeQuery method.
ResultSet object holds all the rows of table which are in the order by result of the query.we have to traverse the result set and fetch the each column value.
Here is the high level flow of any application connect to any database

This topic has been a very basic start to explore on JDBC example. Hopefull you have enough information to get started.
If you have any questions, please feel free to leave a comment and I will get back to you.

Read More

Learn Basics of Inside Java Virtual Machine?

As you know in any machine, we have different components like a hardware (physical machine call it as hardware(CPU, RAM.. etc) and software (Operating System). if you want to perform any operation from another machine, we need to write some code (say in c language) which will open a socket connection, that is a remote network call to other machine and make an OS call i.e native call. Each machine should have different ways to handle this situation. Here the code is tightly coupled means dependent on the target machine. if the target machine is changed or a new machine. The existing code would not work in this case. so that means platform dependent. After the Java virtual machine is introduced, many problems are solved. write once deploy to any machine.

Inside Java Virtual machine:- 

as the name suggests it is a virtual machine run as java process which talks to a physical machine. JVM is dependent on the physical machine, but it gives independent to different machines in the form of Java code.
It is a virtual platform on top of your physical processor.JVM is one of a component of Java runtime environment.

JRE contains a set of Java-based API as well as JVM. The following are responsibilities of the JVM
  • Compiling your java code java bytecode which is understood by the physical machine.
  • Interpret the java bytecode and covert this bytecode into the corresponding native calls i.e Operating system calls
  • Object management handling such as object creation and garbage collection.
JVM has different components.

  • Heap memory:-

    Heap memory is one of the components of the JVM machine which stores the object. here object means which holds the member variables, constructors, and methods. By default heap size is 64 MB. we can increase the size using -Xmx(maximum heap size) and -Xms(initial heap size) options. a lifetime of an object as long as it is referenced. whenever an object is unreferenced, Garbage collector using some algorithm will destroy the objects

  • Stack Memory:-

    holds the local variables. The lifetime of the local variables is the temporary as long as a method executed. Once the function/method execution is over, these variable are removed. This follows the Last In First Out model.

  • Method section:-

    This section holds the current bytecode that is executed presently. once the bytecode is executed, it will point to next bytecode.

  • registers:-

    which are used by the stack variable?
There are multiple different JRE by different vendors
  • 1.JRockit JVM is developed by BEA Systems.
  • 2. Java HotSpot VM developed by Sun Microsystems.

Related Posts:-
1.Learn More about Data transfer Object Design Pattern
2.Learn the basics about Java code to connect to database using JDBC
3.Tutorial with Hello World JSP example
Read More

Saturday, 3 December 2011

Hellow World Jsp Example

Before setting up deploying JSP on your environment, make sure that JAVA_HOME environment is set. and also download tomcat from the apache site annd should set TOMCAT_HOME environment is set.
Please make sure that PATH and CLASSPATH environment variables are set
Steps to create a first webapplication.
  • Create a HelloWorld folder and the folder structure looks like as followng structure
  • HelloWorld root folder containts following structure
  • Create a first.jsp which prints the hello world code to the console
    Hello World JSP page
    <%@ page language=”java” %>
    <% System.out.println(“Hello World ”); %>
    type the above code in the notepad and name it as 'first.jsp'. please this file into your HelloWorld root folder of your webapplication.

  • deploying HelloWorld webapp to tomcat application. to deploy first webapp to tomcat, simply copy HelloWorld app to tomcat installed directory i.e webapps and start the tomcat server. The start script is located under TOMCAT_HOME\bin\startTomcat.bat for windows.
  • Accessing jsp file. For example, to run first.jsp” file, open a browser to the address: http://localhost:8080/first.jsp This will show you the executed JSP file.
  • so you are ready with learning with your first jsp page creation.
    Read More

    java Collections overview

    following are the different collections that we used in java 1.Vector:- is an implementation of list's class and accommodation the allowable array of objects i.e dynamic Synchronized. order of the elements are insertion order. 2.ArrayList:- same as Vector except synchronized supports dynamic array. unsynchronized. order of the objects is in insertion order. 3.LinkedList:- is also same as ArrayList when we will use LinkedList;- retrieving an objects is faster compared to ArrayList and Vector
    Read More

    Front Controller Design pattern in java/jsp applications

    Front Controller is one of the most important design pattern mostly used in web applications.

    The problem:-

    As you know in a webapplication, whenever clients send the request to the server, server process the request, if possible make a database call, get the data from the Database or other third party systems and process the data, and send the response. Here there are different components involved,business data validation,holding the database data(model) and view process. Because of this process, there is a lack of single point of contact for the request. Front Control design pattern is introduce. In This Servlet act as a controller sitting infront of other resources. In this patter, all the request that send by different resoures like browser, mobile client as well as Standalone apps is handled by this servlet and delegate the request to approriate web resources. It is the entry point for the request sent by browser.

    ActionServlet is the front controller for Struts based applications DispatchServlet is the front controller for spring web mvc based applications
    Read More

    Common exceptions in java language

    In java programming, daily coding, we have encountered different exceptions, so I am listing out the list of common exceptions, and the scenarios, how to solve those exceptions.

    following are the exceptions in java programming language. 


    One common exception occurred, This will happens when you are calling the object's method with the object is not created or not initialized properly.
    String str=null; System.out.println(str.toString());

    the solution in our code is
    if(str==null){ //initialize the string object here }else{ System.out.println(str.toString()); }

    ClassCastException error

    This exception occurs if we assign the incorrect object.

    NumberFormatException error

    This exception has occurred if we convert the string data items to number items format object.

    SocketTimeoutException error

    This exception occurred when dealing with sockets communication between client and server. server not accepting sockets accept/read operations

    OutOfMemoryException issue:-

    This issue occurs when an object exists on heap memory is full. The fix is either increase heap memory or fine tune the code to minimize object creation.

    Read More

    Sorting List of Numbers

    In a java programming, Let us say We have a set of numbers say 100,200,4,5,79,26. In java, we can use either Array or List implementation(ArrayList or LinkedList in java.util package used to sort numbers
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.List;
    public class SortDemo {
    public static void main(String args[]){
     Integer[] numbs=new Integer[]{100,200,4,5,79,26};
     System.out.println("Initial List="+numbs);
     /*For sorting numbers we can use Arrays's sort method*/
     Integer[] numbs1=new Integer[]{100,200,4,5,79,26,20};
     /*For sorting numbers we can also use List's  sort method*/
     List listNumbers=Arrays.asList(numbs1);
     System.out.println("Sort List using List sort="+listNumbers);
    Arrays can store the static list of data items, that means size cannot be grown and fixed.where as List store the list of dynamic data itmes.
    Read More

    Friday, 2 December 2011

    Maven Interview Questions

    What is Maven?. Why it is used for? 

    Read More

    Thursday, 1 December 2011

    Linux sudo Command

    sudo is linux/unix command which is used by system administrator to give privileges to some set of users as root. This could be applied to commond level only.

    To check your current sudo privileges, run this command: sudo -l
    Read More

    How to fix java.lang.OutOfMemoryError issue in Maven?

    java.lang.OutOfMemoryError in maven

    Maven is an automation build project management tool. if the project has lot 10000 java files, when you try to build the project using "maven clean install", build failed with an error.
    maven clean install will tries to clean/delete the project and compile the project, and test the project and build the application
    OutOfMemoryError issues occur either in the compile phase of your project or test phase of your project while building your maven project
    For test case execution, maven uses surefire-plugin. in any case, you have a heap to increase the heap size in a number of ways.
    Actually OutOfMemoryError error there is not enough space for your maven process to execute the java project or java classloading issue with your classes.
    java.lang.OutOfMemoryError: Java heap space
    java.lang.OutOfMemoryError: Perm Gen space

    For debugging the exact reason, use the maven -x clean install, it gives exact root cause with a detailed print stack trace.

    First you have to find out which phase this error is occurring
    if the error is giving with compilation, you have to increase heap size as per your system capacity as with following lines of code in Linux, windows.

    Java heap space means there is not enough space to allocate your object execution in heap memory
    Perm Gen space means classloader loads the classes, but when your application still maintains the references of classes after execution is over, this we call it as a memory leak, so you have to use the system classloader when this error occurs in maven

    Fix for OutOfMemoryError for maven in windows:-

    change the environment variable MAVEN_OPTS in such way that increase the heap size by following a piece of code

    set MAVEN_OPTS=-Xmx768M -XX:MaxPermSize=768M

    Fix for OutOfMemoryError for maven in Linux/Unix:-

    Increase heap size for environment variable MAVEN_OPTS.
    the processing for Linux version is different

    export MAVEN_OPTS=-Xmx768M -XX:MaxPermSize=768M

    Most of the times OutOfMemoryError solves with the above lines of code, if it doesn't solve, then follow the below approaches

    Issue with maven-surefire-plugin in maven:-

    As discussed, surefire plugin loads the classes using a different mechanism, we will instruct this plugin to use the system classloader with the following approaches


    the following commands more helpful in debugging your app for running your project
    maven -x
    mvn  -Dmaven.surefire.debug

    Hope you have an idea on solving OutOfMemoryError issues in maven with windows, Linux and Unix environment.

    Feel free to comment if you have anything to share
    Read More

    Maven commands

    As we have encountered the usage of maven in java projects, following are the list of maven commands for your reference. Whenever you run maven command with different goals, It tries to download the different dependencies from the different repositories configured in xml file. If mvn install command unable to download dependent artifacts from repositories, then use the following command with proxy settings enabled
    mvn install -Dhttps.proxyHost="" -Dhttps.proxyPort=""
    To run the maven by skipping unit and integration tests
    mvn clean install -Dmaven.test.skip=true or 
    mvn clean install -DskipTests=true
    To run the maven without downloading artifacts from the repositories i.e offline
    mvn -o install
    To run one test class using maven
    mvn clean test -Pintegration-test -Dtest=java test class
    To execute the maven profile
    mvn -PprofileName install
    Read More

    Build Java project from scratch using Maven

    a maven is a build tool for the java projects. It speeds up the java development build process.maven is one of the Java tools for continuous build integration. Maven has predefined phases or goals. The goals are similar to ant targets. the developer will invoke goals to do their tasks.

    Please make sure that you download maven from the Apache software and install it.
    what are the things to consider while making your java projects to implement Maven as the build tool
    1. project object model file
    2. java project folder structure

    Hello World maven application:- 

    I am going to create a HelloWorld java application.

     mvn archetype:generate -DgroupId=com.techrocksz -DartifactId=HelloWorld -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
    Output of this mvn command:-
    E:\techrocksz>mvn archetype:generate -DgroupId=com.techrocksz -DartifactId=HelloWorld -DarchetypeArtifactId=maven-archetype-quickstart
    [INFO] Scanning for projects...
    [INFO] Searching repository for plugin with prefix: 'archetype'.
    [INFO] ------------------------------------------------------------------------
    [INFO] Building Maven Default Project
    [INFO]    task-segment: [archetype:generate] (aggregator-style)
    [INFO] ------------------------------------------------------------------------
    [INFO] Preparing archetype:generate
    [INFO] No goals needed for project - skipping
    [INFO] Setting property: classpath.resource.loader.class => 'org.codehaus.plexus.velocity.ContextClassLoaderResourceLoader'.
    [INFO] Setting property: velocimacro.messages.on => 'false'.
    [INFO] Setting property: resource.loader => 'classpath'.
    [INFO] Setting property: resource.manager.logwhenfound => 'false'.
    [INFO] [archetype:generate]
    [INFO] Generating project in Interactive mode
    Define value for version:  1.0-SNAPSHOT: : 1.0.0-SNAPSHOT
    Confirm properties configuration:
    groupId: com.techrocksz
    artifactId: HelloWorld
    version: 1.0.0-SNAPSHOT
    package: com.techrocksz
     Y: : Y
    [INFO] ----------------------------------------------------------------------------
    [INFO] Using following parameters for creating OldArchetype: maven-archetype-quickstart:1.0
    [INFO] ----------------------------------------------------------------------------
    [INFO] Parameter: groupId, Value: com.techrocksz
    [INFO] Parameter: packageName, Value: com.techrocksz
    [INFO] Parameter: package, Value: com.techrocksz
    [INFO] Parameter: artifactId, Value: HelloWorld
    [INFO] Parameter: basedir, Value: E:\techrocksz
    [INFO] Parameter: version, Value: 1.0.0-SNAPSHOT
    [INFO] ********************* End of debug info from resources from generated POM ***********************
    [INFO] OldArchetype created in dir: E:\techrocksz\HelloWorld
    [INFO] ------------------------------------------------------------------------
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 30 seconds
    [INFO] Finished at: Fri Dec 02 10:47:29 GMT+05:30 2011
    [INFO] Final Memory: 8M/254M
    [INFO] ------------------------------------------------------------------------
    In the above example created, see the folder structure, In the root folder we have a folder named 'src' and file pom.xml and also we have following subdirectories
    src\main\java :- This folder contains all your java classes src\test\java :-This folder contains all your java test related classes and also we have com\techrocksz\ and com\techrocksz\ files which is a HelloWorld application and it's test class.

    What is pom.xml:-

    pom.xml is a project object model configuration file which is used by maven.
    Maven uses pom.xml which contains all details about your project as well as the configuration details.
    <project xmlns:xsi="" xmlns="" xsi:schemalocation="">
    In the above, groupId represents the package of the project where ExampleDemo-1.0.0.jar file is created artifactId is the project name as well as jar/war name of the module. packaging specify whether this module is web application i.e war or java module i.e jar. if the packaging option is not specified, maven considers this as jar module. dependencies tag specifies the what are dependencies this project has. here as we have written App, by default JUnit dependency is added as part of the sample project. Running Maven Project:-
    1. cd HelloWorld
    2. mvn clean install

    maven execution process:- 

    whenever you executed maven install command, we configured repositories location in pom.xml and the dependencies, For the first time, it tries to download different plugins and dependencies from the repository and copy those dependencies to a folder (the user profile of your document and Settings folder(i.e C:\Documents and Settings\username\.m2\repository). This is time-consuming for the first time as it tries to download all your plugins to your local repository. next time onward, it will download those already downloaded jars and executes quickly
    . Proxy settings to be enabling for maven settings.xml in folder C:\Documents and Settings\username\.m2\ have to be created for this.
    Here is the output of the command.
    E:\techrocksz\HelloWorld>mvn clean install
    [INFO] Scanning for projects...
    [INFO] ------------------------------------------------------------------------
    [INFO] Building HelloWorld
    [INFO]    task-segment: [clean, install]
    [INFO] ------------------------------------------------------------------------
    [INFO] [clean:clean]
    [INFO] Deleting directory E:\techrocksz\HelloWorld\target
    [INFO] [resources:resources]
    [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
    [INFO] skip non existing resourceDirectory E:\techrocksz\HelloWorld\src\main\resources
    [INFO] [compiler:compile]
    [INFO] Compiling 1 source file to E:\techrocksz\HelloWorld\target\classes
    [INFO] [resources:testResources]
    [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
    [INFO] skip non existing resourceDirectory E:\techrocksz\HelloWorld\src\test\resources
    [INFO] [compiler:testCompile]
    [INFO] Compiling 1 source file to E:\techrocksz\HelloWorld\target\test-classes
    [INFO] [surefire:test]
    [INFO] Surefire report directory: E:\techrocksz\HelloWorld\target\surefire-reports
     T E S T S
    Running com.techrocksz.AppTest
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.047 sec
    Results :
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
    [INFO] [jar:jar]
    [INFO] Building jar: E:\techrocksz\HelloWorld\target\HelloWorld-1.0.0-SNAPSHOT.jar
    [INFO] [install:install]
    [INFO] Installing E:\techrocksz\HelloWorld\target\HelloWorld-1.0.0-SNAPSHOT.jar to C:\Documents and Settings\kinturu\.m2\repository\com\techrocksz\HelloWorld\1.0.0-SNAPSHOT\HelloWorld-1.0.0-SNAPSHOT.j
    [INFO] ------------------------------------------------------------------------
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 5 seconds
    [INFO] Finished at: Fri Dec 02 11:58:46 GMT+05:30 2011
    [INFO] Final Memory: 15M/254M
    [INFO] ------------------------------------------------------------------------
    Finally, your module HelloWorld-1.0.0-SNAPSHOT.jar is created. Now Any other app is ready to use this module. Finally, learning maven is started. Please leave a comment if you have any questions.

    Read More

    Data transfer object or Value Object Design Patter

    DTO stands for Data transfer object or Value Object (VO) design patter is a one of the design pattern used for transferring the data between one different machines.

    The problem :-

    In most of the java projects, we have to retrieve the data from the database. In a system, you are queried (select employeeid, employeename from employee) in the databases from your application. Here application is either webapplication or standalone application (applet or Eclipse RCP client). Assume that the applicaiton is executed in Host-1 and MySQL database is hosted in host-2 box. Whenever you are getting the employee information from the application,applicaiton queried the employee id for the first time and employee name for the second time and so on ,repeats this process for all the records.


    here application to database is a network or remote call which is expensive from the application point of view.

    The advatnages with this approaches:-
    • To reduce the network traffic, we will create a java object which has member variables holding each row data and returned the each object or list of objects.
    • Data transfer is made easy and network traffic is reduce.
    • Reduce code duplication with this approach
    public class Employee {
     private long mEmployeeId;
     private String mEmployeeName;
     public void setEmployeeId(long pEmployeeId) {
      this.mEmployeeId = pEmployeeId;
     public long getEmployeeId() {
      return this.mEmployeeId;
     public void setEmployeeName(String pEmployeeName) {
      this.mEmployeeName = pEmployeeName;
     public String getEmployeeName() {
      return this.mEmployeeName;
    I forgot to one more point, whenever java object is transfered between different JVM's or machines, that must be serializable. How to make the java object serializable.

    for any java object to make serializable, we have to implement interface, which has no methods to implement. we can also call this type of interfaces are marker interfaces. so how do we achieve serializable without implementing methods.

    JVM assumes that whenever objects are implemented with serializable interfaces. it is eligible for serialization process. JVM checks each object for using the method (object instanceOf Serializable) for process.

    Read More