Wednesday, August 17, 2011

A Simple Read/Write Example using Cassandra and Java


In this post, we take a look at basic CRUD (Create Read Update Delete) operations on Cassandra database using Java JDBC.

We only use Eclipse IDE. This example was tested in Windows 7 Operating System.

To find out more about NoSQL databases, look here.

Cassandra is an open source distributed database management system developed by Apache Software Foundation. It was designed to handle very large amounts of data spread out across many commodity servers while providing a highly available service with no single point of failure.
Popular user of Cassandra is Facebook

To find out more on Cassandra, refer its home site here.

  • Download and Install Cassandra from here.
  • Extract the files.
  • Setup the following Environment Variables.
    • JAVA_HOME (Give the link to the jre folder where java is installed)
    • CASSANDRA_HOME (Give the link to the cassandra folder where the files are extracted)
  • Go to the location where you extracted and then into the "!/apache-cassandra-0.6.6/bin" folder and open 'cassandra-cli.bat' file using any text editor
  • Replace Line 21 "if NOT DEFINED CASSANDRA_HOME set CASSANDRA_HOME=%CD%" with "if NOT DEFINED CASSANDRA_HOME set CASSANDRA_HOME=%~dp0.."
    Now save the file after editing the line.
  • Now open the command prompt and goto "~/apache-cassandra-0.6.6/bin>" folder and type the following command '.\cassandra.bat'. This starts the server.
  • Now open another command prompt and goto "~/apache-cassandra-0.6.6/bin>" folder and run '.\cassandra-cli.bat'. This is the UI for the database
  • Connect to the server by typing the command 'connect localhost/9160'.
  • Here, type "Create Keyspace AuthDB ;" This creates a cluster (i.e., database)
  • Here, type "Create Column Family AuthCollection ;" This creates a column family (i.e., table)
  • There are certain jar files needed which are available in the Project Dump which is available for download below. It is present in the folder titled 'JarFiles' in the Project Directory.
  • Be sure to add these jar files to the class path.


The code which performs all the CRUD operations is as follows.


package com.examples.cassandra;

import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.beans.ColumnSlice;
import me.prettyprint.hector.api.beans.Rows;
import me.prettyprint.hector.api.factory.HFactory;
import me.prettyprint.hector.api.mutation.Mutator;
import me.prettyprint.hector.api.query.MultigetSliceQuery;
import me.prettyprint.hector.api.query.QueryResult;
import me.prettyprint.hector.api.query.SliceQuery;

public class CassandraExample {

	//The string serializer translates the byte[] to and from String using utf-8 encoding
    private static StringSerializer stringSerializer = StringSerializer.get();
	
    public static void insertData() {
    	try {
     		//Create a cluster object from your existing Cassandra cluster
            Cluster cluster = HFactory.getOrCreateCluster("Test Cluster", "localhost:9160");
           
            //Create a keyspace object from the existing keyspace we created using CLI
            Keyspace keyspace = HFactory.createKeyspace("AuthDB", cluster);
           
            //Create a mutator object for this keyspace using utf-8 encoding
            Mutator<string> mutator = HFactory.createMutator(keyspace, stringSerializer);
    		
            //Use the mutator object to insert a column and value pair to an existing key
            mutator.insert("sample", "authCollection", HFactory.createStringColumn("username", "admin"));
            mutator.insert("sample", "authCollection", HFactory.createStringColumn("password", "admin"));
           
            System.out.println("Data Inserted");
            System.out.println();
    	} catch (Exception ex) {
    		System.out.println("Error encountered while inserting data!!");
    		ex.printStackTrace() ;
    	}
    }
   
    public static void retrieveData() {
    	try {
    		//Create a cluster object from your existing Cassandra cluster
            Cluster cluster = HFactory.getOrCreateCluster("Test Cluster", "localhost:9160");
           
            //Create a keyspace object from the existing keyspace we created using CLI
            Keyspace keyspace = HFactory.createKeyspace("AuthDB", cluster);
    		SliceQuery<String, String, String> sliceQuery = HFactory.createSliceQuery(keyspace, stringSerializer, stringSerializer, stringSerializer);
            sliceQuery.setColumnFamily("authCollection").setKey("sample");
            sliceQuery.setRange("", "", false, 4);
           
            QueryResult<ColumnSlice<String, String>> result = sliceQuery.execute();
            System.out.println("\nInserted data is as follows:\n" + result.get());
    		System.out.println();
    	} catch (Exception ex) {
    		System.out.println("Error encountered while retrieving data!!");
    		ex.printStackTrace() ;
    	}
    }
   
