JAVA N WEB TECH SYLLABUS

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

Wednesday, October 27, 2010

Email Address Validation Using a Regular Expression

The following code demonstrates how to validate email using regular expression:

import java.util.regex.*;

class regexSample 
{
   public static void main(String args[]) 
   {
      //Input the string for validation
      String email = "xyz@hotmail.com";

      //Set the email pattern string
      Pattern p = Pattern.compile(".+@.+\\.[a-z]+");

      //Match the given string with the pattern
      Matcher m = p.matcher(email);

      //check whether match is found 
      boolean matchFound = m.matches();

      if (matchFound)
        System.out.println("Valid Email Id.");
      else
        System.out.println("Invalid Email Id.");
   }
}

Tuesday, October 26, 2010

Member Functions Of Character class

static boolean isJavaIdentifierPart(char ch)
          Determines if the specified character may be part of a Java identifier as other than the first character.
static boolean isJavaIdentifierStart(char ch)
          Determines if the specified character is permissible as the first character in a Java identifier.
static boolean isJavaLetter(char ch)
          Deprecated. Replaced by isJavaIdentifierStart(char).
static boolean isJavaLetterOrDigit(char ch)
          Deprecated. Replaced by isJavaIdentifierPart(char).
static boolean isLetter(char ch)
          Determines if the specified character is a letter.
static boolean isLetterOrDigit(char ch)
          Determines if the specified character is a letter or digit.
static boolean isLowerCase(char ch)
          Determines if the specified character is a lowercase character.

static boolean isSpace(char ch)
          Deprecated. Replaced by isWhitespace(char).
static boolean isSpaceChar(char ch)
          Determines if the specified character is a Unicode space character.
static boolean isTitleCase(char ch)
          Determines if the specified character is a titlecase character.
static boolean isUnicodeIdentifierPart(char ch)
          Determines if the specified character may be part of a Unicode identifier as other than the first character.
static boolean isUnicodeIdentifierStart(char ch)
          Determines if the specified character is permissible as the first character in a Unicode identifier.
static boolean isUpperCase(char ch)
          Determines if the specified character is an uppercase character.
static boolean isWhitespace(char ch)
          Determines if the specified character is white space according to Java.
static char toLowerCase(char ch)
          Converts the character argument to lowercase using case mapping information from the UnicodeData file.
 String toString()
          Returns a String object representing this Character's value.
static String toString(char c)
          Returns a String object representing the specified char.
static char toTitleCase(char ch)
          Converts the character argument to titlecase using case mapping information from the UnicodeData file.
static char toUpperCase(char ch)
          Converts the character argument to uppercase using case mapping information from the UnicodeData file.
 

Monday, October 11, 2010

Java Code For Finding the Substring

public static void main(String[] args) {

   String searchMe = "Look for a substring in me";
   String substring = "sub";
   System.out.println(searchMe.contains 
      (substring) ? "Found it" : "Didn't find it");  

        
}

Member Functions Of String Buffer Class

Method Summary
 StringBuffer append(boolean b)
          Appends the string representation of the boolean argument to the string buffer.
 StringBuffer append(char c)
          Appends the string representation of the char argument to this string buffer.
 StringBuffer append(char[] str)
          Appends the string representation of the char array argument to this string buffer.
 StringBuffer append(char[] str, int offset, int len)
          Appends the string representation of a subarray of the char array argument to this string buffer.
 StringBuffer append(double d)
          Appends the string representation of the double argument to this string buffer.
 StringBuffer append(float f)
          Appends the string representation of the float argument to this string buffer.
 StringBuffer append(int i)
          Appends the string representation of the int argument to this string buffer.
 StringBuffer append(long l)
          Appends the string representation of the long argument to this string buffer.
 StringBuffer append(Object obj)
          Appends the string representation of the Object argument to this string buffer.
 StringBuffer append(String str)
          Appends the string to this string buffer.
 StringBuffer append(StringBuffer sb)
          Appends the specified StringBuffer to this StringBuffer.
 int capacity()
          Returns the current capacity of the String buffer.
 char charAt(int index)
          The specified character of the sequence currently represented by the string buffer, as indicated by the index argument, is returned.
 StringBuffer delete(int start, int end)
          Removes the characters in a substring of this StringBuffer.
 StringBuffer deleteCharAt(int index)
          Removes the character at the specified position in this StringBuffer (shortening the StringBuffer by one character).
 void ensureCapacity(int minimumCapacity)
          Ensures that the capacity of the buffer is at least equal to the specified minimum.
 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
          Characters are copied from this string buffer into the destination character array dst.
 int indexOf(String str)
          Returns the index within this string of the first occurrence of the specified substring.
 int indexOf(String str, int fromIndex)
          Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
 StringBuffer insert(int offset, boolean b)
          Inserts the string representation of the boolean argument into this string buffer.
 StringBuffer insert(int offset, char c)
          Inserts the string representation of the char argument into this string buffer.
 StringBuffer insert(int offset, char[] str)
          Inserts the string representation of the char array argument into this string buffer.
 StringBuffer insert(int index, char[] str, int offset, int len)
          Inserts the string representation of a subarray of the str array argument into this string buffer.
 StringBuffer insert(int offset, double d)
          Inserts the string representation of the double argument into this string buffer.
 StringBuffer insert(int offset, float f)
          Inserts the string representation of the float argument into this string buffer.
 StringBuffer insert(int offset, int i)
          Inserts the string representation of the second int argument into this string buffer.
 StringBuffer insert(int offset, long l)
          Inserts the string representation of the long argument into this string buffer.
 StringBuffer insert(int offset, Object obj)
          Inserts the string representation of the Object argument into this string buffer.
 StringBuffer insert(int offset, String str)
          Inserts the string into this string buffer.
 int lastIndexOf(String str)
          Returns the index within this string of the rightmost occurrence of the specified substring.
 int lastIndexOf(String str, int fromIndex)
          Returns the index within this string of the last occurrence of the specified substring.
 int length()
          Returns the length (character count) of this string buffer.
 StringBuffer replace(int start, int end, String str)
          Replaces the characters in a substring of this StringBuffer with characters in the specified String.
 StringBuffer reverse()
          The character sequence contained in this string buffer is replaced by the reverse of the sequence.
 void setCharAt(int index, char ch)
          The character at the specified index of this string buffer is set to ch.
 void setLength(int newLength)
          Sets the length of this String buffer.
 CharSequence subSequence(int start, int end)
          Returns a new character sequence that is a subsequence of this sequence.
 String substring(int start)
          Returns a new String that contains a subsequence of characters currently contained in this StringBuffer.The substring begins at the specified index and extends to the end of the StringBuffer.
 String substring(int start, int end)
          Returns a new String that contains a subsequence of characters currently contained in this StringBuffer.
 String toString()
          Converts to a string representing the data in this string buffer.