JAVA N WEB TECH SYLLABUS

Thursday, November 17, 2011

Program to search a book for a title given by the user on a web page and display the search results with proper headings.


book.html
<html>
    <body>
    Enter the Book isbn to search
    <br>
    <form action="http://192.168.8.3/naveen/book.php" method="get">
    ISBN:<input type="text" name="bisbn">
       <input type="submit" >
    <input type="reset">
    </form>
    </body>
    </html>




book.php


<?
                $isbn=$_GET["bisbn"];
                $query1="Select * from book where ano like '$isbn'";
                echo "$query1";
                
                
                // connect to the mysql server on localhost 
                $mysql = mysql_connect("localhost", "naveen", "a") 
                    or die("could not connect to mysql"); 

                    
                // execute the MySQL query, grab the result in $result 
                $result = mysql_db_query("naveen", $query1) 
                    or die("query failed  ");
                    

            ?> 
            <html> 
            <head> 
            <title>PHP and MySQL</title> 
            </head> 
            <body bgcolor="CYAN"> 
            <H1>THE SEARCH RESULT IS DISPLAYED BELOW</H1><BR> 
            <hr> 
            We found <b> <?echo mysql_num_rows($result); ?></b> rows. 

            <h3>Query result</h3> 
            <br>
            <table border=2>
            <tr>
                
                <td>ISBN</td>
                <td>TITLE</td>
<td>AUTHOR</td>
                <td>EDITION</td>
<td>PUBLICATION</td>



                
            </tr>

                
             <?
                //loop through each row 
                while ($array = mysql_fetch_row($result)) 
                { 
                    echo "<tr>";

                    echo "<td>$array[0]</td>";
                    echo "<td>$array[1]</td>";
echo "<td>$array[0]</td>";
                    echo "<td>$array[1]</td>";
  echo "<td>$array[1]</td>";



                    
                echo "</tr>";
             
                } 
            ?> 
            </table>
            </body> 
            </html> 
             <?
                // we are all done, so close the MySQL connection 
                mysql_close($mysql); 
            ?> 

Thursday, January 13, 2011

Seesion in servlets

HTTP is a stateless protocol. Each request is independent of the previous one. However,
in some applications, it is necessary to save state information so that information can
be collected from several interactions between a browser and a server. Sessions provide
such a mechanism.

A session can be created via the getSession( ) method of HttpServletRequest. An
HttpSession object is returned. This object can store a set of bindings that associate
names with objects. The setAttribute( ), getAttribute( ), getAttributeNames( ), and
removeAttribute( ) methods of HttpSession manage these bindings. It is important
to note that session state is shared among all the servlets that are associated with a
particular client.
The following servlet illustrates how to use session state. The getSession( ) method
gets the current session. A new session is created if one does not already exist. The
getAttribute( ) method is called to obtain the object that is bound to the name “date”.
That object is a Date object that encapsulates the date and time when this page was last
accessed. (Of course, there is no such binding when the page is first accessed.) A Date
object encapsulating the current date and time is then created. The setAttribute( )
method is called to bind the name “date” to this object.


removeAttribute( ) methods of HttpSession manage these bindings. It is important
to note that session state is shared among all the servlets that are associated with a
particular client.
The following servlet illustrates how to use session state. The getSession( ) method
gets the current session. A new session is created if one does not already exist. The
getAttribute( ) method is called to obtain the object that is bound to the name “date”.
That object is a Date object that encapsulates the date and time when this page was last
accessed. (Of course, there is no such binding when the page is first accessed.) A Date
object encapsulating the current date and time is then created. The setAttribute( )
method is called to bind the name “date” to this object.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get the HttpSession object.
HttpSession hs = request.getSession(true);
// Get writer.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
// Display date/time of last access.
Date date = (Date)hs.getAttribute("date");
if(date != null) {
pw.print("Last access: " + date + "<br>");
}
// Display current date/time.
date = new Date();
hs.setAttribute("date", date);
pw.println("Current date: " + date);
}
}

When you first request this servlet, the browser displays one line with the current
date and time information. On subsequent invocations, two lines are displayed. The
first line shows the date and time when the servlet was last accessed. The second line
shows the current date and time.