    public static void updateData() {
    	try {

    		//Create a cluster object from your existing Cassandra cluster
            Cluster cluster = HFactory.getOrCreateCluster("Test Sample", "localhost:9160");
           
            //Create a keyspace object from the existing keyspace we created using CLI
            Keyspace keyspace = HFactory.createKeyspace("AuthDB", cluster);
           
          //Create a mutator object for this keyspace using utf-8 encoding
            Mutator<string> mutator = HFactory.createMutator(keyspace, stringSerializer);
           
            //Use the mutator object to update a column and value pair to an existing key
            mutator.insert("sample", "authCollection", HFactory.createStringColumn("username", "administrator"));
           
            //Check if data is updated
            MultigetSliceQuery<String, String, String> multigetSliceQuery = HFactory.createMultigetSliceQuery(keyspace, stringSerializer, stringSerializer, stringSerializer);
            multigetSliceQuery.setColumnFamily("authCollection");
            multigetSliceQuery.setKeys("sample");
       
            //The 3rd parameter returns the columns in reverse order if true
            //The 4th parameter in setRange determines the maximum number of columns returned per key
            multigetSliceQuery.setRange("username", "", false, 1);
            QueryResult<Rows<String, String, String>> result = multigetSliceQuery.execute();
            System.out.println("Updated data..." +result.get());
    		
    	} catch (Exception ex) {
    		System.out.println("Error encountered while updating data!!");
    		ex.printStackTrace() ;
    	}
    }

    public static void deleteData() {
    	try {
   
    		//Create a cluster object from your existing Cassandra cluster
    	       Cluster cluster = HFactory.getOrCreateCluster("Test Cluster", "localhost:9160");
    	      
    	       //Create a keyspace object from the existing keyspace we created using CLI
    	       Keyspace keyspace = HFactory.createKeyspace("AuthDB", cluster);
    	      
    	     //Create a mutator object for this keyspace using utf-8 encoding
    	       Mutator<string> mutator = HFactory.createMutator(keyspace, stringSerializer);
    	      
    	       //Use the mutator object to delete row
    	       mutator.delete("sample", "authCollection",null, stringSerializer);
    	      
    	       System.out.println("Data Deleted!!");
    	      
    	       //try to retrieve data after deleting
    	       SliceQuery<String, String, String> sliceQuery = HFactory.createSliceQuery(keyspace, stringSerializer, stringSerializer, stringSerializer);
    	       sliceQuery.setColumnFamily("authCollection").setKey("sample");
    	       sliceQuery.setRange("", "", false, 4);
    	      
    	       QueryResult<ColumnSlice<String, String>> result = sliceQuery.execute();
    	       System.out.println("\nTrying to Retrieve data after deleting the key 'sample':\n" + result.get());
    	      
    	       //close connection
    	       cluster.getConnectionManager().shutdown();
   
		} catch (Exception ex) {
			System.out.println("Error encountered while deleting data!!");
			ex.printStackTrace() ;
		}
	}
   
   
	public static void main(String[] args) {
		
		insertData() ;
		retrieveData() ;
		updateData() ;
		deleteData() ;
       
	}
}
</pre>


The screen shot of the output is as follows:


This code is available for download along with the entire project directory here.

Sunday, August 14, 2011

Error: InvalidRequestException in Cassandra

I have encountered two different kinds of InvalidRequestExceptions while i was working with Cassandra database and Java and I could not find help online.
Fortunately, I could resolve these myself. They are:
  1. InvalidRequestException(why:unconfigured columnfamily sample)
This Exception is encountered if the given column family name is not created in the database. The column family means table in relational database. There are two ways to solve this problem.
  • In java code, you can change the name of the column family to the one existing in the database.
Eg:  If the code is like this,
                 mutator.insert("sample", "auth", HFactory.createStringColumn("username", "admin"));
Change the column family name sample to the one present in the database i.e., if the column family name is login then it should be,
                mutator.insert("login", "auth", HFactory.createStringColumn("username", "admin"));
  •  Create a column family name in the database as follows,
Eg: create column family login ;

  1. InvalidRequestException(why:Keyspace Sample does not exist)

This Exception is encountered if the given Keyspace name is not created in the database. The keyspace means database in relational database. There are two ways to solve this problem.
  • In java code, you can change the name of the Keyspace to the one existing in the database.
