Print the limits of the primitive types in Java

The Java programming language is a strongly-typed language and it consist of eight primitive data types (byte, short, int, long, float, double, boolean, char). For more about java primitive data type, please visit

Well, sometime we really need to know what is the limit of the primitive types in java. With following simple code, we can print out the limit of each of the java primitive data types (except boolean and char) 🙂

public class PrintTypeLimit
    public static void main(String args[]) {        System.out.println("Min byte value   = " + Byte.MIN_VALUE);
        System.out.println("Max byte value   = " + Byte.MAX_VALUE);
        System.out.println("Min short value  = " + Short.MIN_VALUE);
        System.out.println("Max short value  = " + Short.MAX_VALUE);
        System.out.println("Min int value    = " + Integer.MIN_VALUE);
        System.out.println("Max int value    = " + Integer.MAX_VALUE);
        System.out.println("Min long value    = " + Long.MIN_VALUE);
        System.out.println("Max long value    = " + Long.MAX_VALUE);
        System.out.println("Min float value  = " + Float.MIN_VALUE);
        System.out.println("Max float value  = " + Float.MAX_VALUE);
        System.out.println("Min double value = " + Double.MIN_VALUE);
        System.out.println("Max double value = " + Double.MAX_VALUE);



Min byte value   = -128
Max byte value   = 127
Min short value  = -32768
Max short value  = 32767
Min int value    = -2147483648
Max int value    = 2147483647
Min long value    = -9223372036854775808
Max long value    = 9223372036854775807
Min float value  = 1.4E-45
Max float value  = 3.4028235E38
Min double value = 4.9E-324
Max double value = 1.7976931348623157E308


How to recover lossed or deleted data on windows 7,8

Do you think this is possible to do? but i think possible,there are various lot of recovery tools in the internet to download,but all of them are not surely work 100% like you are expected.but there is a recovery tool name recuva,working perfectly as you expected. Download recuva here
Okey now we can see the step by steps to start the process.
Step1)-insert the pen drive in to the usb port.wait for some moment to identify .after that right click on the pen drive icon in the computer and scan for recovery of bad sector and automatically fix system errors

Note- above step is important to recover correctly
Step2)- install the recuva recovery software before you downloaded.
Step3)- open the tool by clicking its icon on the desktop. Program will open up.

Step4)- if you recover images tick the dot on pictures ( removable disk /memory device ) and then select deep scan

Note- selecting deep scan is important.

Step5)-click scan .scanning process will start up wait for some hours or minutes .that depending on your pen drive volume.
Step6)-now picture list show up ,you must select the picture you want. click recover and select the location to put the pictures

That’s all enjoy

Now You Can Generate Electricity While You Walk On This Floor

Power Walking energy floorIn the sustainable energy market, Energy Floors, a Netherlands-based firm is trying hard to make its place. They sell products like Sustainable Energy Floor and Sustainable Dance Floor, that convert footsteps into electricity. As soon as anyone steps onto the floor, the tile flexes round about 10mm, and that movement is converted into electricity-15 Watts on average, and up to 25 Watts peak. If the tiles are connected together, 40 to be precise, the network can produce up to 1kW and this is possible due to the modular nature of these tiles.Power Walking energy floor 2Although we do not know how these magnificent tiles are made but for what we know is that it’s not piezoelectric. For what we can see, it looks like a rack-and-pinion that drives a small permanent magnet generator.

The flow of electricity is directed by a controller module. Charging low voltage devices, charging batteries, or lighting pathways with LEDs is all that can be done from the 12V output.

Power Walking energy floor4When you step on the blocks, they light up and this intrigues people to step on them again. Thus it would be an attractive marketing technique too.

As much fun as they may sound, these aren’t a techie joke or a high-tech toy. Russian Railway Research Institute has partnered with them and hopes to put Energy Floors on railroad platforms and high-traffic walkways. They also plan on looking into the use of this technology in order to gain energy from the movement of cars and trains.

Interesting fact, apart from the company’s sustainable focus, not only are the floor tiles made out of recyclable materials but has an expected lifetime of 30years.