Wednesday, January 5, 2011

Program to request server information viz. Request Method, URL, Protocol and Remote address usin Servlet

Servlet File
ServerInfo.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServerInfo extends HttpServlet
{
    public void doGet(HttpServletRequest request,HttpServletResponse response)
    throws ServletException,IOException
    {
        response.setContentType("text/html");
        PrintWriter pw=response.getWriter();
        pw.println("protocol"+request.getProtocol());
        pw.println("<br>remote address"+request.getRemoteAddr());
        pw.println("<br>URI"+request.getRequestURI());
        pw.println("<br>remote address"+request.getMethod());
        pw.close();
    }
}

Program to create and display a cookie usin servlet

Html File
Cookie.html

 <html>
<head><title>COOKIE INFORMATION</title></head>
<body><form method="Get" action="http://192.168.8.3:8080/servlet/MyCookie">
<input type="text" name="txtcookie">
<input type="submit">
</form>
</body>
</html>

Servlet File
MyCookie.java






import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyCookie extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
String daa=req.getParameter("txtcookie");
Cookie coo=new Cookie("naveen",daa);
res.addCookie(coo);
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("<B>mycookie has been set to");
pw.println(daa);
pw.close();
}
}

Program to change the background color of the page on the color selected by the user usin servlet.

Html File
Colour.html

<html><body bgcolor="blue">
<form action="http://192.168.8.3:8080/servlet/Colour">
<select name="color" size="3">
<option value="red">Red</option>
<option value="magenta">Magenta</option>
</select>
<input type="Submit" value="Submit">
</form>
</body>
</html>

Servlet File
Colour.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Colour extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
String col=req.getParameter("color");
PrintWriter out=res.getWriter();
res.setContentType("text/html");
out.println("<html><body bgcolor=" +col+">");
out.println("<b>SELECTED COLOR IS</b>");
out.println("<b>"+col+"</b>");
out.println("</body></html>");
out.close();
}
}

Program to accept user name and display a greeting message using servlet

Html file 
Name.html
<html>
<body bgcolor="blue">
<form action="http://192.168.8.3:8080/servlet/Greeting " method="get">
<input type="text" name="uname">
<input type="Submit" value="Submit">
<input type="Reset" value="Reset"></form>
</body>
</html>

Servlet File
Greeting.java



import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Greeting extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
String username=req.getParameter("uname");
PrintWriter out=res.getWriter();
res.setContentType("text/html");
out.println("Welcome"+username);
out.close();
}
}

Thursday, December 23, 2010

Program to insert new name and age information entered by the user into the database.

cust.html


    <html>

    <body>
    Enter the Customer details to add a  record in Customer table
    <br>
    <form action="http://192.168.8.3/naveen/cust.php" method="get">
    Name:<input type="text" name="uname">
    Age:<input type="text" name="uage">
    <input type="submit" >
    <input type="reset">
    </form>

    
    </body>
    </html>


output:
-----------------------------------------------------------------------------------------------------------------------------------
Enter the Customer details to add a record in Customer table

Name: Age:
-------------------------------------------------------------------------------------------------------------
cust.php


             <?
                $name=$_GET["uname"];
                $age=$_GET["uage"];
                $query1="Insert into customer values('$name',$age)";
                echo "$query1";
                
                
                // connect to the mysql server on localhost 
                $mysql = mysql_connect("192.168.8.3", "naveen", "a") 
                    or die("could not connect to mysql"); 

                    
                // execute the MySQL query, grab the result in $result 
                $result1 = mysql_db_query("naveen", $query1) 
                    or die("query failed  ");
                    $query2="select * from customer";
                echo "$query2";
                $result = mysql_db_query("studentinfo", $query2) 
                    or die("query failed  ");
                

            ?> 
            <html> 
            <head> 
            <title>PHP and MySQL</title> 
            </head> 
            <body bgcolor="CYAN"> 
            We Added the Record: 
            <hr> 
            We found <b> <?echo mysql_num_rows($result); ?></b> rows. 

            <h3>Query result</h3> 
            <br>
            <table border=2>
            <tr>
                
                <td>NAME</td>
                <td>AGE</td>
                
            </tr>

                
             <?
                //loop through each row 
                while ($array = mysql_fetch_row($result)) 
                { 
                    echo "<tr>";

                    echo "<td>$array[0]</td>";
                    echo "<td>$array[1]</td>";
                    
                echo "</tr>";
             
                } 
            ?> 
            </table>
            </body> 
            </html> 
             <?
                // we are all done, so close the MySQL connection 
                mysql_close($mysql); 
            ?> 