Eg:  If the code is like this,
                 Keyspace keyspace = HFactory.createKeyspace("Sample", cluster);
Change the column family name sample to the one present in the database i.e., if the Keyspace name is Login then it should be,
                Keyspace keyspace = HFactory.createKeyspace("Login", cluster);
  •  Create a keyspace in the database as follows,
Eg: create keyspace login ;









Monday, August 8, 2011

A Simple Read/Write Example using MongoDB and Java

In this post, we take a look at basic CRUD (Create Read Update Delete) operations on MongoDB using Java JDBC.

We only use Eclipse IDE.

To find out more about NoSQL databases, look here.

MongoDB is a scalable, high-performance open source, schema free, Document-oriented NoSQL database and is highly suitable for Web Applications.

To find out more on MongoDB, refer its home site here.


  • Download and Install MongoDB from here.
  • Extract the files.
  • Run the mongod.exe file present in the bin folder of the Mongodb folder to start the server.
  • If you want to open the UI for the database, run the mongo.exe file present in the bin folder.
  • You will be needing a mongo.jar file to connect Java to the MongoDB which can be downloaded from here.
  • This jar file is also available in the Project Dump which is available for download below. It is present in the folder titled 'JarFiles' in the Project Directory.
  • Be sure to add this jar file to the class path.


The code which performs all the CRUD operations is as follows.

package com.examples.mongodb;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo ;

public class MongoDBExample {

  public static void main(String[] args) {
  
   try {
    // Mongodb Database Setup
    Mongo m = new Mongo("localhost", 27017) ;
    DB db = m.getDB("authDB") ;
    DBCollection col = db.getCollection("authCollection") ;
  
    // Creating Data 
    // setup and insert data into the authDB database

    BasicDBObject doc = new BasicDBObject() ;
    doc.put("username", "admin") ;
    doc.put("password", "admin") ;
    System.out.println(doc);
    col.insert(doc) ;
   
    // 5 records  are inserted in the following 'for' loop
    for (int i = 0 ; i < 5 ; i++) {
     BasicDBObject data = new BasicDBObject() ;
     data.put("username", "user_" + i ) ;
     data.put("password", "pass_" + i ) ;
     System.out.println(data);
     col.insert(data) ;
     data.clear() ;
    }
    System.out.println("Data Inserted");
   
    // Retrieving Data 
    System.out.println("Data Retrieved");
    DBCursor cursor = col.find() ;
    while (cursor.hasNext()) {
     // The entire records in the collection is displayed here.
     System.out.println(cursor.next());
    }
    

    // Updating Data 
    BasicDBObject oldData = new BasicDBObject() ;   
    oldData.put("username", "admin") ;
    oldData.put("password", "admin") ;
   
    BasicDBObject newData = new BasicDBObject() ;
    newData.put("username", "administrator") ;
    newData.put("password", "administrator") ;
    col.update(oldData, newData) ;
    System.out.println("Data Updated");
   
    DBCursor cursor1 = col.find() ;
    while (cursor1.hasNext()) {
     // The updated record with other records present in the collection is displayed here.
     System.out.println(cursor1.next());
    }
   
    // Deleting Data 
    // This deletes the record where username equals user_5
    BasicDBObject delRecord = new BasicDBObject() ;
    delRecord.put("username", "user_5") ;
    col.remove(delRecord) ;
    System.out.println("Record Deleted") ;
   
    DBCursor cursor2 = col.find() ;
    while (cursor2.hasNext()) {
     // Here there is no record with username data equals user_5
     System.out.println(cursor2.next());
    }

    // Dropping or deleting entire database
    m.dropDatabase("authDB") ;
    System.out.println("Database deleted/dropped");
    DBCursor cursor3 = col.find() ;
    while (cursor3.hasNext()) {
     //Nothing is displayed here as the database is deleted
     System.out.println(cursor3.next());
    }
   } catch (Exception e) {
    // TODO: handle exception
    System.out.println(e.getMessage()) ;
    e.printStackTrace() ;
   }
  }
}


The screen shot of the output is as follows:



This code is available for download along with the entire project directory here.

Friday, June 3, 2011

JQuery Servlet Ajax application


In this post, I am demonstrating a simple ajax application using jquery and java servlets.

In this Sample Project, I am trying to suggest the names of the countries starting with A.