Power Walking energy floor3Laurence Kemball-Cook delivers a TED talk on this concept:

‘Sustainable energy is a multifaceted industry. Solar, wind, and hydroelectric are the big players, but small energy-harvesting products have their place as well. A journey of a thousand miles begins with a single step. Energy Floors could make that step more productive.’


Hide and Seek with jQuery.

This tutorial about Hide and Seek with jQuery and PHP. This script helps you to present all modules in single page. Take a look at live demo click buttons


Download Script     Live Demo

Javascript Code

// <![CDATA[
javascript” src=”
// ]]>
<script type=”text/javascript”>

var button_id = $(this).attr(“id”);

//Add Record button


//Cancel button

else if(button_id==”cancel”)

// save button


// insert record
// more details Submit form with jQuery


return false;


Contains javascipt code. $(“.button”).click(function(){}- button is the class name of buttons(Add, Save and Cancel). Using $(this).attr(“id”) calling button id value.

<div id=”results” >

<a href=”#”color: blue;”>button” id=”add” >Add Record </a>

<div id=”save_form” style=”display:none” >

<a href=”#”color: blue;”>button” id=”save” >Save </a>
<a href=”#”color: blue;”>button” id=”cancel” >Cancel </a>

<div id=”update” >


Pagination with jQuery, MySQL and PHP.

I received lot of requests from my readers that asked to me how to implement Pagination with jQuery, PHP and MySQL. so I had developed a simple tutorial. It’s looks big but very simple script. Take a look at this live demo
Pagination with jQuery, MySQL and PHP.

The tutorial contains three PHP files and two js files includes jQuery plugin.

-config.php (Database Configuration)

Download Script     Live Preview

Database Table

message TEXT

Contains javascript this script works like a data controller.


//Display Loading Image

function Display_Load()
$(“#loading”).html(“<img src=”bigLoader.gif” />”);

//Hide Loading Image

function Hide_Load()

//Default Starting Page Results

$(“#pagination li:first”)
.css({‘color’ : ‘#FF0084’}).css({‘border’ : ‘none’});
$(“#content”).load(“pagination_data.php?page=1”, Hide_Load());

//Pagination Click

$(“#pagination li”).click(function(){

//CSS Styles

$(“#pagination li”)
.css({‘border’ : ‘solid #dddddd 1px’})
.css({‘color’ : ‘#0063DC’});

.css({‘color’ : ‘#FF0084’})
.css({‘border’ : ‘none’});

//Loading Data

var pageNum =;
$(“#content”).load(“pagination_data.php?page=” + pageNum, Hide_Load());


You have to change hostname, username, password and databasename.


$mysql_hostname = “localhost”;
$mysql_user = “username”;
$mysql_password = “password”;
$mysql_database = “database”;
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die(“Opps some thing went wrong”);
mysql_select_db($mysql_database, $bd)
or die(“Opps some thing went wrong”);


User interface page.


$per_page = 9;

//Calculating no of pages
$sql = “select * from messages”;
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$pages = ceil($count/$per_page)


// <![CDATA[
javascript” src=”
// ]]>
// <![CDATA[
javascript” src=”jquery_pagination.js”>
// ]]>

<div id=”loading” ></div>
<div id=”content” ></div>
<ul id=”pagination”>
//Pagination Numbers

for($i=1; $i<=$pages; $i++)
echo ‘<li id=”‘.$i.‘”>’.$i.‘</li>’;


Simple php script display data from the messages table.


$per_page = 9;

$start = ($page-1)*$per_page;
$sql = “select * from messages order by msg_id limit $start,$per_page”;
$result = mysql_query($sql);


<table width=”800px”>


while($row = mysql_fetch_array($result))


<td><?php echo $msg_id; ?></td>
<td><?php echo $message; ?></td>





CSS Code
CSS code for page numbers.


width: 100%;
position: absolute;


list-style: none;
float: left;
margin-right: 16px;
border:solid 1px #dddddd;


cursor: pointer;


Struts Validation Framework Tutorial with example.

English: Logo of Apache Struts

Apache Struts has changed the way we develop a Web application. Since its inception as an MVC architecture, Struts has been extensively used in J2EE world to develop robust, extendable and effective web applications.

Introduction to Struts Validation Framework

One of the important features of Struts framework is Struts Validation framework that performs validation on incoming form data. Validation framework was introduced by David Winterfeldt as an external plugin to Struts framework. It’s functionality has since been split so that validator can serve as the basis for a independant component and is now part of Jakarta Commons.

The Struts framework’s simple validation interface alleviates much of the headache associated with handling data validation, allowing you to focus on validation code and not on the mechanics of capturing data and redisplaying incomplete or invalid data.

In order to do form validation without Validator framework, one has to use validate() method of the form bean (ActionForm class) to perform this task. Also one has to handle error messages during manual validation. Lot of fields that we validate require same logic to validate them, hence code is unneccessarily duplicated (if not managed properly).

Validation framework comes with set of useful routines to handle form validation automatically and it can handle both server side as well as client side form validation. If certain validation is not present, you can create your own validation logic and plug it into validation framework as a re-usable component.

Validator uses two XML configuration files to determine which validation routines should be installed and how they should be applied for a given application, respectively. The first configuration file, validator-rules.xml, declares the validation routines that should be plugged into the framework and provides logical names for each of the validations. The validator-rules.xml file also defines client-side JavaScript code for each validation routine. Validator can be configured to send this JavaScript code to the browser so that validations are performed on the client side as well as on the server side.

The second configuration file, validation.xml, defines which validation routines should be applied to which Form Beans. The definitions in this file use the logical names of Form Beans from the struts-config.xml file along with the logical names of validation routines from the validator-rules.xml file to tie the two together.

Using the Validator framework involves enabling the Validator plug-in, configuring Validator’s two configuration files, and creating Form Beans that extend the Validator’s ActionForm subclasses. The following sections explain in detail how to configure and use Validator.

Create a Struts project

Create a struts web application project. I assume you have working environment set for a Struts project. If not then go through the tutorial: Creating Struts application using Eclipse and create a struts project.

Create Form Beans

struts validator form bean
Create a form bean in your project called CustomerForm and copy following code in it.

package net.viralpatel.struts.validation.form;
import org.apache.struts.validator.ValidatorForm;
public class CustomerForm extends ValidatorForm {
    private String name;
    private String telephone;
    private String email;
    private int age;
    public String getName() {
        return name;
    public void setName(String name) { = name;
    public String getTelephone() {
        return telephone;
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    public String getEmail() {
        return email;
    public void setEmail(String email) { = email;
    public int getAge() {
        return age;
    public void setAge(int age) {
        this.age = age;

We will use this validator plugin to validate this form. Note that the form bean is extended from class ValidatorForm and not ActionForm as we generally do in Struts project.

Add Validator Plug-in in struts-config.xml

In order to use Validator in our project we need to configure it in struts-config.xml file. For this add following code in your struts-config.xml file.

<!-- Validator Configuration -->
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
    <set-property property="pathnames"
                /WEB-INF/validation.xml" />

This definition tells Struts to load and initialize the Validator plug-in for your application. Upon initialization, the plug-in loads the comma-delimited list of Validator config files specified by the pathnames property. Each config file’s path should be specified by use of a Web application-relative path, as shown in the previous example.

Define validations for the form

validation.xml file struts validator framework

Create a file validation.xml in your applications WEB-INF directory. And copy following content in it.

<?xml version="1.0" encoding="UTF-8" ?>
<!--DOCTYPE form-validation PUBLIC
          "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"
    <form name="CustomerForm">
        <field property="name" depends="required">
            <arg key="" />
        <field property="age" depends="required, integer, intRange">
            <arg0 key="label.age" />
            <arg1 key="${var:min}" resource="false"/>
            <arg2 key="${var:max}" resource="false"/>
        <field property="telephone" depends="required, mask">
            <arg key="label.telephone" />
            <arg1 key="label.telephone" />
        <field property="email" depends="email">
            <arg0 key="" />
            <arg1 key="" />

In the above xml file, we have defined the rules for form validation. Note that we are validating form CustomerForm and the fields being validated are name, age, telephone and email. tag defines the validation for a property of form. We can specify different rules like required, integer, email, intRange, mask etc in depends attribute of field tag..

Also you can define constants that can be reused in the validation xml using global constants tag.

Struts-config.xml entry for the action

Following is the entry in struts-config.xml file which maps the Action to our Validator form.

    <form-bean name="CustomerForm"
        type="net.viralpatel.struts.validation.form.CustomerForm" />
    <action path="/customer" name="CustomerForm" validate="true"
        <forward name="success" path="/Customer.jsp" />
        <forward name="failure" path="/index.jsp" />


Struts validation framework uses externalization of the error messages. The messages are stored in a property file ( and are referred by the key values. Copy following in your (or Name Email
label.telephone= Telephone
label.age= Age
# general error msgs
errors.header=<font size="2"><UL>
errors.prefix=<LI><span style="color: red">
errors.invalid={0} is invalid.
errors.maxlength={0} can not be greater than {1} characters.
errors.minlength={0} can not be less than {1} characters.
errors.range={0} is not in the range {1} through {2}.
errors.required={0} is required.
errors.byte={0} must be an byte.{0} is not a date.
errors.double={0} must be an double.
errors.float={0} must be an float.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.short={0} must be an short.

Create JSP to display the form

Create a JSP file called index.jsp and copy following content in it.

<%@ taglib uri="" prefix="html"%>
<%@ taglib uri="" prefix="bean"%>
<title>Struts Validation Framework example.</title>
<html:errors />
<html:javascript formName="CustomerForm" />
<html:form action="/customer">
    <bean:message key="" />
    <html:text property="name"></html:text>
    <br />
    <bean:message key="label.age" />
    <html:text property="age"></html:text>
    <br />
    <bean:message key="" />
    <html:text property="email"></html:text>
    <br />
    <bean:message key="label.telephone" />
    <html:text property="telephone"></html:text>
    <br />
    <html:submit value="Submit"></html:submit>

Running the application

We are done with our application. Now execute it from any web container (Tomcat in my case) and open in browser.
struts validator form screen

Enter any invalid value in the form and press submit.


Reference :

Tomcat Manuall Configuration On windows

English: Logo of Русский: Логотип Apache Tomcat

Setting the JAVA_HOME , CATALINA_HOME Environment Variable on Windows

One can do using command prompt
1. set JAVA_HOME=C:\”top level directory of your java install”
2. set CATALINA_HOME=C:\”top level directory of your Tomcat install”

Or you can do the same

  1. Go to system properties.
  2. Go to environment variables and add a new variable with the name  JAVA_HOME and provide variable value as C:\”top level directory of your java install”.
  3. Go to environment variables and add a new variable with the name  CATALINA_HOME and provide variable value as C:\”top level directory of your Tomcat install”.
  4. In path variable add a new variable value as ;%CATALINA_HOME%\bin;

and write startup.bat on command Prompt and press enter tomcat will start up and for shutdown u just write shutdown.bat        once you start the tomcat you can access it like that http://localhost:8080     and access Application Manager using login and password …. if you dont know username and password you can  follow below instructions ….

User and password for Tomcat

By default, Tomcat does not enable admin or manager access. To enable it, you have to edit the “%TOMCAT_FOLDER%/conf/tomcat-users.xml” manually.

File : tomcat-users.xml (before update) , initially, Tomcat comments all users and roles like above.

  <role rolename="role1"/>

File : tomcat-users.xml (after updated)

<?xml version='1.0' encoding='utf-8'?>
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
  <role rolename="manager"/>
  <role rolename="admin"/>
  <user username="admin" password="admin" roles="admin,manager"/>

To enable admin access, just update the content like above. Saved it and restart Tomcat, now you can access Tomcat admin or manger pages with user = “admin” and password = “admin“.

Difference between execute, executeQuery, executeUpdate

International Bibliography of Periodical Liter...

executeQuery()—for getting the data from database
executeUpdate()—for insert,update,delete
execute()—any kind of operations

executeQuery() This is used generally for reading the content of the database. The output will be in the form of ResultSet. Generally SELECT statement is used.

executeUpdate() This is generally used for altering the databases. Generally DROP TABLE or DATABASE, INSERT into TABLE, UPDATE TABLE, DELETE from TABLE statements will be used in this. The output will be in the form of int. This int value denotes the number of rows affected by the query.

execute() If you dont know which method to be used for executing SQL statements, this method can be used. This will return a boolean. TRUE indicates the result is a ResultSet and FALSE indicates it has the int value which denotes number of rows affected by the query.

How to Load CSV file into Database

Deutsch: Logo der Christlich Sozialen Volkspartei

Loading CSV file into Database can be cumbersome task if your Database provider does not offer an out of box feature for this. Most of the time you’ll spend up in creating valid insert statements and putting up values escaping all special characters. Importing CSV files gets a bit complicated when you start doing things like importing files with description fields that can contain punctuation (such as commas or single-double quotation marks).

So here’s a simple Java Utility class that can be used to load CSV file into Database. Note how we used some of the best practices for loading data. The CSV file is parsed line by line and SQL insert query is created. The values in query are binded and query is added to SQL batch. Each batch is executed when a limit is reached (in this case 1000 queries per batch).

Import CSV into Database example

Let’s us check an example. Below is the sample CSV file that I want to upload in database table Customer.

employee.csv – Sample CSV file:


The Table customer contains few fields. We added fields of different types like VARCHAR, DATE, NUMBER to check our load method works properly.

Table: Customer – Database table


Following is a sample Java class that will use CSVLoader utility class (we will come to this shortly). – Load sample.csv to database

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
    private static String JDBC_CONNECTION_URL =
    public static void main(String[] args) {
        try {
            CSVLoader loader = new CSVLoader(getCon());
            loader.loadCSV("C:\\employee.sql", "CUSTOMER", true);
        } catch (Exception e) {
    private static Connection getCon() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(JDBC_CONNECTION_URL);
        } catch (ClassNotFoundException e) {
        } catch (SQLException e) {
        return connection;

In above Main class, we created an object of class CSVLoader using parameterized constructor and passed java.sql.Connection object.

Then we called the loadCSV method with three arguments. First the path of CSV file, second the table name where data needs to be loaded and third boolean parameter which decides whether table has to be truncated before inserting new records.

Execute this Java class and you’ll see the records getting inserted in table.


The CSV is successfully loaded in database.

Let’s check the Utility class now. I strongly recommend you to go through below tutorials as the Utility class combines the idea from these tutorials.

  1. Batch Insert In Java – JDBC
  2. Read / Write CSV file in Java
  3. Check if String is valid Date in Java

The utility class uses OpenCSV library to load and parse CSV file. Then it uses the idea of Batching in JDBC to batch insert queries and execute them. Each CSV value is checked if it is valid date before inserting. – Utility class to load CSV into Database

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
 * @author
public class CSVLoader {
    private static final
        String SQL_INSERT = "INSERT INTO ${table}(${keys}) VALUES(${values})";
    private static final String TABLE_REGEX = "\\$\\{table\\}";
    private static final String KEYS_REGEX = "\\$\\{keys\\}";
    private static final String VALUES_REGEX = "\\$\\{values\\}";
    private Connection connection;
    private char seprator;
     * Public constructor to build CSVLoader object with
     * Connection details. The connection is closed on success
     * or failure.
     * @param connection
    public CSVLoader(Connection connection) {
        this.connection = connection;
        //Set default separator
        this.seprator = ',';
     * Parse CSV file using OpenCSV library and load in
     * given database table.
     * @param csvFile Input CSV file
     * @param tableName Database table name to import data
     * @param truncateBeforeLoad Truncate the table before inserting
     *          new records.
     * @throws Exception
    public void loadCSV(String csvFile, String tableName,
            boolean truncateBeforeLoad) throws Exception {
        CSVReader csvReader = null;
        if(null == this.connection) {
            throw new Exception("Not a valid connection.");
        try {
            csvReader = new CSVReader(new FileReader(csvFile), this.seprator);
        } catch (Exception e) {
            throw new Exception("Error occured while executing file. "
                    + e.getMessage());
        String[] headerRow = csvReader.readNext();
        if (null == headerRow) {
            throw new FileNotFoundException(
                    "No columns defined in given CSV file." +
                    "Please check the CSV file format.");
        String questionmarks = StringUtils.repeat("?,", headerRow.length);
        questionmarks = (String) questionmarks.subSequence(0, questionmarks
                .length() - 1);
        String query = SQL_INSERT.replaceFirst(TABLE_REGEX, tableName);
        query = query
                .replaceFirst(KEYS_REGEX, StringUtils.join(headerRow, ","));
        query = query.replaceFirst(VALUES_REGEX, questionmarks);
        System.out.println("Query: " + query);
        String[] nextLine;
        Connection con = null;
        PreparedStatement ps = null;
        try {
            con = this.connection;
            ps = con.prepareStatement(query);
            if(truncateBeforeLoad) {
                //delete data from table before loading csv
                con.createStatement().execute("DELETE FROM " + tableName);
            final int batchSize = 1000;
            int count = 0;
            Date date = null;
            while ((nextLine = csvReader.readNext()) != null) {
                if (null != nextLine) {
                    int index = 1;
                    for (String string : nextLine) {
                        date = DateUtil.convertToDate(string);
                        if (null != date) {
                            ps.setDate(index++, new java.sql.Date(date
                        } else {
                            ps.setString(index++, string);
                if (++count % batchSize == 0) {
            ps.executeBatch(); // insert remaining records
        } catch (Exception e) {
            throw new Exception(
                    "Error occured while loading data from file to database."
                            + e.getMessage());
        } finally {
            if (null != ps)
            if (null != con)
    public char getSeprator() {
        return seprator;
    public void setSeprator(char seprator) {
        this.seprator = seprator;

The class looks complicated but it is simple :)

The loadCSV methods combines the idea from above three tutorials and create insert queries.

Following is the usage of this class if you want to use it in your project:


CSVLoader loader = new CSVLoader(connection);
loader.loadCSV("C:\\employee.csv", "TABLE_NAME", true);

Load file with semicolon as delimeter:

CSVLoader loader = new CSVLoader(connection);
loader.loadCSV("C:\\employee.csv", "TABLE_NAME", true);

Load file without truncating the table:

CSVLoader loader = new CSVLoader(connection);
loader.loadCSV("C:\\employee.csv", "TABLE_NAME", false);

Hope this helps.

Download Source Code (2.05 MB)

Learning Assembly language

Die Rotationsbefehle. Der Ausgangszustand ist ...

Programming is an art.

There are plenty of compilers around to program.The famous C,the beautiful Java,the useful HTML,the elusive oracle and the simple .net…

So why assembly language????

Those of you who ever had a go at cracking and all other stuff will have a readymade answer to it.No cracking without a crack at assembly language.

If u are not in the cracking Biz why do you need it?

No programmer is complete without mastery over assembly language..your program ruins slow or there is some deep work on it day and night and still the glitch remains a comes the assembly language.You analyse the processes and come at a diagnosis…

Assembly language makes you is the base on which everything is built.

Without assembly language you will always remain a novice.whatever you build or achieve.

So lets start the learning process.

You must have heard that the—-

Assembly language is hard to learn and understand

Its difficult to debug

It’s a messy outfit

Why do you want to save a little space using assembly language when you have so much space?

Believe Me, learning assembly language is easier than most high level languages..

Once you learn assembly language everything else comes naturally..

Assembly language has several benefits:

• Speed. Assembly language programs are generally the fastest programs around.

• Space. Assembly language programs are often the smallest.

• Capability. You can do things in assembly which are difficult or impossible in HLLs.

• Knowledge. Your knowledge of assembly language will help you write better programs,

even when using HLLs.