-------------------------------------------------------------------------------------------------------------
OUTPUT:
Insert into customer values('naveen11',27)   
We Added the Record:
We found rows.

Query result select * from customer


NAME AGE
jhonny 22
bravo 22
naveen 27
xyz 27
abc27

Program to display the current contents of the table in a database.

display.php   

    <?
        // connect to the mysql server on localhost
        $mysql = mysql_connect("192.168.8.3", "naveen", "a")
            or die("could not connect to mysql");

        // execute the MySQL query, grab the result in $result
        $result = mysql_db_query("naveen", "SELECT * FROM student")
            or die("query failed  ");

    ?>
    <html>
    <head>
    <title>PHP and MySQL</title>
    </head>
    <body bgcolor="CYAN">
    We executed: <b> SELECT * FROM student</b>
    <hr>
    We found <b><?echo mysql_num_rows($result); ?></b> rows.

    <h3>Query result</h3>
    <br>
    <table border=2>
    <tr>
   <td>USN</td>
   <td>NAME</td>
   <td>BRANCH</td>
   <td>SEM</td>
   <td>CGPA</td>
    </tr>

 
    <?
        //loop through each row
        while ($array = mysql_fetch_row($result))
   {
            echo "<tr>";

   echo "<td>$array[0]</td>";
   echo "<td>$array[1]</td>";
   echo "<td>$array[2]</td>";
   echo "<td>$array[3]</td>";
   echo "<td>$array[4]</td>";
   echo "</tr>";
    
   }
    ?>
    </table>
    </body>
    </html>
    <?
        // we are all done, so close the MySQL connection
        mysql_close($mysql);
    ?>
OUT PUT:
We executed: SELECT * FROM student
We found 7 rows.

Query result


USN NAME BRANCH SEM CGPA
2sd02is006 jhon cse 7 8.75
2sd02is007 jackie ec 5 7.75
2sd02is008 tom ee 5 6.75
2sd02is008 jerry ise 7 7.77
2sd02is015 ford ise 5 5.55
ytyutyu ee ee 2 5.55
2sd05is099 nnnnn ise 7 9.99

Program to keep track of the number of visitors, visited the web page and display the counter with proper headings.

count.html
<html>
<body>
To know the no of times the web page Count.php is viewed <a href="http://192.168.8.3/naveen/count.php">Click Here</a>
</body>
</html>

count.php

<?

$filename = 'c.txt';

if (file_exists($filename))
    {
        $count = file('c.txt'); //read all the lines from the file c.txt and store it in array
        $count[0] ++;//increment the first line
        $fp = fopen("c.txt", "w"); //open c.txt in write mode
        fputs ($fp, "$count[0]"); //put the updated value in c.txt 
        fclose ($fp);
        echo "No of vistors vistin the pages is $count[0]";
    }
?>
Note:For this code u hav to create c.txt in u r webcontainer
go to u r web contain
cd /var/www/html/<usn>
vi c.txt
enter the value 0 and save it
change the permission of c.txt to 777
access the html to see the no of times the page is visited.

Program to accept UNIX command from a HTML form and display the output of the command executed.

cmd.html
<html>
<body>
Enter the valid Linux command :
<form action="http://192.168.8.3/naveen/cmd.php" method ="get">
<input type="text" name="cmd">
<input type="submit">
</form>
</body>
</html>

cmd.php

<html>
<body>
<? $cmd=$_GET["cmd"];?>
The output of the command <? echo "$cmd"; ?> is:
<br>
<? $s=system($cmd); 
echo "$s";
?>
</body>
</html>

Note : if we use exec($cmd) it will only print the last line of the output command so its better to use
system($cmd); which will print all the lines of the output of the command.

A Simple PHP

<html>
<body>
<?
echo "Welcome To My First PHP Page"<br>";