So, if we type more than two letters, than it suggests the names of the countries.

The following is the screenshot for the above application.



First we define a html file as follows:

<%--
    Document   : Sample
    Created on : Apr 23, 2011, 5:15:15 PM
    Author     : Sriram
--%>


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">


<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JQuery Example</title>
    </head>
    <body>
        <center>
            <h3>Ajax Example using JQuery and Servlets</h3>
        </center>
        <script type="text/javascript" src="jquery-1.5.1.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                alert("Thanks for visiting!");
                $(".name").keyup(function(){
                    $country = $("#name").val();
                    if ($country.length > 1) {
                        $.ajax({
                            url: 'SampleServlet',
                            type: "POST",
                            data: {country:$country },
                            error: function(){
                                alert("Data Error");
                            },
                            success: function (data){
                                $("#flag").html("Country Suggestion: " + data) ;
                            }
                        });
                    }
                });
            });
        </script>
        <form id="sampleform" >
            <center>
                Enter Country starting with A:  <input id="name" class="name" type="text" >  <br/><br/>
                <div id="flag"> </div>
                <br/><br/><br/>
                Type Atleast Two Letters *
            </center>
        </form>
    </body>
</html>

The above program needs "jquery-1.5.1.js" file which is a JQuery library.

Save this file as .js file. This library should be placed in the same location where the jsp page is present.

This jsp program is calling SampleServlet Program as follows:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Sriram
 */
public class SampleServlet extends HttpServlet {
  
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet SampleServlet</title>"); 
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet SampleServlet at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
            */
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String name = request.getParameter("name") ;
        System.out.println(name);
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.println("Hello " + name);
        }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String name = request.getParameter("country") ;
        System.out.println(name);
        String result = this.countryList(name) ;
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.println(result);
    }

    public String countryList(String name) {
        String country[] = new String[5] ;
        country[0] = "America" ;
        country[1] = "Australia" ;
        country[2] = "Argentina" ;
        country[3] = "Africa" ;
        country[4] = "Antartica" ;

        int flag = name.length() ;
        for (int i = 0 ; i < country.length ; i++) {
            if (country[i].substring(0, flag).equalsIgnoreCase(name)) {
                return country[i] ;
            }
        }
        return "Country Not Available in List!!" ;
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}





The web.xml configuration for the SampleServlet program is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>SampleServlet</servlet-name>
        <servlet-class>SampleServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SampleServlet</servlet-name>
        <url-pattern>/SampleServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>


The jsp program atleast two let as parameter and sends it to POST method in SimpleServlet using ajax. There is a callback function which displays the output in an alert box and ultimatly in the jsp page.


There Source code is given as follows. It consists of a war file. Place this war file in the webapps folder of your server and paste http://localhost:8080/Sample/Sample.jsp in the url of the browser.

Simple JQuery-Servlet Application

Name the project as Sample.The jsp program here calls the GET method.


In this post, I am demonstrating a simple jquery application using jquery and java servlets.

<%--
    Document   : Sample
    Created on : Apr 23, 2011, 5:15:15 PM
    Author     : Sriram
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JQuery Example</title>
    </head>
    <body>
        <center>
            <h3>Getter Example using Servlets</h3>
        </center>
        <script type="text/javascript" src="jquery-1.5.1.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                alert("Thanks for visiting!");
        $(".Submit").click(function(){
                    $name=$("#name").val();
                    alert($name) ;
                    $.get("SampleServlet", {name:$name}, function(data) {
                        alert(data) ;
                        $("#flag").html(data) ;
                    });
        });
            });
        </script>
        <form id="sampleform" method="POST">
            <center>
                Enter your Name:  <input id="name" class="name" type="text">  <br/><br/>
                <input class="Submit" name="Submit" type="button" value="Submit" id="Submit">
            </center>
        </form>
        <div id="flag"> </div>
    </body>
</html>

 
** The above program needs "jquery-1.5.1.js" file which is a JQuery library.
Save this file as .js file. This library should be placed in the same location where the jsp page is present.

This jsp program is calling SampleServlet Program as follows:
 
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Sriram
 */
public class SampleServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and 
        <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, 
                 HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet SampleServlet</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println
                ("<h1>Servlet SampleServlet at " + 
                      request.getContextPath()+ "</h1>");
            out.println("</body>");
            out.println("</html>");
            */
        } finally { 
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. 
    Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, 
          HttpServletResponse response)
    throws ServletException, IOException {
        String name = request.getParameter("name") ;
        System.out.println(name);
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.println("Hello " + name);
        }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, 
               HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}