$name="naveen";
$sem=7;
$cgpa=7.77;
$cgpa2=$cgpa*10;
echo $name;
echo "<br>";
echo $sem;
echo "<br>";
echo $cgpa;
echo "<br>";
echo $cgpa2;


?>
</body>
</html>

Wednesday, December 22, 2010

JDBC ResultSet MetaData

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

public class MyResultSetMetaData {
    public static void main(String[] args) throws Exception {
        Connection conn = getHSQLConnection();
        Statement st = conn.createStatement();
      
      
        st = conn.createStatement();
        ResultSet rs = st.executeQuery("SELECT * FROM student");
      
        ResultSetMetaData rsMetaData = rs.getMetaData();
      
        int numberOfColumns = rsMetaData.getColumnCount();
        System.out.println("resultSet MetaData column Count=" + numberOfColumns);
      
        String TableName = rsMetaData.getTableName(1);
        System.out.println("resultSet MetaData TableName=" + TableName);
      
      
      
        String ColumnLabel = rsMetaData.getColumnLabel(1);
        System.out.println("resultSet MetaData column Label 1=" + ColumnLabel);
      
        String ColumnLabe2 = rsMetaData.getColumnLabel(2);
        System.out.println("resultSet MetaData column Label 2=" + ColumnLabe2);
      
      
        rs.close();
        st.close();
        conn.close();
    }
  
    private static Connection getHSQLConnection() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost/studentinfo";
        return DriverManager.getConnection(url, "root", "root");
    }
}
output


resultSet MetaData column Count=5
resultSet MetaData TableName=student
resultSet MetaData column Label 1=usn
resultSet MetaData column Label 2=name

JDBC Database MetaData

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;

public class Main {
    public static void main(String[] args) throws Exception {
        Connection conn = getConnection();
      
        DatabaseMetaData mtdt = conn.getMetaData();
        System.out.println("URL in use: " + mtdt.getURL());
        System.out.println("User name: " + mtdt.getUserName());
        System.out.println("DBMS name: " + mtdt.getDatabaseProductName());
        System.out.println("DBMS version: " + mtdt.getDatabaseProductVersion());
        System.out.println("Driver name: " + mtdt.getDriverName());
        System.out.println("Driver version: " + mtdt.getDriverVersion());
        System.out.println("supp. SQL Keywords: " + mtdt.getSQLKeywords());
      
      
        conn.close();
    }
  
    private static Connection getConnection() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost/studentinfo";
      
        return DriverManager.getConnection(url, "root", "root");
    }
}
output


URL in use: jdbc:mysql://localhost/studentinfo
User name: root@localhost
DBMS name: MySQL
DBMS version: 5.0.27-community-nt
Driver name: MySQL-AB JDBC Driver
Driver version: mysql-connector-java-5.0.5 ( $Date: 2007-03-01 00:01:06 +0100 (Thu, 01 Mar 2007) $, $Revision: 6329 $ )

Using Prepared Statement

In this code we r makin use of the PreparedStatement for displayin a particular student record from student table


import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
 * Display.java
 *
 * Created on December 14, 2010, 9:25 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/**
 *
 * @author Naveen
 */
public class Display {
  
    /** Creates a new instance of Display */
    public Display() {
    }
    public static void main(String args[]) {
        PreparedStatement pstmt=null;
        Connection conn = null;
        ResultSet rs=null;
      
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        String url="jdbc:mysql://localhost/studentinfo";
        String userName="root";
        String password="root";
        try {
          
            conn=DriverManager.getConnection(url,userName,password);
          
        }
      
        catch (SQLException ex) {
            System.out.println("Unable to Connect to Database");
        }
      
        try {
          
            String query="select * from student where cgpa=? and sem =?";
            pstmt=conn.prepareStatement(query);
          
            pstmt.setFloat(1,8.75f);
            pstmt.setInt(2,7);
            rs =pstmt.executeQuery();
            while(rs.next()) {
                System.out.print(rs.getString(1)+"\t");
                System.out.print(rs.getString(2)+"\t");
                System.out.print(rs.getString(3)+"\t");
              
                System.out.print(rs.getInt(4)+"\t");
                System.out.print(rs.getFloat(5)+"\t");
            }
          
          
        } catch (SQLException ex) {
            System.out.println("Unable to create Statment");
        }
      
      
      
      
      
    }
}

Displaying all the records from Student table

Here in this code we r displaying all the  student records from student table.In this example code we are makin use of jdbc driver type 4 provided by mysql.



import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
 * Display.java
 *
 * Created on December 14, 2010, 9:25 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */


/**
 *
 * @author Naveen
 */
public class Display2 {
    
    /** Creates a new instance of Display */
    public Display2() {
    }
    public static void main(String args[]) {
        
        Connection conn = null;
        ResultSet rs=null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        String url="jdbc:mysql://localhost/studentinfo";
        String userName="root";
        String password="root";
        try {
            
            conn=DriverManager.getConnection(url,userName,password);
            
        }
        
        catch (SQLException ex) {
            System.out.println("Unable to Connect to Database");
        }
        
        try {
            
            String query="Select * from student" ;
            stmt=conn.createStatement();
            
            
            rs= stmt.executeQuery(query);
            while(rs.next()) {
                System.out.print(rs.getString("usn")+"\t");
                System.out.print(rs.getString(2)+"\t");
                System.out.print(rs.getString(3)+"\t");
                
                System.out.print(rs.getInt(4)+"\t");
                System.out.println(rs.getFloat(5)+"\t");
            }
            
            
            
            
        } catch (SQLException ex) {
            System.out.println("Unable to create Statment");
        }
        
        
        
        
        
    }
}

The JDBC Process

Here in this code we r inserting a student record into a student table.In this example code we are makin use of jdbc driver type 4 provided by mysql.

import java.io.DataInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/*
 * DemoJdbc.java
 *
 * Created on December 13, 2010, 10:23 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/**
 *
 * @author Naveen
 */
public class DemoJdbc {
  
    /** Creates a new instance of DemoJdbc */
    public DemoJdbc() {
      
    }
    public static void main(String args[]) {
        DataInputStream din=new DataInputStream(System.in);
        Connection conn = null;
        Statement stmt = null;
      
        try {
            System.out.println("Enter the data usn,name,branch,sem,cgpa");
            String usn=din.readLine();
            String name=din.readLine();
            String branch=din.readLine();
            String sem=din.readLine();
            String cgpa=din.readLine();
            try {
              
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException ex) {
                System.out.println("Unable to Load Class");
            }
            String url="jdbc:mysql://localhost/studentinfo";
            String userName="root";
            String password="root";
            try {
              
                conn=DriverManager.getConnection(url,userName,password);
              
            }
          
            catch (SQLException ex) {
                System.out.println("Unable to Connect to Database");
            }
            try {
              
                stmt=conn.createStatement();
            } catch (SQLException ex) {
                System.out.println("Unable to create Statment");
            }
          
            boolean sucessful = false;
            try {
              
                String query="Insert into student values (" +
                        "'"+usn+"',"+
                        "'"+name+"',"+
                        "'"+branch+"',"+
                        sem+","+cgpa+")";
              
                System.out.println("\nQuery Framed=="+query);
                sucessful = stmt.execute(query);
                System.out.println("Query executed sucessfully");
              
              
            } catch (SQLException ex) {
                System.out.println("Query  not executed ");
            }
          
          
          
          
        } catch (IOException ex) {
            System.out.println("Unable to read data from keyboard");
        } finally {
            try {
                conn.close();
            } catch (SQLException ex) {
                System.out.println("Unable to close Connection");
            }
        }
      
      
    }
}

Tuesday, December 14, 2010

Difference between String s = "abc"; vs String s2 = new String("abc");

/*
 * NewMain.java
 *
 * Created on December 14, 2010, 11:43 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/**
 *
 * @author Naveen
 */
public class NewMain {
  