The web.xml configuration for the SampleServlet program is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>SampleServlet</servlet-name>
        <servlet-class>SampleServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SampleServlet</servlet-name>
        <url-pattern>/SampleServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
 
The jsp program takes a name as parameter and sends it to GET method in SimpleServlet using ajax. There is a callback function which displays the output in an alert box and ultimatly in the jsp page.
There Source code is given as follows. It consists of a war file. Place this war file in the webapps 
folder of your server and paste  http://localhost:8080/Sample/Sample.jsp 
in the  url of the browser.

Download Source Code
 
 

Wednesday, March 23, 2011

Error E212: Can't open or save file

If you are getting an error E212 in Linux while saving data in vi editor,

1. Go to the root mode: su -
2. Type the following: chown <username>:<username> /<directory_location>

Thursday, February 3, 2011

Data Input using String (Java)

In the following example, the data is taken as input using Strings.


import java.io.* ;

public class DataInput {

public static void main(String args[]) {

try {
String data ; //declare the variable as per your choice of datatype
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter your name: ");
data = br.readLine();
System.out.println("Hello " + data);
} catch (IOException e) {
e.printStackTrace() ;
}

}

}

The output for the above program is as follows:
Enter your name: abc
Hello abc

Break and Continue Statements Examples (Java)

While using 'break' and 'continue' statements, each of them are classified into two types.

1. Unlabelled Statements
In Unlabelled statements, both the keywords (break and continue) are used directly.


A 'break' statement (unlabeled) will exit out of the innermost loop construct and proceed with the next line of code after the loop.

A 'continue' statement (unlabeled) will exit this iteration and proceeds with the next iteration, but NOT the whole loop.


2. Labelled Statements

A Label is commonly used with loop statements like for or while. However, in conjunction with break and continue statements, a label statement must be placed just before the statement being labeled, and it consists of a valid identifier that ends with a colon (:).



A 'break' statement (labeled) will exit out of the LABEL and proceed with the next line of code after the loop.

A 'continue' statement (labeled) will exit this iteration and proceeds with the next iteration, but NOT the whole LABEL.

The difference between labeled and unlabeled 'break' and 'continue'  is shown in the following Java example.

import java.io.* ;

public class Demo {

public static void main (String a[]) {

System.out.println() ;
System.out.println("1. Unlabeled Statements ") ;
System.out.println() ;
System.out.println("1.1 'Break' Command Demo ") ;
for (int i = 1 ; i <= 3 ; i++)  {
if (i == 3) {
break ;
} else {
System.out.println(" i = " +i) ;
}
}
System.out.println() ;

System.out.println("1.2 'Continue' Command Demo ") ;
for (int i = 1 ; i <= 5 ; i++)  {
if (i == 3) {
continue ;
} else {
System.out.println(" i = " +i) ;
}
}

System.out.println() ;
System.out.println("2. Labeled Statements") ;
System.out.println() ;
System.out.println("2.1 'Break' Command Demo ") ;
System.out.println("Beginning of foo 1 label") ;
foo1: // Declaring a label foo 1
for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {
System.out.println("i=" +i + " j="+j);
if ( j == 3 )
break foo1;
} // end of inner loop
System.out.println("End of for loop"); // Never prints
}
System.out.println("End of foo 1 label") ;

System.out.println( ) ;
System.out.println("2.2 'Continue' Command Demo ") ;
System.out.println("Beginning of foo 2 label") ;
foo2: // Declaring a label foo 2
for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {
System.out.println("i=" +i + " j="+j);
continue foo2;
} // end of inner loop
System.out.println("End of for loop"); // Never prints
}
System.out.println("End of foo 2 label") ;
}
}

The Output for the program is as follows:

1. Unlabeled Statements

1.1 'Break' Command Demo
 i = 1
 i = 2

1.2 'Continue' Command Demo
 i = 1
 i = 2
 i = 4
 i = 5

2. Labeled Statements

2.1 'Break' Command Demo
Beginning of foo 1 label
i=0 j=0
i=0 j=1
i=0 j=2
i=0 j=3
End of foo 1 label

2.2 'Continue' Command Demo
Beginning of foo 2 label
i=0 j=0
i=1 j=0
i=2 j=0
i=3 j=0
i=4 j=0
End of foo 2 label