    /** Creates a new instance of NewMain */
    public NewMain() {
    }
  
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        String s1="abc";
        String s2="abc";
        String s3=new String("abc");


Naveen Mirajkar December 15 at 12:16am
/*
* NewMain.java
*
* Created on December 14, 2010, 11:43 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/

/**
*
* @author Naveen
*/
public class NewMain {

/** Creates a new instance of NewMain */
public NewMain() {
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String s1="abc";
String s2="abc";
/*
for these 2 above line in first for s1 runtime will create a new object and it is referenced by s1
4 nd line
already sequence of char "abc" is in mem pool at runtime so the java interpretor will not create a new object but to already exsisting object referred by s1 is assigned to s2
thats why when u use s1==s2 v use == wrt object to chech weather they are same or not wrt to memloc and their hashcode


in the line s3=new String("abc")
the runtime will create a new object in heap havin seq of chars "abc"

but
it has its own mem addr diff from s1 n s2
so if u use
s1==s3
it is false


but
s1.equals(s3)
is true coz v checkin the char seqncs in both the objs which r same

ok
i hope u got it..........*/




        String s4=s1;
        if(s1==s4) {
            System.out.println("Hi0");
        }
        if(s1.equals(s4)) {
            System.out.println("Hi00");
        }
      
        if(s1==s2) {
            System.out.println("Hi");
        }
        if(s1==s3) {
            System.out.println("Hello");
        }
        if(s1.equals(s2)) {
            System.out.println("Hi1");
        }
        if(s1.equals(s3)) {
            System.out.println("Hi2");
        }
      
      
      
        System.out.println(s1==s2); //true
        System.out.println(s1==s3); //false diff object identity
        System.out.println(s1.equals(s2)); //true
        System.out.println(s1.equals(s3)); //true
      
        System.out.println(System.identityHashCode(s1)); //they are
        System.out.println(System.identityHashCode(s2)); //the same object
        System.out.println(System.identityHashCode(s3)); //diff  object
      
      
      
    }
}
output

Hi0
Hi00
Hi
Hi1
Hi2
true
false
true
true
4072869
4072869
1671711



Thursday, November 18, 2010

Exception Handling In Java

Hi
In Java Exception Handling is managed by 5 key word,they are

  1. try
  2. catch
  3. finally
  4. throw
  5. throws  
Here i am posting a typical example code which will make use of these five keywords,in this example we are writing code for preparing Tea.
For preparing the tea we require the following Ingredients
  • TeaPowder
  • Milk
  • Sugar
If these things are not available at the preparation time we are throw Exception objects created from our Exception classes like
  • SugarException
  • TeaPowderException
  • MilkException. 
As we know to create our own exception classes we have to extend it from the Base Class Exception.
The code for this is shown below
import java.io.DataInputStream;
import java.io.IOException;
/*
 * MakeTea.java
 *
 * Created on November 16, 2010, 9:11 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/**
 *
 * @author NVAEEN S MIRAJKAR
 */

class SugarException extends Exception
{
    int errorCode;
    String info;
    public SugarException()
    {
        this.errorCode=100;
        this.info="No Sugar Exception";
    }
    public String getDetails()
    {
        return("Error Code="+this.errorCode+"\t"+this.info);
    }
}

class MilkException extends Exception
{
    int errorCode;
    String info;
    public MilkException()
    {
        this.errorCode=101;
        this.info="No Milk Exception";
    }
    public String getDetails()
    {
        return("Error Code="+this.errorCode+"\t"+this.info);
    }
}

class TeaPowderException extends Exception
{
    int errorCode;
    String info;
    public TeaPowderException()
    {
        this.errorCode=102;
        this.info="No Tea Powder Exception";
    }
    public String getDetails()
    {
        return("Error Code="+this.errorCode+"\t"+this.info);
    }
}
public class MakeTea {
    
    /** Creates a new instance of MakeTea */
    int milk;
    int teaPowder;
    int sugar;
    
    public MakeTea(int sugar,int teaPowder,int milk) throws SugarException,MilkException,TeaPowderException
    {
        if(milk==0)
        {
            MilkException mke=new MilkException();
            throw mke;
        }
        if(sugar==0)
        {
            
            throw new SugarException();
        }
        if(teaPowder==0)
        {
            TeaPowderException tpe=new TeaPowderException();
            throw tpe;
        }
        this.milk=milk;
        this.teaPowder=teaPowder;
        this.sugar=sugar;
        
    }
    public static void printScreen(String msg)
    {
        System.out.println(msg);
    }
    public static void main(String args[])
    {
        int sugar = 0;
        int milk = 0;
        int tpowder = 0;
        
        MakeTea.printScreen("To Prepare Tea First on the gas an lite the stove");
        try 
        {
            
            DataInputStream din=new DataInputStream(System.in);
            
            MakeTea.printScreen("Enter the quantity of Sugar");
            sugar=Integer.parseInt(din.readLine());
            
            MakeTea.printScreen("Enter the quantity of Tea Powder");
            tpowder=Integer.parseInt(din.readLine());
            
            MakeTea.printScreen("Enter the quantity of Milk");
            milk=Integer.parseInt(din.readLine());

            MakeTea.printScreen("The Quantities entered are \n"+
                    "Sugar="+sugar+
                    "\nTeapowder="+tpowder+
                    "\nMilk="+milk);
        
            
        } 
        catch (IOException ex) 
        {
           MakeTea.printScreen("Cannot read values from key board");
        }
        
        try 
        {
            
            MakeTea mkt=new MakeTea(sugar,tpowder,milk);
            MakeTea.printScreen("We have Sucessfullt prepared the Tea now enjoy......!");
        } 
        catch (SugarException ex) 
        {
            MakeTea.printScreen(ex.getDetails());
        } 
        catch (MilkException ex) 
        {
            MakeTea.printScreen(ex.getDetails());
        } 
        catch (TeaPowderException ex) 
        {
            MakeTea.printScreen(ex.getDetails());
        }
        finally
        {
            MakeTea.printScreen("Wether u are able to make tea or not OFF the Stove n GAS");
            MakeTea.printScreen("Gas n Stove Turned OFF");
        }
        
        
    }
    
}

Tuesday, November 9, 2010

Java Code for getting the current date and time

Here in this code we are making use of the classes
java.util.Calendar;
java.util.GregorianCalendar;

these classes are present inside the Util package

public class GregorianCalendar
extends Calendar
GregorianCalendar is a concrete subclass of Calendar and provides the standard calendar used by most of the world.
The standard (Gregorian) calendar has 2 eras, BC and AD.
This implementation handles a single discontinuity, which corresponds by default to the date the Gregorian calendar was instituted (October 15, 1582 in some countries, later in others). The cutover date may be changed by the caller by calling setGregorianChange().
Historically, in those countries which adopted the Gregorian calendar first, October 4, 1582 was thus followed by October 15, 1582. This calendar models this correctly. Before the Gregorian cutover, GregorianCalendar implements the Julian calendar. The only difference between the Gregorian and the Julian calendar is the leap year rule. The Julian calendar specifies leap years every four years, whereas the Gregorian calendar omits century years which are not divisible by 400.
GregorianCalendar implements proleptic Gregorian and Julian calendars. That is, dates are computed by extrapolating the current rules indefinitely far backward and forward in time. As a result, GregorianCalendar may be used for all years to generate meaningful and consistent results. However, dates obtained using GregorianCalendar are historically accurate only from March 1, 4 AD onward, when modern Julian calendar rules were adopted. Before this date, leap year rules were applied irregularly, and before 45 BC the Julian calendar did not even exist.
Prior to the institution of the Gregorian calendar, New Year's Day was March 25. To avoid confusion, this calendar always uses January 1. A manual adjustment may be made if desired for dates that are prior to the Gregorian changeover and which fall between January 1 and March 24.
Values calculated for the WEEK_OF_YEAR field range from 1 to 53. Week 1 for a year is the earliest seven day period starting on getFirstDayOfWeek() that contains at least getMinimalDaysInFirstWeek() days from that year. It thus depends on the values of getMinimalDaysInFirstWeek(), getFirstDayOfWeek(), and the day of the week of January 1. Weeks between week 1 of one year and week 1 of the following year are numbered sequentially from 2 to 52 or 53 (as needed).
For example, January 1, 1998 was a Thursday. If getFirstDayOfWeek() is MONDAY and getMinimalDaysInFirstWeek() is 4 (these are the values reflecting ISO 8601 and many national standards), then week 1 of 1998 starts on December 29, 1997, and ends on January 4, 1998. If, however, getFirstDayOfWeek() is SUNDAY, then week 1 of 1998 starts on January 4, 1998, and ends on January 10, 1998; the first three days of 1998 then are part of week 53 of 1997.
Values calculated for the WEEK_OF_MONTH field range from 0 to 6. Week 1 of a month (the days with WEEK_OF_MONTH = 1) is the earliest set of at least getMinimalDaysInFirstWeek() contiguous days in that month, ending on the day before getFirstDayOfWeek(). Unlike week 1 of a year, week 1 of a month may be shorter than 7 days, need not start on getFirstDayOfWeek(), and will not include days of the previous month. Days of a month before week 1 have a WEEK_OF_MONTH of 0.
For example, if getFirstDayOfWeek() is SUNDAY and getMinimalDaysInFirstWeek() is 4, then the first week of January 1998 is Sunday, January 4 through Saturday, January 10. These days have a WEEK_OF_MONTH of 1. Thursday, January 1 through Saturday, January 3 have a WEEK_OF_MONTH of 0. If getMinimalDaysInFirstWeek() is changed to 3, then January 1 through January 3 have a WEEK_OF_MONTH of 1.
Example:

import java.util.Calendar;
import java.util.GregorianCalendar;

public class DateAndTime {

          public static void main(String args[]) {
                      GregorianCalendar today = new GregorianCalendar();

                          int todayMonth = today.get(Calendar.MONTH);

                              int todayDayOfMonth = today.get(Calendar.DAY_OF_MONTH);

                                  int todayYear = today.get(Calendar.YEAR);

                                      int todayDayOfYear = today.get(Calendar.DAY_OF_YEAR);
 
                                      int hour=today.get(Calendar.HOUR);
 
                                      int minutes=today.get(Calendar.MINUTE);
 
                                      int seconds=today.get(Calendar.SECOND);
                                      System.out.println(todayDayOfMonth+"-"+todayMonth+"-"+todayYear+" "+hour+":"+minutes+":"+seconds);
          }
}
                      
                                                                                                                                   
            
 

Tuesday, November 2, 2010

Java Inheritance

Inheritance can be defined as the process where one object acquires the properties of another. With the use of inheritance the information is made manageable in a hierarchical order.
When we talk about inheritance the most commonly used key words would beextends and implements. These words would determine whether one object IS-A type of another. By using these keywords we can make one object acquire the properties of another object.

IS-A Relationship:

IS-A is a way of saying : This object is a type of that object. Let us see how theextends keyword is used to achieve inheritance.
public class Animal{
}

public class Mammal extends Animal{
}

public class Reptile extends Animal{
}

public class Dog extends Mammal{
}
Now based on the above example, In Object Oriented terms following are true:
  • Animal is the superclass of Mammal class.
  • Animal is the superclass of Reptile class.
  • Mammal and Reptile are sub classes of Animal class.
  • Dog is the subclass of both Mammal and Animal classes.
Now if we consider the IS-A relationship we can say:
  • Mammal IS-A Animal
  • Reptile IS-A Animal
  • Dog IS-A Mammal
  • Hence : Dog IS-A Animal as well
With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass.
We can assure that Mammal is actually an Animal with the use of the instance operator.

Example:

public class Dog extends Mammal{
   public static void main(String args[]){

      Animal a = new Animal();
      Mammal m = new Mammal();
      Dog d = new Dog();

      System.out.println(m instanceof Animal);
      System.out.println(d instanceof Mammal);
      System.out.println(d instanceof Animal);
   }
}
This would produce following result:
true
true
true
Since we have a good understanding of the extends keyword let us look into how the implements keyword is used to get the IS-A relationship.
The implements keyword is used by classes by inherit from interfaces. Interfaces can never be extended.

Example:

public interface Animal {}

public class Mammal implements Animal{
}

public class Dog extends Mammal{
}

The instanceof Keyword:

Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog is actually an Animal
interface Animal{}

class Mammal implements Animal{}

class Dog extends Mammal{
   public static void main(String args[]){

      Mammal m = new Mammal();
      Dog d = new Dog();

      System.out.println(m instanceof Animal);
      System.out.println(d instanceof Mammal);
      System.out.println(d instanceof Animal);
   }
} 
This would produce following result:
true
true
true