Web Technology Lab Manual
Web Technology Lab Manual
Web Technology Lab Manual
S. No 1 2 3 Lab Objective Introduction About Lab Guidelines to Students List of Lab Exercises 4
Contents
Page.No 1 2 4
6 7 8 9
Solutions for JNTU Programs Solutions for Additional Programs Viva questions Reference Books
6 68 120 147
LAB OBJECTIVE Overview Object Web Technologies Basic Concept of Web Technologies Advance Programming
1) Introduction to object oriented programming concepts- java as an object oriented programming language. Introduction to java application and applets-control structuresmethods-arrays. 2) Object based and object oriented programming creating packages-using overloaded constructors-static class variables-data abstraction and information hiding-relation between super class objects and subclass objects composition verses inheritancepolymorphism- dynamic method binding abstract super classes and concrete super classes inheriting interface-use of inner classes and wrapper classes-String to kenizer and String Suffer classes. 3) Role of object oriented programming in designing GUI Graphs and Java20overview of swing- event handling, adapter classes and layout managers. Advance GUI components- JPopup Menus- JDesktopPane- advance layout managers. 4) Exception handling and multithreading in object oriented programming- When exception handling should be used-java exception handling exceptions and inheritance-multithreading in java-thread synchronization-daemon threads Runnable interface- Files and streams in java 5) Network and Database handling through object oriented programming using JOSC processing queries-overview of servlet introduction to networking establishing a simple server and a client introduction to RMI implementing the remote interface.
-2-
LAB REQUIREMENTS: Each student required a system with below configuration in 1:1 ratio as per the schedule: Processor RAM Hard Disk Mouse : : : Pentium IV
All systems are configured in DUAL BOOT mode i.e., Students can boot from Windows XP or Linux as per their lab requirement. This is very useful for students because they are familiar with different Operating Systems so that they can execute their programs in different programming environments. Each student has a separate login for database access Systems are assigned numbers and same system is allotted for students when they do the lab. A web browser either IE or firefox or others. Tomcat 5.5 web server and Apache web server XML editor like Altova Xml-spy [www.Altova.com/XMLSpy free ] , Stylusstudio , etc., A database either Mysql or Oracle JVM(Java virtual machine) must be installed on your system BDK(Bean development kit) must be also be installed
1. 2. 3. 4. 5. 6.
-3-
-4-
Guidelines to Students Equipment in the lab for the use of student community. Students need to maintain a proper decorum in the computer lab. Students must use the equipment with care. Any damage is caused is punishable. Students are required to carry their observation / programs book with completed exercises while entering the lab. Students are supposed to occupy the machines allotted to them and are not supposed to talk or make noise in the lab. The allocation is put up on the lab notice board. Lab can be used in free time / lunch hours by the students who need to use the systems should take prior permission from the lab in-charge. Lab records need to be submitted on or before date of submission. Students are not supposed to use floppy disks Use of computer network is encouraged.
-5-
Web Technologies Syllabus Programs (JNTU) S.No 1 Programs Develop static pages (using only HTML) of an online Book store. The pages should resemble: www.amazon.com The website should consist the following pages. Home page, Registration and user Login, User profile page, Books catalog, Shopping cart, Payment By credit card, order confirmation. Validate the registration, user login, user profile and payment by credit card pages using JavaScript. Create and save an XML document at the server, which contains 10 users information. Write a program which takes User Id as input and returns the user details by taking the user information from the XML document. Bean Assignments a. Create a JavaBeans which gives the exchange value of INR (Indian Rupees) into equivalent American/Canadian/Australian Dollar value. b. Create a simple Bean with a label which is the count of number of clicks. Then create a Bean info class such that only the count properly is visible in the property Window. c. Create two Beans a) Keypad b) Display pad. After that integrate the two Beans to make it work as a calculator. d. Create two Beans Traffic Light(implemented as a label with only three background colors-red, green, yellow) and Automobile(Implemented as a Text Box which states its state/movement). The state of the Automobile should depend on the following Light Transition table. Install TOMCAT web server. Convert the static web pages of assignments 2 into dynamic web pages using servlets and cookies. Hint: Users information (user id, password, credit card number) would be stored in web. Xml. Each user should have a separate shopping cart. Redo the previous task using JSP by converting the static web pages of assignment 2 into dynamic web pages. Create a database with user information and books information. The books catalogue should be dynamically loaded from the database. Follow the MVC architecture while doing the website. Implement the Hello World program using JSP Struts Framework. Using JavaScript sort given array in ascending and descending order.
2 3
7 8
-6-
Web Technologies Programs (JNTU) solutions 1. Develop static pages (using only HTML) of an online Book store. The pages should resemble: www.amazon.com The website should consist the following pages. Home page, Registration and user Login, User profile page, Books catalog, Shopping cart, Payment By credit card, order confirmation. HomePage.html <HTML> <HEAD><TITLE>HomePage</TITLE></HEAD> <BODY> This is HomePage <HR> <MARQUEE>WWW.BOOKS.COM</MARQUEE> <IMG SRC=".\book.gif" height="30%" width="40%"> <PRE> <A HREF=".\HomePage1.html">Home Page</A> <A HREF=".\Registration1.html">Registration User Login</A> <A HREF=".\UserProfile1.html">User Profile Page</A> <A HREF=".\BooksCatalog1.html">Books Catalog</A> <A HREF=".\ShoppingCart1.html">Shopping Cart</A> <A HREF=".\Payment1.html">Payment By CreditCard</A> <A HREF=".\OrderConfirmation1.html">Order Confirmation</A> </PRE> </BODY> </HTML>
-7-
Registration1.html <HTML><HEAD><TITLE>Registration</TITLE></HEAD> <BODY>This is Registration User Login<HR> <MARQUEE>WWW.BOOKS.COM</MARQUEE> <IMG SRC=".\book.gif" height="30%" width="40%"> <PRE><A HREF="\WEBSITE\HomePage.html">Home Page</A> <A HREF=".\HomePage1.html">Home Page</A> <A HREF=".\Registration1.html">Registration User Login</A> <A HREF=".\UserProfile1.html">User Profile Page</A> <A HREF=".\BooksCatalog1.html">Books Catalog</A> <A HREF=".\ShoppingCart1.html">Shopping Cart</A> <A HREF=".\Payment1.html">Payment By CreditCard</A> <A HREF=".\OrderConfirmation1.html">Order Confirmation</A> </PRE><FORM><pre> Enter your Name :<INPUT TYPE="TEXT"> Enter Password :<INPUT TYPE="PASSWORD"> Confirm Password:<INPUT TYPE="PASSWORD"> Gender :<Input type="Radio" name="R1" value="Male">Male <Input type="Radio" name="R1" value="Female">Female Country :<select><option selected>Select Country</option> <option value="ind">India</option> <option value="usa">United States of America</option> <option value="eng">England</option> <option value="aus">Australia</option> <option value="ger">Germany</option> <option value="pol">Poland</option> </select><center><Input type="submit"><input type="reset"></center> </pre></form></BODY></HTML>
-8-
USERLOGIN1.HTML:<html><head><title>UserLogin</title></head> <body> <IMG SRC=".\book.gif" height="30%" width="40%"> <PRE><A HREF="\WEBSITE\HomePage.html">Home Page</A> <A HREF=".\HomePage1.html">Home Page</A> <A HREF=".\Registration1.html">Registration User Login</A> <A HREF=".\UserProfile1.html">User Profile Page</A> <A HREF=".\BooksCatalog1.html">Books Catalog</A> <A HREF=".\ShoppingCart1.html">Shopping Cart</A> <A HREF=".\Payment1.html">Payment By CreditCard</A> <A HREF=".\OrderConfirmation1.html">Order Confirmation</A> </PRE> UserId : <input type="text" id="uid"><br/> Password: <input type="text" id="pwd"><br /> <br/><input type ="button" value ="LogIn"> </body></html>
-9-
PAYMENT1.Html:<HTML><HEAD><TITLE>Payment By Credit Card</TITLE></HEAD> <BODY> <MARQUEE>WWW.BOOKS.COM</MARQUEE> <IMG SRC=".\book.gif" height="30%" width="40%"> <PRE> <A HREF=".\HomePage1.html">Home Page</A> <A HREF=".\Registration1.html">Registration User Login</A> <A HREF=".\UserProfile1.html">User Profile Page</A> <A HREF=".\BooksCatalog1.html">Books Catalog</A> <A HREF=".\ShoppingCart1.html">Shopping Cart</A> <A HREF=".\Payment1.html">Payment By CreditCard</A> <A HREF=".\OrderConfirmation1.html">Order Confirmation</A> </PRE> <table border=0 cellpadding=0 cellspacing=0 width=400> <tr><th>What will it take to pay off my credit card?</th></tr> <tr><td align=center> <table cellpadding=2 cellspacing=0> <tr><td align="right">Enter your credit card balance: $</td><td><input size=6 type=text id="cwBalance"></td></tr> <tr><td align="right">Enter the credit card's interest rate: </td><td><input size=6 type=text id="cwRate">%</td></tr> <tr><td align="right">Enter payment amount per month: $</td><td><input size=6 type=text id="cwMonthlyAmount"></td></tr> <tr><td align="center"><b>or</b></td><td> </td></tr> <tr><td align="right">Enter desired months until debt free: </td><td><input size=6 type=text id="cwDesiredMonths"></td></tr> <tr><td colspan=2 align="center"><input type=button value="Calculate" onclick="cwCalc();"></td></tr> <tr><td colspan=2 align="center" id="cwResult"></td></tr> </table></td></tr> </table> </BODY> </HTML>
-10-
2. Validate the registration, user login, user profile and payment by credit card pages using JavaScript. REGISTRATION FORM <Html> <Head> <Title>User Registration Form</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <script language="JavaScript" fptype="dynamicanimation"> </script> </head> <body> <script language="javascript"> function verify(form) { if(document.forms[0].elements[0].value=="") { alert("Please Enter User ID"); document.forms[0].elements[0].focus(); return(false); } if(document.forms[0].elements[1].value=="") { alert("Please Enter your Password"); document.forms[0].elements[2].value=""; document.forms[0].elements[1].focus(); return(false); } if(document.forms[0].elements[1].value.length<4) { alert("Password must be greater than 4 character"); document.forms[0].elements[1].value=""; document.forms[0].elements[2].value=""; document.forms[0].elements[1].focus(); return(false); } if(document.forms[0].elements[2].value=="") { alert("Please Enter your Confirm Password"); document.forms[0].elements[2].focus(); return(false); } if((document.forms[0].elements[1].length)!=(document.forms[0].elements[2].length)) { alert("Your Password does not match with Confirm Password"); document.forms[0].elements[1].value=""; -11-
document.forms[0].elements[2].value=""; document.forms[0].elements[1].focus(); return(false); } if((document.forms[0].elements[1].length)==(document.forms[0].elements[2].length)) { if((document.forms[0].elements[1].value)!=(document.forms[0].elements[2].value)) { alert("Your Password does not match with Confirm Password"); document.forms[0].elements[1].value=""; document.forms[0].elements[2].value=""; document.forms[0].elements[1].focus(); return(false); } } if(document.forms[0].elements[3].value=="secq") { alert("Please Select your Security Question"); document.forms[0].elements[3].focus(); return(false); } if(document.forms[0].elements[4].value=="") { alert("Please Answer the security question"); document.forms[0].elements[4].focus(); return(false); } if(document.forms[0].elements[5].value=="DD") { alert("Please select Day of DOB"); document.forms[0].elements[5].focus(); return(false); } if(document.forms[0].elements[6].value=="MM") { alert("Please select Month of DOB"); document.forms[0].elements[6].focus(); return(false); } if(document.forms[0].elements[7].value=="YYYY") { alert("Please select Year of DOB"); document.forms[0].elements[7].focus(); return(false); -12-
} if(document.forms[0].elements[10].checked==true) { if(document.forms[0].elements[11].value=="") { alert("Please Enter your First Name"); document.forms[0].elements[11].focus(); return(false); } if(document.forms[0].elements[13].value=="") { alert("Please Enter your Last Name"); document.forms[0].elements[13].focus(); return(false); } if(document.forms[0].elements[14].value=="Year") { alert("Please specify your Academic year"); document.forms[0].elements[14].focus(); return(false); } if(document.forms[0].elements[15].value=="adminyear") { alert("Please put your Admission Year"); document.forms[0].elements[15].focus(); return(false); } if(document.forms[0].elements[16].value=="dept") { alert("Please Select your Department"); document.forms[0].elements[16].focus(); return(false); } if(document.forms[0].elements[17].value=="") { alert("Please put your Roll Number"); document.forms[0].elements[17].focus(); return(false); } if(document.forms[0].elements[17].value!="") { r0=document.forms[0].elements[17].value.indexOf('2'); r1=document.forms[0].elements[17].value.indexOf('k'); r2=parseInt(document.forms[0].elements[17].value.charAt(2)); r3=document.forms[0].elements[17].value.indexOf('_'); r4=parseInt(document.forms[0].elements[17].value.charAt(4)); -13-
r5=parseInt(document.forms[0].elements[17].value.charAt(5)); r6=parseInt(document.forms[0].elements[17].value.charAt(6)); len=document.forms[0].elements[17].value.length; if((len!=7)||(r0!=0)||(r1!=1)||(r3!=3)||(r4>6 || r4<1)||(r2>9 || r2<1)) { alert("Not a valid Roll Number"); document.forms[0].elements[17].focus(); return(false) } switch(document.forms[0].elements[16].value) { case 'IT': if(r4!=6||(r5>4||r5<0)||(r6>9||r6<0)) { alert("Not a valid Roll Number of Information Technology"); document.forms[0].elements[16].focus(); return(false) }break; case 'CSE': if(r4!=5||(r5>4||r5<0)||(r6>9||r6<0)) { alert("Not a valid Roll Number of Computer Science"); document.forms[0].elements[16].focus(); return(false) }break; case 'ECE': if(r4!=4||(r5>4||r5<0)||(r6>9||r6<0)) { alert("Not a valid Roll Number of Electronics"); document.forms[0].elements[16].focus(); return(false) }break; case 'EE': if(r4!=2||(r5>6||r5<0)||(r6>9||r6<0)) { alert("Not a valid Roll Number of Electrical Engineering"); document.forms[0].elements[16].focus(); return(false) }break; case 'ME': if(r4!=3||(r5>6||r5<0)||(r6>9||r6<0)) { alert("Not a valid Roll Number of Mechanical Engineering"); document.forms[0].elements[16].focus(); return(false) }break; -14-
case 'CE': if(r4!=1||(r5>6||r5<0)||(r6>9||r6<0)) { alert("Not a valid Roll Number of Civil Engineering"); document.forms[0].elements[16].focus(); return(false) }break; } switch(document.forms[0].elements[14].value) { case 'Fourth': if(r2!=1||(r2>9||r2<0)) { alert("Not a valid Roll Number of Forth Year"); document.forms[0].elements[14].focus(); return(false) }break; case 'Third': if(r2!=2||(r2>9||r2<0)) { alert("Not a valid Roll Number of Third Year"); document.forms[0].elements[14].focus(); return(false) }break; case 'Second': if(r2!=3||(r2>9||r2<0)) { alert("Not a valid Roll Second Year"); document.forms[0].elements[14].focus(); return(false) }break; case 'First': if(r2!=4||(r2>9||r2<0)) { alert("Not a valid Roll Number of First Year"); document.forms[0].elements[14].focus(); return(false) }break; } } } if(document.forms[0].elements[24].checked==true) { if(document.forms[0].elements[25].value=="") { -15-
alert("Please Enter Your First Name"); document.forms[0].elements[25].focus(); return(false); } if(document.forms[0].elements[27].value=="") { alert("Please Enter your Last Name"); document.forms[0].elements[27].focus(); return(false); } if(document.forms[0].elements[30].value=="state") { alert("Please Select Your State"); document.forms[0].elements[30].focus(); return(false); } if(document.forms[0].elements[31].value=="country") { alert("Please Select Your State"); document.forms[0].elements[31].focus(); return(false); } if((document.forms[0].elements[32].value=="pincode")|| (document.forms[0].elements[33].value="")) { alert("Please Select Your Pincode OR if Other specify"); document.forms[0].elements[32].focus(); return(false); } } } function studentclear(form) { document.forms[0].elements[11].value=""; document.forms[0].elements[12].value=""; document.forms[0].elements[13].value=""; document.forms[0].elements[14].value="Year"; document.forms[0].elements[15].value="adminyear"; document.forms[0].elements[16].value="dept"; document.forms[0].elements[17].value=""; document.forms[0].elements[18].value="selecthostel"; document.forms[0].elements[19].value=""; document.forms[0].elements[20].value=""; document.forms[0].elements[21].value=""; document.forms[0].elements[22].value=""; document.forms[0].elements[23].value=""; -16-
document.forms[0].elements[25].focus(); } function generalclear(form) { document.forms[0].elements[25].value=""; document.forms[0].elements[26].value=""; document.forms[0].elements[27].value=""; document.forms[0].elements[28].value="City"; document.forms[0].elements[29].value=""; document.forms[0].elements[30].value="state"; document.forms[0].elements[31].value="country"; document.forms[0].elements[32].value="pincode"; document.forms[0].elements[33].value=""; document.forms[0].elements[34].value=""; document.forms[0].elements[35].value=""; document.forms[0].elements[36].value=""; document.forms[0].elements[37].value=""; document.forms[0].elements[11].focus(); } </script> <body onLoad=document. forms [0].elements[0].focus();> <form action ="" method="post" onsubmit="return verify(this.form)"> <center> <p dynamicanimation="fpAnimelasticRightFP1" id="fpAnimelasticRightFP1" style="position: relative !important; visibility: hidden" language="Javascript1.2"> <font size="6" face="Monotype Corsiva" color="#800000">New User Registration Form</font></p> </center><br> <i><font color="#FF0000"><font face="Arial" size="4">*</font> <font face="Arial" size="2"></font> </font> <font face="Arial" size="2"color="#FF0000">Indicates all the fields are mandatory</font></i><hr><p> <font size="4" face="Arial, Helvetica, sans-serif" color="#FF0000">*</font> <font size="-1" face="Arial, Helvetica,sans-serif">User ID:</font><b> <input name="uid" size="16" maxlength="15"></b> <font color="#FF0033" size="2"> </font> <font face="Arial" size="2" color="#FF0033"> (Contains only letters (a-z), numbers (0-9) and underscore)</font> <br><b><br></b> <font size="4" face="Arial, Helvetica, sans-serif" color="#FF0000">*</font> <font size="-1" face="Arial, Helvetica,sans-serif">Password: </font> <font color="#000000"> </font> <input type="password" name="pswd" size="9" maxlength="10" style="font-weight: bold; color:#008000"> <font color="#000000"size="2"><font face="Arial"> </font></font> <font color="#FF0033" size="2" face="Arial"> -17-
(Password should be of minimum 4(four) and maximum 10(ten) characters. </font> <font size="2"><font color="#FF0033" face="Arial">) </font></p> </font> <font face="ARIAL, HELVETICA" size="-1"> </font> <font size="4" face="Arial, Helvetica, sans-serif" color="#FF0000">*</font> <font face="ARIAL, HELVETICA" size="-1">Re-Type Password</font>:<font size="2"> <b> <input type="password" name="cpswd" size="11" maxlength="10" style="color:#008000" ></b> </font> <hr><font size="2"> </font><font size="2"> <font face="Arial, Helvetica, sans-serif"> <i>If you forget your password, you can retrieve it by answering your unique hint question. <br> Frame your question such that only you know its answer. </i></font></font> <div align="center"><font face="Arial" size="2"></font> <font face="Arial" size="2"></font><font face="Arial" size="2"></font> <font face="Arial" size="2"></font></div> <font face="Arial" size="2"><br></font> <font size="2"><font face="Arial"> <font face="Arial,Helvetica, sans-serif"></font></font></font> <font size="4" face="Arial, Helvetica, sans-serif" color="#FF0000">*</font> <font size="2"><font face="Arial"> <font face="Arial, Helvetica,sans-serif"> Select a question forgetting password </font><b>: </b></font> <select size="1" name="secq"> <option selected value="secq">Select a hit question ?</option> <option value="What is your favourite multimedia software?"> What is your favourite multimedia software?</option> <option value="What is your favourite game?">What is your favourite game?</option> <option value="who is your favourite Cricketer?"> who is your favourite Cricketer? </option> <option value="who is your favourite Film Actor?"> who is your favourite Film Actor?</option> <option value="what is your favourite food?">what is your favourite food?</option> </select><font face="Arial"><b> </b></font></font><p><font size="2"> </font><font size="4" face="Arial, Helvetica, sans-serif" color="#FF0000">*</font> <font color="#000000" face="Arial, Helvetica, sans-serif" size="2">Hit Answer: <input type="text" name="seca" size="21"> </font> <font size="2"><font color="#000000" face="Arial, Helvetica,sans-serif"> </font> <font color="#FF0033" face="Arial">(Write Your Answer)</font> <font color="#000000" face="Arial"> </font> </font><font size="1"></p></font> <hr><div align="left"><font face="Arial,Helvetica, sans-serif" size="-1"> DD MM YYYY <br> </font> <font size="4" face="Arial, Helvetica, sans-serif"color="#FF0000">*</font> -18-
<font face="Arial, Helvetica, sans-serif" size="-1">Date of Birth: <select size="1" name="DD"> <option selected value="DD">Day</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select size="1" name="MM"> <option selected value="MM">Month</option><option value="JANUARY">JAN</option> <option value="FEBRUARY">FEB</option> <option value="MARCH">MAR</option> <option value="APRIL">APR</option> <option value="MAY">MAY</option> <option value="JUNE">JUN</option> <option value="JULY">JUL</option> <option value="AUGUST">AUG</option> <option value="SEPTEMBER">SEP</option> <option value="OCTOBER">OCT</option><option value="NOVEMBER">NOV</option> <option value="DECEMBER">DEC</option> </select> <select size="1" name="YYYY"> <option selected value="YYYY">Year</option> <option value="1970">1970</option> <option value="1971">1971</option> <option value="1972">1972</option> <option value="1973">1973</option> <option value="1974">1974</option> <option value="1975">1975</option> <option value="1976">1976</option> <option value="1977">1977</option> <option value="1978">1978</option> <option value="1979">1979</option> <option value="1980">1980</option> <option value="1981">1981</option> <option value="1982">1982</option> <option value="1983">1983</option> <option value="1984">1984</option> <option value="1985">1985</option> <option value="1986">1986</option> <option value="1987">1987</option> <option value="1988">1988</option> <option value="1989">1989</option> <option value="1990">1990</option> <option value="1991">1991</option> <option value="1992">1992</option> <option value="1993">1993</option> <option value="1994">1994</option> <option value="1995">1995</option> <option value="1996">1996</option> <option value="1996">1996</option> <option value="1997">1997</option> <option value="1998">1998</option> <option value="1999">1999</option> <option value="2000">2000</option> <option value="2001">2001</option> -19-
<option value="2002">2002</option> <option value="2003">2003</option> <option value="2004">2004</option> <option value="2005">2005</option> <option value="2006">2006</option> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010">2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> <option value="2017">2017</option> <option value="2018">2018</option> <option value="2019">2019</option> <option value="2020">2020</option> </select></font></div> <p><font face="Arial, Helvetica, sans-serif" size="-1"></font> <font size="4" face="Arial, Helvetica, sans-serif" color="#FF0000">*</font> <font face="Arial, Helvetica, sans-serif" size="-1"> Gender: <input type="radio" name="Male" value="male" checked> Male <INPUT type=radio value="female" name="Male" >Female </font> <hr><font size="4" face="Arial, Helvetica, sans-serif" color="#FF0000"> </font> <p> <font face="Arial, Helvetica, sans-serif" size="-1"> Contact No: <input type="text" size="6" name="std" maxlength="6"><b> -</b> <input type="text" size="9" name="phno" maxlength="9"> </font><p> <font face="Arial, Helvetica, sans-serif" size="-1"> Mobile No: <input type="text" size="18" name="mobno" maxlength="15"></font><p> <font face="Arial, Helvetica, sans-serif" size="-1"> Email:<input type="text" name="email" size="20"> </font><p><hr> <div align="left"><font face="Arial, Helvetica, sans-serif" size="-1"> </font> </div><center> <input type="submit" value="Submit" name="Submit" tabindex="25"> <input type="reset" value="Reset" name="Reset" tabindex="26"> </center></form></body></html>
-20-
OUTPUT:-
-21-
USER LOGIN:<html><head><script> function f() { if(document.getElementById('uid').value.length==0) alert("UserId can't e blank"); else if(document.getElementById('pwd').value.length==0) alert("Password can't be blank"); else { alert("successfully logged in"); window.open("Welcome.html");} } </script></head> <body> UserId : <input type="text" id="uid"><br/> Passowrd: <input type="text" id="pwd"><br /> <br/><input type ="button" onclick="f()" value ="LogIn"> </body></html> OUTPUT:-
-22-
USER PROFILE <html> <head> <title>User Profile</title> </head> <body> <H1>User Profile</H1> <Hr> <pre> <b>Name : </b> <b>E-Mail ID : </b> <b>Date of Birth : </b> <b>Gender : </b> <b>City : </b> <b>State : </b> <b>Country : </b> <b>Zip Code : </b> </pre> </Body> </Html> OUTPUT:-
-23-
PAYMENT BY CREDIT CARD <HTML><HEAD> <style type="text/css"> <!-.cwCalc{border:1px solid black;} .cwCalc TH{background-color:#BBBBBB;} .cwCalc TD{background-color:#DDDDDD;} --> </style> <script type="text/javascript"> function cwCalc() { if (cwBalance.value=='') { alert('Please enter your credit card balance.'); return;} if (cwRate.value=='') { alert('Please enter your credit card\'s interest rate.'); return;} if ( (cwMonthlyAmount.value=='' && cwDesiredMonths.value=='') || (cwMonthlyAmount.value!='' && cwDesiredMonths.value!='') ) { alert('Please enter either a payment amount or desired months.'); return;} var mRate=(cwRate.value/100)/12; if (cwMonthlyAmount.value=='') { var payment=cwBalance.value*(mRate) / (1-Math.pow((1+mRate),(-cwDesiredMonths.value)) ); payment=Math.round(payment*100)/100; cwResult.innerHTML="It will cost $" + payment.toFixed(2) + " a month to pay off this card and will cost you a total of $" + (payment*cwDesiredMonths.value).toFixed(2) + "."; } else { var remainingBalance=cwBalance.value; var minPayment=mRate*cwBalance.value; var months=0; var lastPayment; if (minPayment>cwMonthlyAmount.value) { alert ('Your monthly payment is less than the monthly interest charged by this card.'); return;} while (remainingBalance>0) { months++; remainingBalance=remainingBalance*(1 + mRate)-cwMonthlyAmount.value; } cwResult.innerHTML="It will take " + months + " months to pay off this card and will cost you a total of $" + (cwMonthlyAmount.value*months).toFixed(2) + "."; } } -24-
</script> </HEAD> <BODY> <table class="cwCalc" border=0 cellpadding=0 cellspacing=0 width=400> <tr><th>What will it take to pay off my credit card?</th></tr> <tr><td align=center> <table cellpadding=2 cellspacing=0> <tr><td align="right">Enter your credit card balance: $</td><td><input size=6 type=text id="cwBalance"></td></tr> <tr><td align="right">Enter the credit card's interest rate: </td><td><input size=6 type=text id="cwRate">%</td></tr> <tr><td align="right">Enter payment amount per month: $</td><td><input size=6 type=text id="cwMonthlyAmount"></td></tr> <tr><td align="center"><b>or</b></td><td> </td></tr> <tr><td align="right">Enter desired months until debt free: </td><td><input size=6 type=text id="cwDesiredMonths"></td></tr> <tr><td colspan=2 align="center"><input type=button value="Calculate" onclick="cwCalc();"></td></tr> <tr><td colspan=2 align="center" id="cwResult"></td></tr> </table></td></tr> <tr> <td align=right valign=top style="font-weight:bold;font-size:8pt;"> Powered by:<a href="http://www.creditorweb.com/CreditCards/" target="_blank"> <img src="http://www.creditorweb.com/images/logosmall.png" border="0" alt="Compare credit cards and find credit card tools and articles at Creditor Web"></a></td></tr> </table> <p><center> <font face="arial, helvetica" size"-2">Free JavaScripts provided<br>by <a href="http://srinu.com">The JavaScript Source</a></font> </center><p> </BODY> </HTML>
-25-
OUTPUT:-
-26-
3.Create and save an XML document at the server. Which contains user information or Program To Implement Loginform Using Sevlets PROGRAM filename:Usevalidation.html <html> <head> <title>Login Form</title> </head> <body leftmargin=75 topmargin=75 bgcolor=white> <form method=Get action="http:127.0.0.1:8080\validation"> UserName <input type=text name=user> <br><br> Password <input type=password name=pass> <br><br> <input type=submit value=submit> <input type=reset name=cancel> </form> </body> </html> filename:UserValid.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class UserValid extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { res.setContentType("text/html"); PrintWriter out=res.getWriter(); String usr=res.getParameter("user"); String pwd=res.getParameter("pass"); if(usr equals("naveen")&&pwd equals("nav") out.println("Successfully Logged in"); else out.println("Unsuccessful"); } } -27-
filename:web.xml <web-app> <servlet> <servlet-name>UserValidation</servlet-name> <servlet-class>UserValid</servlet-class> </servlet> <servlet-mapping> <servlet-name>UserValidation</servlet-name> <url-pattern>/validation/*</url-pattern> </servlet-mapping> </web-app>
-28-
4.Developing a Simple Bean Using the BDK: This section presents an example that shows how to develop a simple Bean and connect it to other components via the BDK. Our new component is called the Colors Bean. It appears as either a rectangle or ellipse that is filled with a color. A color is chosen at random when the Bean begins execution. A public method can be invoked to change it. Each time the mouse is clicked on the Bean, another random color is chosen. There is one boolean read/write property that determines the shape. The BDK is used to lay out an application with one instance of the Colors Bean and one instance of the OurButton Bean. The button is labeled Change. Each time it is pressed, the color changes. SOFTWARE DEVELOPMENT USING JAVA Create a New Bean Here are the steps that you must follow to create a new Bean: 1. Create a directory for the new Bean. 2. Create the Java source file(s). 3. Compile the source file(s). 4. Create a manifest file. 5. Generate a JAR file. 6. Start the BDK. 7. Test. The following sections discuss each of these steps in detail. Create a Directory for the New Bean You need to make a directory for the Bean. To follow along with this example, create c:\bdk\demo\sunw\demo\colors. Then change to that directory. The Colors and OurButton Beans Create the Source File for the New Bean The source code for the Colors component is shown in the following listing. It is located in the file Colors.java. The import statement at the beginning of the file places it in the package named sunw.demo.colors. Recall from Chapter 9 that the directory hierarchy corresponds to the package hierarchy. Therefore, this file must be located in a subdirectory named sunw\demo\colors relative to the CLASSPATH environment variable. The color of the component is determined by the private Color variable color, and its shape is determined by the private boolean variable rectangular. The constructor defines an anonymous inner class that extends MouseAdapter and overrides its mousePressed( ) method. The change( ) method is invoked in response to mouse presses. The component is initialized to a rectangular shape of 200 by 100 pixels. The change( ) method is invoked to select a random color and repaint the component. The getRectangular( ) and setRectangular( ) methods provide access to the one property of this Bean. The change( ) method calls randomColor( ) to choose a color and then calls repaint( ) to make the change visible. Notice that the paint( ) method uses the rectangular and color variables to determine how to present the Bean. // A simple Bean. package sunw.demo.colors; -29-
import java.awt.*; import java.awt.event.*; public class Colors extends Canvas { transient private Color color; private boolean rectangular; public Colors() { addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { change(); } }); rectangular = false; setSize(200, 100); change(); } public boolean getRectangular() { return rectangular; } public void setRectangular(boolean flag) { this.rectangular = flag; repaint(); } public void change() { SOFTWARE DEVELOPMENT USING JAVA color = randomColor(); repaint(); } private Color randomColor() { int r = (int)(255*Math.random()); int g = (int)(255*Math.random()); int b = (int)(255*Math.random()); return new Color(r, g, b); } public void paint(Graphics g) { Dimension d = getSize(); int h = d.height; int w = d.width; g.setColor(color); if(rectangular) { g.fillRect(0, 0, w-1, h-1); } else { g.fillOval(0, 0, w-1, h-1); } } -30-
} Compile the Source Code for the New Bean Compile the source code to create a class file. Type the following: javac Colors.java. Create a Manifest File You must now create a manifest file. First, switch to the c:\bdk\demo directory. This is the directory in which the manifest files for the BDK demos are located. Put the source code for your manifest file in the file colors.mft. It is shown here: Name: sunw/demo/colors/Colors.class Java-Bean: True This file indicates that there is one .class file in the JAR file and that it is a Java Bean. Notice that the Colors.class file is in the package sunw.demo.colors and in the subdirectory sunw\demo\colors relative to the current directory. Generate a JAR File Beans are included in the ToolBox window of the BDK only if they are in JAR files in the directory c:\bdk\jars. These files are generated with the jar utility. Enter the following: jar cfm ..\jars\colors.jar colors.mft sunw\demo\colors\*.class This command creates the file colors.jar and places it in the directory c:\bdk\jars. (You may wish to put this in a batch file for future use.) Start the BDK Change to the directory c:\bdk\beanbox and type run. This causes the BDK to start. You should see three windows, titled ToolBox, BeanBox, and Properties. The ToolBox window should include an entry labeled Colors for your new Bean. Create an Instance of the Colors Bean After you complete the preceding steps, create an instance of the Colors Bean in the BeanBox window. Test your new component by pressing the mouse anywhere within its borders. Its color immediately changes. Use the Properties window to change the rectangular property from false to true. Its shape immediately changes. Create and Configure an Instance of the OurButton Bean Create an instance of the OurButton Bean in the BeanBox window. Then follow these steps: 1. Go to the Properties window and change the label of the Bean to Change. You should see that the button appearance changes immediately when this property is changed. 2. Go to the menu bar of the BeanBox and select Edit | Events | action | actionPerformed. 3. Move the cursor so that it is inside the Colors Bean display area, and click the left mouse button. You should see the Event Target Dialog dialog box. 4. The dialog box allows you to choose a method that should be invoked when this button is clicked. Select the entry labeled change and click the OK button. You should see a message box appear very briefly, stating that the tool is Generating and compiling adaptor class. 5. Click on the button. You should see the color change. You might want to experiment with the Colors Bean a bit before moving on. Output: -31-
Create two Beans Traffic Light(implemented as a label with only three background colors-red, green, yellow) and Automobile(Implemented as a Text Box which states its state/movement). The state of the Automobile should depend on the following Light Transition table. /*<applet code="Sig.class" height=300 width=200></applet>*/ import java.awt.*; import java.lang.String; import java.awt.event.*; import java.applet.Applet; import java.applet.*; public class Sig extends Applet implements ItemListener{ boolean c1,c2,c3; String s1; Checkbox r1,r2,r3; CheckboxGroup cbg; public void init(){ cbg=new CheckboxGroup(); Panel p=new Panel(); p.setLayout(new GridLayout()); add(r1=new Checkbox("red",cbg,false)); add(r2=new Checkbox("yellow",cbg,false)); add(r3=new Checkbox("green",cbg,false)); r1.addItemListener(this); r2.addItemListener(this); -32-
r3.addItemListener(this); } public void paint(Graphics g) { g.setColor(Color.red); g.drawOval(10, 30, 20, 20); //System.out.println(s1); g.setColor(Color.yellow); g.drawOval(10, 60, 20, 20); g.setColor(Color.green); g.drawOval(10, 90, 20, 20); s1=cbg.getSelectedCheckbox().getLabel(); if(s1=="red") { g.setColor(Color.red); g.fillOval(10, 30, 20, 20); } else if(s1=="yellow") { g.setColor(Color.yellow); g.fillOval(10, 60, 20, 20); } else if(s1=="green") { g.setColor(Color.green); g.fillOval(10, 90, 20, 20); } } public void itemStateChanged(ItemEvent ie) { repaint(); } }
-33-
5: SERVELETS & COOKIES Reading Servlet Parameters The ServletRequest class includes methods that allow you to read the names and values of parameters that are included in a client request. We will develop a servlet that illustrates their use. The example contains two files: PostParameters.htm defines a Web page, and PostParametersServlet.java defines a servlet. The HTML source code for PostParameters.htm is shown in the following listing. It defines a table that contains two labels and two text fields. One of the labels is Employee and the other is Phone. The form also includes a submit button. Notice that the action parameter of the form tag specifies a URL. The URL identifies the servlet to process the HTTP POST request. <html> <body> <center> <form name="Form1" method="post" action="http://localhost:8080/servlet/PostParametersServlet"> <table> <tr> <td><B>Employee</td> <td><input type=textbox name="e" size="25" value=""></td> </tr> <tr> <td><B>Phone</td> <td><input type=textbox name="p" size="25" value=""></td> </tr> </table> <input type=submit value="Submit"> </body> </html> The source code for PostParametersServlet.java is shown in the following listing. The service( ) method is overridden to process client requests. The getParameterNames( ) method returns an enumeration of the parameter names. These are processed in a loop. You can see that the parameter name and value are output to the client. The parameter value is obtained via the getParameter( ) method. import java.io.*; import java.util.*; import javax.servlet.*; public class PostParametersServlet extends GenericServlet { public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { -34-
// Get print writer PrintWriter pw = response.getWriter(); // Get enumeration of parameter names Enumeration e = request.getParameterNames(); // Display parameter names and values while(e.hasMoreElements()) { String pname = (String)e.nextElement(); pw.print(pname + " = "); String pvalue = request.getParameter(pname); pw.println(pvalue); } pw.close(); } }
The example contains two files: ColorGet.htm defines a Web page, and ColorGetServlet.java defines a servlet. The HTML source code for ColorGet.htm is shown in the following listing. It defines a form that contains a select element and a submit button. Notice that the action parameter of the form tag specifies a URL. The URL identifies a servlet to process the HTTP GET request. <body> <center> <form name="Form1" action="http://localhost:8080/servlet/ColorGetServlet"> <B>Color:</B> <select name="color" size="1"> <option value="Red">Red</option> <option value="Green">Green</option> <option value="Blue">Blue</option> </select> <br><br> <input type=submit value="Submit"> </form> </body> </html> method is overridden to process any HTTP GET requests that are sent to this servlet. It uses the getParameter( ) method of HttpServletRequest to obtain the selection that was made by the user. A response is then formulated. import java.io.*; import javax.servlet.*; -35-
import javax.servlet.http.*; public class ColorGetServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String color = request.getParameter("color"); response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>The selected color is: "); pw.println(color); pw.close();
The HTML source code for ColorPost.htm is shown in the following listing. It is identical to ColorGet.htm except that the method parameter for the form tag explicitly specifies that the POST method should be used, and the action parameter for the form tag specifies a different servlet. <html> <body> <center> <form name="Form1" method="post" action="http://localhost:8080/servlet/ColorPostServlet"> <B>Color:</B> <select name="color" size="1"> <option value="Red">Red</option> <option value="Green">Green</option> <option value="Blue">Blue</option> </select> <br><br> <input type=submit value="Submit"> </form> </body> </html> The source code for ColorPostServlet.java is shown in the following listing. The doPost( ) method is overridden to process any HTTP POST requests that are sent to this servlet. It uses the getParameter( ) method of HttpServletRequest to obtain the selection that was made by the user. A response is then formulated. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ColorPostServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) -36-
throws ServletException, IOException { String color = request.getParameter("color"); response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>The selected color is: "); pw.println(color); pw.close(); } }
-37-
6. JSP Source Code for Basic Arithmetic Example <html> <head> <title>JSP 2.0 Expression Language - Basic Arithmetic</title> </head> <body> <h1>JSP 2.0 Expression Language - Basic Arithmetic</h1> <hr> This example illustrates basic Expression Language arithmetic. Addition (+), subtraction (-), multiplication (*), division (/ or div), and modulus (% or mod) are all supported. Error conditions, like division by zero, are handled gracefully. <br> <blockquote> <code> <table border="1"> <thead> <td><b>EL Expression</b></td> <td><b>Result</b></td> </thead> <tr> <td>\${1}</td> <td>${1}</td> </tr> <tr> <td>\${1 + 2}</td> <td>${1 + 2}</td> </tr> <tr> <td>\${1.2 + 2.3}</td> <td>${1.2 + 2.3}</td> </tr> <tr> <td>\${1.2E4 + 1.4}</td> <td>${1.2E4 + 1.4}</td> </tr> <tr> <td>\${-4 - 2}</td> <td>${-4 - 2}</td> </tr> <tr> <td>\${21 * 2}</td> <td>${21 * 2}</td> </tr> -38-
<tr> <td>\${3/4}</td> <td>${3/4}</td> </tr> <tr> <td>\${3 div 4}</td> <td>${3 div 4}</td> </tr> <tr> <td>\${3/0}</td> <td>${3/0}</td> </tr> <tr> <td>\${10%4}</td> <td>${10%4}</td> </tr> <tr> <td>\${10 mod 4}</td> <td>${10 mod 4}</td> </tr> <tr> <td>\${(1==2) ? 3 : 4}</td> <td>${(1==2) ? 3 : 4}</td> </tr> </table> </code> </blockquote> </body> </html>
-39-
OUTPUT: JSP 2.0 Expression Language - Basic Arithmetic EL Expression ${1} ${1 + 2} ${1.2 + 2.3} ${1.2E4 + 1.4} ${-4 - 2} ${21 * 2} ${3/4} ${3 div 4} ${3/0} ${10%4} ${10 mod 4} ${(1==2) ? 3 : 4} Result 1 3 3.5 12001.4 -6 42 0.75 0.75 Infinity 2 2 4
-40-
Source Code for functions.jsp <html> <head> <title>JSP 2.0 Expression Language - Functions</title> </head> <body> <h1>JSP 2.0 Expression Language - Functions</h1> <hr> An upgrade from the JSTL expression language, the JSP 2.0 EL also allows for simple function invocation. Functions are defined by tag libraries and are implemented by a Java programmer as static methods. <blockquote> <u><b>Change Parameter</b></u> <form action="functions.jsp" method="GET"> foo = <input type="text" name="foo" value="${fn:escapeXml(param["foo"])}"> <input type="submit"> </form> <br> <code> <table border="1"> <thead> <td><b>EL Expression</b></td> <td><b>Result</b></td> </thead> <tr> <td>\${param["foo"]}</td> <td>${fn:escapeXml(param["foo"])} </td> </tr> <tr> <td>\${my:reverse(param["foo"])}</td> <td>${my:reverse(fn:escapeXml(param["foo"]))} </td> </tr> <tr> <td>\${my:reverse(my:reverse(param["foo"]))}</td> <td>${my:reverse(my:reverse(fn:escapeXml(param["foo"])))} </td> </tr> <tr> <td>\${my:countVowels(param["foo"])}</td> <td>${my:countVowels(fn:escapeXml(param["foo"]))} </td> </tr> </table> </code> </blockquote> </body> </html> -41-
Source Code for Calendar Example <HTML> <HEAD><TITLE> Calendar: A JSP APPLICATION </TITLE></HEAD> <BODY BGCOLOR="white"> <%@ page language="java" import="cal.*" %> <jsp:useBean id="table" scope="session" class="cal.TableBean" /> <% table.processRequest(request); if (table.getProcessError() == false) { %> <!-- html table goes here --> <CENTER> <TABLE WIDTH=60% BGCOLOR=yellow CELLPADDING=15> <TR> <TD ALIGN=CENTER> <A HREF=cal1.jsp?date=prev> prev </A> <TD ALIGN=CENTER> Calendar:<%= table.getDate() %></TD> <TD ALIGN=CENTER> <A HREF=cal1.jsp?date=next> next </A> </TR> </TABLE> <!-- the main table --> <TABLE WIDTH=60% BGCOLOR=lightblue BORDER=1 CELLPADDING=10> <TR> <TH> Time </TH> <TH> Appointment </TH> </TR> <FORM METHOD=POST ACTION=cal1.jsp> <% for(int i=0; i<table.getEntries().getRows(); i++) { cal.Entry entr = table.getEntries().getEntry(i); %> <TR> <TD> <A HREF=cal2.jsp?time=<%= entr.getHour() %>> <%= entr.getHour() %> </A> </TD> <TD BGCOLOR=<%= entr.getColor() %>> -42-
<% out.print(util.HTMLFilter.filter(entr.getDescription())); %> </TD> </TR> <% } %> </FORM> </TABLE> <BR> <!-- footer --> <TABLE WIDTH=60% BGCOLOR=yellow CELLPADDING=15> <TR> <TD ALIGN=CENTER> <% out.print(util.HTMLFilter.filter(table.getName())); %> : <% out.print(util.HTMLFilter.filter(table.getEmail())); %> </TD> </TR> </TABLE> </CENTER> <% } else { %> <font size=5> You must enter your name and email address correctly. </font> <% } %> </BODY> </HTML>
-43-
OUT PUT Please Enter the following information: Name Email prev Time 8am 9am 10am 11am 12pm 1pm 2pm 3pm 4pm 5pm 6pm 7pm Calendar:5/29/2008 Appointment next
None None None None None None None None None None None None
pvr : [email protected]
Calender2 -44-
<HTML> <HEAD><TITLE> Calendar: A JSP APPLICATION </TITLE></HEAD> <BODY BGCOLOR="white"> <jsp:useBean id="table" scope="session" class="cal.TableBean" /> <% String time = request.getParameter ("time"); %> <FONT SIZE=5> Please add the following event: <BR> <h3> Date <%= table.getDate() %> <BR> Time <%= util.HTMLFilter.filter(time) %> </h3> </FONT> <FORM METHOD=POST ACTION=cal1.jsp> <BR> <BR> <INPUT NAME="date" TYPE=HIDDEN VALUE="current"> <BR> <INPUT NAME="time" TYPE=HIDDEN VALUE=<%= util.HTMLFilter.filter(time) %> <BR> <h2> Description of the event <INPUT NAME="description" TYPE=TEXT SIZE=20> </h2> <BR> <INPUT TYPE=SUBMIT VALUE="submit"> </FORM> </BODY> </HTML>
-45-
PROGRAM FOR JSP-Servlet-JSP Source Code for JSP calling servlet <HTML> <body bgcolor="white"> <!-- Forward to a servlet --> <jsp:forward page="/servletToJsp" /> </html> OR Source Code for Servlet calling JSP import javax.servlet.*; import javax.servlet.http.*; public class servletToJsp extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) { try { // Set the attribute and Forward to hello.jsp request.setAttribute ("servletName", "servletToJsp"); getServletConfig().getServletContext().getRequestDispatcher("/jsptoserv/hello.jsp").forward(req uest, response); } catch (Exception ex) { ex.printStackTrace (); } } } OUT PUT I have been invoked by servletToJsp Servlet.
-46-
7. Source Code for HelloWorld Example import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Hello World!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello World!</h1>"); out.println("</body>"); out.println("</html>"); } } OUTPUT: Hello World!
-47-
Source Code for Session Example import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class SessionExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(true); // print session info Date created = new Date(session.getCreationTime()); Date accessed = new Date(session.getLastAccessedTime()); out.println("ID " + session.getId()); out.println("Created: " + created); out.println("Last Accessed: " + accessed); // set session info if needed String dataName = request.getParameter("dataName"); if (dataName != null && dataName.length() > 0) { String dataValue = request.getParameter("dataValue"); session.setAttribute(dataName, dataValue); } // print session contents Enumeration e = session.getAttributeNames(); while (e.hasMoreElements()) { String name = (String)e.nextElement(); String value = session.getAttribute(name).toString(); out.println(name + " = " + value); } } }
-48-
OUTPUT:Sessions Example Session ID: E55B7AE87EEC8556A084BBFF47E96155 Created: Thu May 29 12:00:08 IST 2008 Last Accessed: Thu May 29 12:00:43 IST 2008 The following data is in your session: ANANTH = 1234 RAM = 4321 Name of Session Attribute: Value of Session Attribute: GET based form: Name of Session Attribute: Value of Session Attribute: URL encoded
-49-
Using Cookies Now, let's develop a servlet that illustrates how to use cookies. The servlet is invoked when a form on a Web page is submitted. The example contains three files, as summarized here: File Description AddCookie.htm Allows a user to specify a value for the cookie named M yCookie AddCookieServlet.java P rocesses the submission of AddCookie.htm GetCookiesServlet.java D isplays cookie values The HTML source code for AddCookie.htm is shown in the following listing. This page contains a text field in which a value can be entered. The page also includes a submit button. When this button is pressed, the value in the text field is sent to AddCookieServlet via an HTTP POST request. <html> <body> <center> <form name="Form1" method="post" action="http://localhost:8080/servlet/AddCookieServlet"> <B>Enter a value for MyCookie:</B> <input type=textbox name="data" size=25 value=""> <input type=submit value="Submit"> </form> </body> </html> The source code for AddCookieServlet.java is shown in the following listing. It gets the value of the parameter named "data". It then creates a Cookie object that has the name "MyCookie" and contains the value of the "data" parameter. The cookie is then added to the header of the HTTP response via the addCookie( ) method. A feedback message is then written to the browser. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class AddCookieServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get parameter from HTTP request String data = request.getParameter("data"); Cookie cookie = new Cookie("MyCookie", data); // Add cookie to HTTP response response.addCookie(cookie); -50-
// Write output to browser response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>MyCookie has been set to"); pw.println(data); pw.close(); } } The source code for GetCookiesServlet.java is shown in the following listing. It invokes the getCookies( ) method to read any cookies that are included in the HTTP GET request. The names and values of these cookies are then written to the HTTP response. Observe that the getName( ) and getValue( ) methods are called to obtain this information. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class GetCookiesServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get cookies from header of HTTP request Cookie[] cookies = request.getCookies(); // Display these cookies response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>"); for(int i = 0; i < cookies.length; i++) { String name = cookies[i].getName(); String value = cookies[i].getValue(); pw.println("name = " + name + "; value = " + value); } pw.close(); } } 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 getValue( ) 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 putValue( ) method is called to bind the name "date" to this object. import java.io.*; -51-
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.getValue("date"); if(date != null) { pw.print("Last access: " + date + "<br>"); } // Display current date/time date = new Date(); hs.putValue("date", date); pw.println("Current date: " + date); }}
-52-
Source Code for Cookie Example import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class CookieExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); // print out cookies Cookie[] cookies = request.getCookies(); for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; String name = c.getName(); String value = c.getValue(); out.println(name + " = " + value); } // set a cookie String name = request.getParameter("cookieName"); if (name != null && name.length() > 0) { String value = request.getParameter("cookieValue"); Cookie c = new Cookie(name, value); response.addCookie(c); } } }
-53-
OUTPUT: Cookies Example Your browser is sending the following cookies: Cookie Name: ANANTH Cookie Value: 876543 Cookie Name: RAM Cookie Value: 1234567 You just sent the following cookie to your browser: Name: GURUNANAK Value: 5000060 Create a cookie to send to your browser Name: Value:
-54-
Write web program to implement Hello word <Web-app> <servlet> <servlet-name>simple servlet </servlet-name> <servlet-class> Hello Word</servlet-class> </servlet> <servlet-mapping> <servlet-name>simple servlet</servlet-name> <un-pattern>servlet<un-pattern> </Web-app> OUTPUT : Hello Word Program for Simple Servlet import java.io.*; import javax.servlet.*; public class simpleServlet extends GenericServlet{ public void service(ServletRequest request,ServletResponse response) throws ServletException,IOException{ res.setcontenttype Type("TEXT/HTML"); PrintWriter out=res.getwriter(); out.println("<html>"); out.println("<head>"); out.println("<title>this is simple servlet</title>); out.println("</head"); out.println("</body>"); out.println(<center<b>testing servelet</b></center); out.println(</body>); out.println(</html>); out.close(); } }
-55-
Program for Postparmeter Servlet import java.io.*; import java.util.*; import javax.servlet.*; public class PostParametersServlet extends GenericServlet{ public void service(ServletRequest request,ServletResponse response) throws ServletException,IOException{ //Get printwriter PrintWriter pw=response.getWriter(); //Get enumeration of parameternames Enumeration e=request.getParameterNames(); //Display parameter names and values while(e.hasMoreElements()) { String pname=(String)e.nextElement(); pw.print(pname+"="); String pvalue=request.getParameter(pname); pw.println(pvalue); } pw.close(); } }
-56-
7 Implement the Hello World! program using JSP Struts Framework. Source Code for the Hello World Tag Example <html> <head> <title>JSP 2.0 Examples - Hello World SimpleTag Handler</title> </head> <body> <h1>JSP 2.0 Examples - Hello World SimpleTag Handler</h1> <hr> <p>This tag handler simply echos "Hello, World!" It's an example of a very basic SimpleTag handler with no body.</p> <br> <b><u>Result:</u></b> <mytag:helloWorld/> </body> </html> OUT PUT This tag handler simply echos "Hello, World!" It's an example of a very basic SimpleTag handler with no body. Result: Hello, world!
-57-
Program : Deposit <HTML> <HEAD> <P ALIGN="RIGHT"><A HREF="TRANSACTIONS.HTML">HOME</A></P> <TITLE> DEPOSIT DETAILS </TITLE><BR><BR><BR><BR><BR> <CENTER><FONT SIZE="6" COLOR="#0000CC"> <FORM METHOD=POST ACTION="http://localhost:8080/bank/resourses/Deposit.com"> DEPOSIT DETAILS</FONT><BR><BR><BR> ACCOUNT NO.:<INPUT TYPE="text" NAME="ACCOUNTNO"><BR><BR> AMOUNT:<INPUT TYPE="text" NAME="AMT"><BR><BR> <INPUT TYPE="submit" VALUE="SUBMIT"> <INPUT TYPE="reset"> </FORM> </CENTER> </HEAD> <BODY> </BODY> </HTML> OUTPUT DEPOSIT DETAILS ACCOUNT NO.: AMOUNT:
-58-
Program : Transactions <HTML> <HEAD> <TITLE> TRANSACTIONS</TITLE><BR><BR><BR> <FORM METHOD=POST ACTION="" NAME="TRANSACTION"> <CENTER> <FONT SIZE="6"COLOR="#0000CC"> TRANSACTIONS </FONT><BR><BR><BR><BR> <UL> <LI><A HREF="VIEWBAL.HTML">VIEW BALANCE</A><BR><BR> <LI><A HREF="DEPDETAILS.HTML">DEPOSIT</A><BR><BR> <LI><A HREF="WITHDETAILS.HTML">WITHDRAW</A><BR><BR> <LI><A HREF="CLOSING.HTML">CLOSE AN ACCOUNT</A><BR><BR> <LI><A HREF="USERDETAILS.HTML">EXIT</A></UL> </CENTER> </FORM> </HEAD> </BODY> </BODY> </HTML> OUTPUT :
TRANSACTIONS
VIEW BALANCE
DEPOSIT WITHDRAW
CLOSE AN ACCOUNT
EXIT
-59-
Program : User Details <HTML> <HEAD> <TITLE> USER DETAILS </TITLE> <CENTER><BR><BR><BR><BR><BR> <FONT SIZE="6" COLOR="#0000CC">USER DETAILS</FONT><BR><BR><BR> <FORM METHOD=POST ACTION=""> USERNAME: <INPUT TYPE="text" NAME="UN"><BR><BR> PASSWORD: <INPUT TYPE="text" NAME="PW"><BR><BR><BR> INVALID USERNAME OR PASSWORD. <INPUT TYPE="submit" VALUE="SUBMIT"><BR><BR><BR> Click here to Create<A HREF="NEWACC.HTML">NEW USER</A></CENTER> </FORM> </HEAD> <BODY> </BODY> </HTML> Output:
USER DETAILS USERNAME: PASSWORD: INVALID USERNAME OR PASSWORD. Click here to Create :NEW USER
<HTML> <HEAD> <P ALIGN="RIGHT"><A HREF="TRANSACTIONS.HTML">HOME</A></P> <TITLE> WITHDRAWAL DETAILS </TITLE><BR><BR><BR><BR><BR> <CENTER><FONT SIZE="6" COLOR="#0000CC"> WITHDRAWAL DETAILS</FONT><BR><BR><BR> <FORM METHOD=POST ACTION="http://localhost:8080/bank/resourses/Withdraw.com"> ACCOUNT NO.:<INPUT TYPE="text" NAME="ACCOUNTNO"><BR><BR> AMOUNT:<INPUT TYPE="text" NAME="AMT"><BR><BR> <INPUT TYPE="submit" VALUE="SUBMIT"> <INPUT TYPE="reset"> </FORM> </CENTER> </HEAD> <BODY> </BODY> </HTML>
Output:
WITHDRAWAL DETAILS ACCOUNT NO.: AMOUNT:
-61-
Program : Closing <HTML> <HEAD> <P ALIGN="RIGHT"><A HREF="TRANSACTIONS.HTML">HOME</A></P> <TITLE> CLOSING ACCOUNT </TITLE><BR><BR><BR><BR><BR> <CENTER><FONT SIZE="6" COLOR="#0000CC"> CLOSING ACCOUNT</FONT><BR><BR><BR> <FORM METHOD=POST ACTION="http://localhost:8080/bank/resourses/Close.com"> ACCOUNT NO.:<INPUT TYPE="text" NAME="ACCOUNTNO"><BR><BR> <INPUT TYPE="submit" VALUE="SUBMIT"> <INPUT TYPE="reset"> </FORM> </CENTER> </HEAD> <BODY> </BODY> </HTML> Output: CLOSING ACCOUNT ACCOUNT NO.:
-62-
Program : User Account <HTML> <HEAD> <TITLE> NEW ACCOUNT FORM </TITLE> <CENTER><BR><FONT SIZE="6" COLOR="#0000CC"> NEW ACCOUNT FORM</FONT><BR><BR> <FORM METHOD=POST ACTION="http://localhost:8080/bank/Signup.com"> <TABLE> <TR> <TD>NAME:</TD> <TD><INPUT TYPE="text" NAME="NAME"></TD><BR> </TR> <TR> <TD>AGE:</TD> <TD><INPUT TYPE="text" NAME="AGE">YRS</TD><BR> </TR> <TR> <TD>OCCUPATION:</TD> <TD><SELECT NAME="OCCUPATION"> <OPTION VALUE="" SELECTED>BUSINESS</OPTION> <OPTION VALUE="">STUDENT</OPTION> </SELECT><BR></TD> </TR> <TR> <TD>ADDRESS:</TD> <TD><TEXTAREA NAME="ADDRESS" ROWS="3" COLS="20"></TEXTAREA><BR></TD> </TR> <TR> <TD>PHONE-NUMBER:</TD> <TD><INPUT TYPE="text" NAME="PHONE"><BR></TD> </TR> <TR> <TD>ACCOUNT TYPE:</TD> <TD><SELECT NAME="ACCTYPE"> <OPTION VALUE="" SELECTED>SAVING</OPTION> <OPTION VALUE="">CURRENTACC </SELECT><BR></TD> </TR> <TR> <TD>OPENING-DATE:</TD> <TD><INPUT TYPE="text" NAME="OPENDATE"><BR></TD> </TR> <TR> <TD>USERNAME:</TD> <TD><INPUT TYPE="text" NAME="USERNAME"><BR></TD> </TR> -63-
<TR> <TD>PASSWORD:</TD> <TD><INPUT TYPE="text" NAME="PASSWORD"><BR></TD> </TR> <TR> <TD>REENTER PASSWORD:</TD> <TD><INPUT TYPE="text" NAME="REPWD"></TD> </TR> <TR><BR> <TD><INPUT TYPE="submit" VALUE="SUBMIT" ></TR><BR><BR><BR> <TD><INPUT TYPE="reset"></TD> </FORM> </CENTER> </HEAD> <BODY> </BODY> </HTML> Output: NEW ACCOUNT FORM NAME: AGE: OCCUPATION: ADDRESS: PHONE-NUMBER: ACCOUNT TYPE: OPENING-DATE: USERNAME: PASSWORD: REENTER PASSWORD: YRS
Program : User Details <HTML> <HEAD> <TITLE> USER DETAILS </TITLE> <CENTER><BR><BR><BR><BR><BR> <FONT SIZE="6" COLOR="#0000CC">USER DETAILS</FONT><BR><BR><BR> <FORM METHOD=POST ACTION="http://localhost:8080/bank/Login.com"> -64-
USERNAME: <INPUT TYPE="text" NAME="UN"><BR><BR> PASSWORD: <INPUT TYPE="text" NAME="PW"><BR><BR><BR> <INPUT TYPE="submit" VALUE="SUBMIT"><BR><BR><BR> Click here to Create<A HREF="NEWACC.HTML">NEW USER</A></CENTER> </FORM> </HEAD> <BODY> </BODY> </HTML> Output: USER DETAILS USERNAME: PASSWORD:
-65-
Program : View Balance <HTML> <HEAD> <P ALIGN="RIGHT"><A HREF="TRANSACTIONS.HTML">HOME</A></P> <TITLE>VIEW BALANCE</TITLE><BR><BR><BR><BR><BR><BR><BR> <FORM METHOD=POST ACTION="http://localhost:8080/bank/Balance.com" NAME="BAL"> <CENTER><FONT SIZE="6" COLOR="#0000CC"> VIEW BALANCE</FONT><BR><BR><BR><BR> ACCOUNT NUMBER: <INPUT TYPE="text" NAME="ACCNO"><BR><BR><BR> <INPUT TYPE="submit" VALUE="SUBMIT"> </CENTER> </FORM> </HEAD> <BODY> </BODY> </HTML> Output : VIEW BALANCE
ACCOUNT NUMBER:
-66-
8. Enter into the following text box "34 22 23 435 33 2 1 43 54", for example, and press the sort numerically button. Or, try entering "this is a test", and press the sort alpha button. <script type="text/javascript"> function sortit(a,b){ return(a-b) } function sortvalues(param){ var inputvalues=document.sorter.sorter2.value.split(" ") if (param==0) //if sort alphabetically inputvalues.sort() else //else if sort numerically inputvalues.sort(sortit) document.sorter.sorter2.value='' for (i=0;i<inputvalues.length-1;i++) document.sorter.sorter2.value=document.sorter.sorter2.value+inputvalues[i]+" " document.sorter.sorter2.value+=inputvalues[inputvalues.length-1] } </script> <form name="sorter"> <p> <textarea rows="10" name="sorter2" cols="50" wrap="virtual"></textarea><br> <input type="button" value="Sort alphabetically" onClick="sortvalues(0)"> <input type="button" value="Sort numerically" onClick="sortvalues(1)"> <input type="reset" value="Reset"> </form>
-67-
Output
-68-
Additional Programs s.no 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 Programs Program for implementation of Fonts Program for implementation of Table Program for implementation of List Program for addition of two nos in java script Program for implementation of Switch case Program to find maximum of 3 nos Program for Entering a password Program for implementation of Thambola Program for Factorial Program for Addition of two Matrices Program for Online Exam Program for Bubble Sort Program for implementation of Linear Search Program for displaying an image on mouse click Program for Exhibiting Blending Effect Program Code To Exhibit X-ray Effect Program Code To Exhibit Shadow Effect Program Code To Exhibit Wave Effect Program for implementing Animation Program To display background Sound Program To add video file Using JavaScript sort given array in ascending and descending order. Page no 23 24 27 28 30 33 35 38 40 42 48 53 55 59 61 63 65 67 69 72 76
-69-
AIM
Write a script for selection sort. PROGRAM <html> <head> <title> Sort </title> <script language="Javascript"> var b,i,j,temp; var a; a=[]; document.write("Enter array"); for(i=0;i<5;i++) { b=prompt("enter array element=","0"); a[i]=parseInt(b); } for(i=0;i<5;i++) { document.write("<br>"+a[i]); } document.write("<br>Sorted array is"); -70-
for(i=0;i<5;i++) { for(j=0;j<5;j++) { if(a[i]<a[j]) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } for(i=0;i<5;i++) { document.write("<br>"+a[i]); } </script> </head></html>
-71-
OUTPUT
-72-
AIM Write Java Script that inputs three integers from the user and outputs their sum, average, largest. Use alert dialog box to display results. PROGRAM <html> <head> <title> MAX </title>
<script language="javascript"> var a,b,c,n1,n2,n3,m1,m2,sum,avg; a=prompt("enter 1st no="," "); b=prompt("enter 2nd no="," "); c=prompt("enter 3rd no="," "); n1=parseInt(a); n2=parseInt(b); n3=parseInt(c); sum=n1+n2+n3; avg=sum/3; m1=Math.max(n1,n2); m2=Math.max(n3,m1); alert("the sum is= "+sum); alert("the avg is= "+m2); alert("the max no is "+m2); </script> </head></html>
-73-
OUTPUT
-74-
AIM Write a script to write word equivalent of a check amount. PROGRAM <html> <HEAD> <SCRIPT LANGUAGE="JavaScript"> var checkflag = "false";
function check(field) { if (checkflag == "false") { for (i = 0; i < field.length; i++) { field[i].checked = true;} checkflag = "true"; return "Uncheck All"; } else { for (i = 0; i < field.length; i++) { field[i].checked = false; -75-
</script> </HEAD> <BODY> <center> <form name=myform action="" method=post> <table> <tr><td> <b>Your Favorite Scripts & Languages</b><br> <input type=checkbox name=list value="1">Java<br> <input type=checkbox name=list value="2">JavaScript<br> <input type=checkbox name=list value="3">ASP<br> <input type=checkbox name=list value="4">HTML<br> <input type=checkbox name=list value="5">SQL<br> <br> <inputtype=button value="Check All" </td></tr> </table> -76onClick="this.value=check(this.form.list)">
OUTPUT
-77-
AIM Practice writing css rules PROGRAM <html> <head> <title>style sheets</title> <style type=text/css></head> em{backgroundcolor:#8000ff;color=white} h1{font family:Lucida console;color:red} p{font size:30pt} sp{color:red} </style> </head> <body> <h2class=sp>testing</h2> <em><h1>test</h1></em> <em>test1</em> <p>test2</p> </body> </html>
-78-
-79-
AIM Write a web page that displays grades of a student. PROGRAM <html> <head> <title> STUDENT GRADES </title> <script language="java script"> var a,n,b,c,sum=0,avg=0; b=prompt("enter student no=","0"); n=parseInt(b); while(n<=10) { a=prompt("enter ur grade=","0"); c=parseInt(a); sum=sum+c; n++; } avg=sum/n; document.write("avg is"+avg); </script> </head></html>
-80-
AIM Write a function that responds to a click anywhere on the page. PROGRAM <html> <body> <center> [<a href="/" onMouseOver="document.bgColor='Green'">GREEN</a>] [<a href="/" onMouseOver="document.bgColor='Red'">RED</a>] [<a href="/" onMouseOver="document.bgColor='orange'">orange</a>] [<a href="/" onMouseOver="document.bgColor='green'">brightgreen</a>] [<a href="/" onMouseOver="document.bgColor='seagreen'">seagreen</a>] </center> </body> </html>
-81-
OUTPUT
-82-
AIM Program for implementation of Fonts PROGRAM <html> <head> <title>Font Test</title> </head> <body> <br><b><font face=Times New Roman>Font Check</font></b> <br><i><font face=Times New Roman><font size=4><font color=black>All Operations</font></i> <br><i><b>Bold italic check</b></i> </body> </html>
-83-
AIM Program for creating a table PROGRAM <! code to show the use of tables> <html> <head> <title> Using Tables</title> </head> <body><center> <table border="1" width="5" height="5" bordercolor="red"> <caption> Student Marks </caption> <thead> <tr> <th>Name</th> <th>Marks</th> </tr> </thead> <tbody> <tr> <td>alok</td> <td>90</td> </tr> <tr> -84-
<td>anuj</td> <td>90</td> </tr> <tr> <td>ankush</td> <td>90</td> </tr> </tbody> <tfoot> <tr> <th>Avg Marks</th> <th>90</th> </tr> </tfoot> </body> </html>
-85-
OUTPUT
-86-
AIM Program for implementation of List PROGRAM <html> <body> <ul> <li>list1</li> </ul><ul> <li>Gnec</li> <ol> <li>IT</li> <li>CSE</li> <li>ECE</li> </ol></ol></ul></body></html> OUTPUT list1 Gnec 1. IT 2. CSE 3. ECE
-87-
AIM Write a java script to compute addition of two numbers PROGRAM <html> <head> <title> Java Script Add </title> <script language="java script"> alert("Addition \n of two numbers!"); var num1, num2,n1,n2,sum; num1=window. prompt("Enter the first number","0"); num2=window. prompt("Enter the second number","0"); n1=parseInt(num1); n2=parseInt(num2); sum=n1+n2; alert("sum is"+sum); </script> </head> <body>
OUTPUT
Addition of 10 and 20 : 30
-89-
AIM Program for implementation of Switch case PROGRAM <html> <head> <title> USING THE SWITCH STATEMENT </title> <script language ="Javascript"> var num=true;var choice,ch,ft,lt,head; choice=window.prompt(" UNDERLINED ......","1"); ch =parseInt(choice); switch(ch) { case 1: ft="<b>"; lt="</b>"; head="<h1> This is in BOLD </h1>"; break; case 2: ft="<i>"; lt="</i>"; head="<h1> This is in ITALICS </h1>"; break; -901. BOLD 2. ITALICS 3.
case 3:
default : num=false; break; } if(num==true) document.write(head+ft+" <h1>Text </h1>"+lt); else document.write(" <h1>Wrong Choice ! try again."); </script> </head> <body> </body> </html> OUTPUT
-91-
AIM Program to find maximum of 3 nos PROGRAM <html> <head> <title> Maximum of Number </title> <script language ="Javascript"> var a,b,c,a1,b1,c1,max1,max2; a=window.prompt("Enter first number >>","0"); b=window.prompt("Enter second number >>","1"); c=window.prompt("Enter third number >>","2");
a1=parseInt(a); b1=parseInt(b); c1=parseInt(c); max1=Math.max(a,b); max2=Math.max(max1,c); document.write("<br><br><br><center><h1>Maximum number of "+a1+", "+b1+" and "+c1+" is "+max2); </script> <body></body> </html> -92-
-93-
Output
-94-
AIM Program for Entering a password PROGRAM <html> <head> <title>event clicking</title> <script language="javascript"> function passwordCheck() { var pw=ole.pw.value; var cpw=ole.cpw.value; if(pw!=cpw) window.alert("Re-enter your password"); } </script></head>
<center> <body font size=5 bgcolor="cyan" leftmargin=120 topmargin=120 > <Form id="ole" onSubmit="passwordCheck(this)">
-95-
PASSWORD: &nb sp; <input type=password name="pw"size=10 max length=8 > </input> <br><br><br> CONFIRM PASSWORD &nbs p; <input type=password name="cpw"size=10 max length=8 > </input> <br><br><br> <input type="submit" name="sub" value="submit"> <input type="reset" name="rt" value="reset"></center </body> </html>
-96-
OUTPUT
-97-
AIM Program for implementation of Thambola PROGRAM <html> <head> <title> J Script </title> <script language="javascript"> var value; alert("thambola"); document.writeln("<table border=1 width=50% align=center> ");
for(var i=1;i<=15;i++) {
-98-
OUTPUT
-99-
AIM Program for Factorial PROGRAM <html> <head><u><center><b>RECURSIVE FACTORIAL</b><br></u> <title> factorial </title> <script lang="javascript"> var i,fact,a,n; a=prompt("enter any no","0"); n=parseInt(a); for (i=1;i<=n;i++) { res=fact(i); document.writeln("<br> THE FACTORIAL OF "+i+" IS >> "+res); } function fact(x) { if(x==0 || x==1) return(1); else return(x*fact(x-1)); -100-
RECURSIVE FACTORIAL THE FACTORIAL OF 1 IS >> 1 THE FACTORIAL OF 2 IS >> 2 THE FACTORIAL OF 3 IS >> 6 THE FACTORIAL OF 4 IS >> 24 THE FACTORIAL OF 5 IS >> 120
-101-
AIM Program for addition of two matrices PROGRAM <html> <head> <title>Array Addition</title> <script language="javascript"> var a,n,i,j,b,c; a=[[],[]]; b=[[],[]]; c=[[],[]]; n=parseInt(window.prompt("Enter the array size"," ")); window.alert("Enter the elements in the first array"); for (i=0;i<n;i++) { for (j=0;j<n;j++) { a[i][j]=parseInt(window.prompt("Enter the element","")); } } window.alert("Enter the elements in the second array"); for (i=0;i<n;i++) { -102-
for (j=0;j<n;j++) { b[i][j]=parseInt(window.prompt("Enter the element","")); } } document.writeln("<br>The elements of Ist Matrix are.."); for (i=0;i<n;i++) { for (j=0;j<n;j++) { document.writeln(a[i][j]); } } document.writeln("<br>The elements of IInd Matrix are.."); for (i=0;i<n;i++) { for (j=0;j<n;j++) { document.writeln(b[i][j]); } } for (i=0;i<n;i++) { -103-
for (j=0;j<n;j++) { c[i][j]=a[i][j]+b[i][j]; } } document.writeln("<br>The addition of matrices is:"); for (i=0;i<n;i++) { for (j=0;j<n;j++) {
-104-
-105-
-106-
The elements of Ist Matrix are.. 1 1 1 1 The elements of IInd Matrix are.. 1 1 1 1 The addition of matrices is: 2 2 2 2
-107-
AIM Program for Online Exam PROGRAM <html> <head> <title> Exam </title> <script language="Javascript"> function exam(form) { var i=0; if(form.one[2].checked) i=i+1; if(form.three[0].checked) i=i+1; if(form.four[0].checked) i=i+1; if(form.five[1].checked) i=i+1; window.alert("score is"+i); } </script> </head> <body> -108-
<form onSubmit="exam(this)"> <center>Online exam</center> <P> <h1>1)Which is platform independent language</h1> <input type="radio" name="one" value="c++"> <label>c++</label> <input type="radio" name="one" value="c"> <label>c</label> <input type="radio" name="one" value="java"> <label>Java</label> <input type="radio" name="one" value="basic"> <label>BASIC</label> </P> <P> <h1>2)Which is class of all class in java</h1> <input type="radio" name="three" value="object"> <label>Object</label> <input type="radio" name="three" value="math"> <label>Math</label> <input type="radio" name="three" value="system"> <label>System</label> <input type="radio" name="three" value="graphic"> <label>Graphic</label> -109-
</P> <P> <h1>3)Frame package is in which package</h1> <input type="radio" name="four" value="awt"> <label>AWT</label> <input type="radio" name="four" value="applet"> <label>Applet</label> <input type="radio" name="four" value="lang"> <label>Lang</label> <input type="radio" name="four" value="swing"> <label>Swing</label> </P> <P> <h1>4)Java does not support</h1> <input type="radio" name="five" value="inheritance"> <label>Inheritance</label> <input type="radio" name="five" value="multiple inheritance"> <label>Multiple inheritance</label> <input type="radio" name="five" value="polymorphism"> <label>Polymorphism</label> <input type="radio" name="five" value="encryption"> <label>Encryption</label> </P> <P><center> -110-
<input type="submit" value="submit"> <input type="reset" name="reset" value="reset"> </center> OUTPUT Online exam 1)Which is platform independent language c++ c Java BASIC 2)Which is class of all class in java Object Math System Graphic 3)Frame package is in which package AWT Applet Lang Swing 4)Java does not support Inheritance Multiple inheritance Polymorphism Encryption </p> </body></html>
AIM -111-
Program for Bubble Sort PROGRAM <html> <head> <title>Bubble Sort</title> <script language="JavaScript"> var a=[3,5,2,9,1,8] var t,n=6; for( var i=0;i<n;i++) { for(var j=0;j<n-1;j++) { if(a[j]>a[j+1]) { t=a[j]; a[j]=a[j+1]; a[j+1]=t; } } } document.write("<h1>The sorted order is: "); for(i=0;i<n;i++) { -112-
document.write(a[i]); document.write(" "); } </script> </head> <body topmargin=50 leftmargin=100></body> </html> OUTPUT The sorted order is: 1 2 3 5 8 9
-113-
AIM Program for implementation of Linear Search PROGRAM <html> <head> <title>Array Addition</title> <script language="javascript"> var flag=0,a,n,key,i var a=new Array(10); n=parseInt(window.prompt("Enter the size of the array","")); window.alert("Enter the elements in the array"); for (i=0;i<n;i++) { a[i]=parseInt(window.prompt("Enter the element ","")); } key=parseInt(window.prompt("Enter the searching element","")); for (i=0;i<n;i++) { if (a[i]==key) { flag=1; window.alert(" element is found at location "+(i+1)); } -114-
found");//document.writeln("The element is not found"); </script> </head> <body bgcolor="pink"> </body> </html>
-115-
OUTPUT
-116-
-117-
<html> <head> <title>onclick image</title> </head> <body leftmargin=100 topmargin=100 bgcolor="#111111"> <img name="images" width=200 height=200 src=1.gif "><p> <form><h3> <input type="button" value="image1" onClick="document.images.src='1.gif' "> <input type="button" value="image2" onClick="document.images.src='2.gif' "> <input type="button" value="image3" onClick="document.images.src='3.gif' "> </form></h3></body></html>
-118-
OUTPUT
-119-
AIM Program Code To Exhibit Blending Effect PROGRAM <html> <head> <title> J Script </title> <script language="javascript"> function blendOut() { //textInput.filters("blendTrans").apply(); //textInput.style.visibility="hidden"; textInput.filters("blendTrans").play(); } </script> </head> <body> <div id="textInput" onmouseover="blendOut()" style="width:100; filter:blendTrans(duration=5)"> <h1> </div> </body> </html> MULTI MEDIA </h1>
-120-
OUTPUT
-121-
VIVA questions & Answers 1. What is the difference between procedural and object-oriented programs?- a) In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code. b) In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible with in the object and which in turn assures the security of the code. 2. What are Encapsulation, Inheritance and Polymorphism?- Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse. Inheritance is the process by which one object acquires the properties of another object. Polymorphism is the feature that allows one interface to be used for general class actions. 3. What is the difference between Assignment and Initialization?- Assignment can be done as many times as desired whereas initialization can be done only once. 4. What is OOPs?- Object oriented programming organizes a program around its data, i. e. , objects and a set of well defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code. 5. What are Class, Constructor and Primitive data types?- Class is a template for multiple objects with similar features and it is a blue print for objects. It defines a type of object according to the data the object can hold and the operations the object can perform. Constructor is a special kind of method that determines how an object is initialized when created. Primitive data types are 8 types and they are: byte, short, int, long, float, double, boolean, char. 6. What is an Object and how do you allocate memory to it?- Object is an instance of a class and it is a software unit that combines a structured set of data with a set of operations for inspecting and manipulating that data. When an object is created using new operator, memory is allocated to it. 7. What is the difference between constructor and method?- Constructor will be automatically invoked when an object is created whereas method has to be called explicitly. 8. What are methods and how are they defined?- Methods are functions that operate on instances of classes in which they are defined. Objects can communicate with each other using methods and can call methods in other classes. Method definition has four parts. They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method. A methods signature is a combination of the first three parts mentioned above. 9. What is the use of bin and lib in JDK?- Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all packages. 10. What is casting?- Casting is used to convert the value of one type to another. 11. How many ways can an argument be passed to a subroutine and explain them?- An argument can be passed in two ways. They are passing by value and passing by reference. Passing by value: This method copies the value of an argument into the formal -122-
parameter of the subroutine. Passing by reference: In this method, a reference to an argument (not the value of the argument) is passed to the parameter. 12. What is the difference between an argument and a parameter?- While defining method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments. 13. What are different types of access modifiers?- public: Any thing declared as public can be accessed from anywhere. private: Any thing declared as private cant be seen outside of its class. protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages. default modifier : Can be accessed only to classes in the same package. 14. What is final, finalize() and finally?- final : final keyword can be used for class, method and variables. A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods. A final method cant be overridden. A final variable cant change from its initialized value. finalize() : finalize() method is used just before an object is destroyed and can be called just prior to garbage collection. finally : finally, a key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this contingency. 15. What is UNICODE?- Unicode is used for internal representation of characters and strings and it uses 16 bits to represent each other. 16. What is Garbage Collection and how to call it explicitly?- When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection. System. gc() method may be used to call it explicitly. 17. What is finalize() method?- finalize () method is used just before an object is destroyed and can be called just prior to garbage collection. 18. What are Transient and Volatile Modifiers?- Transient: The transient modifier applies to variables only and it is not stored as part of its objects Persistent state. Transient variables are not serialized. Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program. 19. What is method overloading and method overriding?- Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading. Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding. 20. What is difference between overloading and overriding?- a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method. b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass. c) In overloading, separate methods share the same name whereas in overriding, subclass method replaces the superclass. d) Overloading must have different method signatures whereas overriding must have same signature. 21. What is meant by Inheritance and what are its advantages?- Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are -123-
reusability of code and accessibility of variables and methods of the super class by subclasses. 22. What is the difference between this() and super()?- this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a super class constructor. 23. What is the difference between superclass and subclass?- A super class is a class that is inherited whereas sub class is a class that does the inheriting. 24. What modifiers may be used with top-level class?- public, abstract and final can be used for top-level class. 25. What are inner class and anonymous class?- Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private. Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors. 26. What is a package?- A package is a collection of classes and interfaces that provides a high-level layer of access protection and name space management. 27. What is a reflection package?- java. lang. reflect package has the ability to analyze itself in runtime. 28. What is interface and its use?- Interface is similar to a class which may contain methods signature only but not bodies and it is a formal set of method and constant declarations that must be defined by the class that implements it. Interfaces are useful for: a)Declaring methods that one or more classes are expected to implement b)Capturing similarities between unrelated classes without forcing a class relationship. c)Determining an objects programming interface without revealing the actual body of the class. 29. What is an abstract class?- An abstract class is a class designed with implementation gaps for subclasses to fill in and is deliberately incomplete. 30. What is the difference between Integer and int?- a) Integer is a class defined in the java. lang package, whereas int is a primitive data type defined in the Java language itself. Java does not automatically convert from one to the other. b) Integer can be used as an argument for a method that requires an object, whereas int can be used for calculations. 31. What is a cloneable interface and how many methods does it contain?- It is not having any method because it is a TAGGED or MARKER interface. 32. What is the difference between abstract class and interface?- a) All the methods declared inside an interface are abstract whereas abstract class must have at least one abstract method and others may be concrete or abstract. b) In abstract class, key word abstract must be used for the methods whereas interface we need not use that keyword for the methods. c) Abstract class must have subclasses whereas interface cant have subclasses. 33. Can you have an inner class inside a method and what variables can you access?Yes, we can have an inner class inside a method and final variables can be accessed. 34. What is the difference between String and String Buffer?- a) String objects are constants and immutable whereas StringBuffer objects are not. b) String class supports constant strings whereas StringBuffer class supports growable and modifiable strings. 35. What is the difference between Array and vector?- Array is a set of related data type and static whereas vector is a growable array of objects and dynamic. -124-
36. What is the difference between exception and error?- The exception class defines mild error conditions that your program encounters. Exceptions can occur when trying to open the file, which does not exist, the network connection is disrupted, operands being manipulated are out of prescribed ranges, the class file you are interested in loading is missing. The error class defines serious error conditions that you should not attempt to recover from. In most cases it is advisable to let the program terminate when such an error is encountered. 37. What is the difference between process and thread?- Process is a program in execution whereas thread is a separate path of execution in a program. 38. What is multithreading and what are the methods for inter-thread communication and what is the class in which these methods are defined?- Multithreading is the mechanism in which more than one thread run independent of each other within the process. wait (), notify () and notifyAll() methods can be used for inter-thread communication and these methods are in Object class. wait() : When a thread executes a call to wait() method, it surrenders the object lock and enters into a waiting state. notify() or notifyAll() : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object. 39. What is the class and interface in java to create thread and which is the most advantageous method?- Thread class and Runnable interface can be used to create threads and using Runnable interface is the most advantageous method to create threads because we need not extend thread class here. 40. What are the states associated in the thread?- Thread contains ready, running, waiting and dead states. 41. What is synchronization?- Synchronization is the mechanism that ensures that only one thread is accessed the resources at a time. 42. When you will synchronize a piece of your code?- When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption. 43. What is deadlock?- When two threads are waiting each other and cant precede the program is said to be deadlock. 44. What is daemon thread and which method is used to create the daemon thread?Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread. 45. Are there any global variables in Java, which can be accessed by other part of your program?- No, it is not the main method in which you define variables. Global variables is not possible because concept of encapsulation is eliminated here. 46. What is an applet?- Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser. 47. What is the difference between applications and applets?- a)Application must be run on local machine whereas applet needs no explicit installation on local machine. b)Application must be run explicitly within a java-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser. d)Application starts execution with its main method whereas applet starts execution with its init method. e)Application can run with or without graphical user interface whereas applet must run within a graphical user interface. -125-
48. How does applet recognize the height and width?- Using getParameters() method. 49. When do you use codebase in applet?- When the applet class file is not in the same directory, codebase is used. 50. What is the lifecycle of an applet?- init() method - Can be called when an applet is first loaded start() method - Can be called each time an applet is started. paint() method - Can be called when the applet is minimized or maximized. stop() method - Can be used when the browser moves off the applets page. destroy() method - Can be called when the browser is finished with the applet. 51. How do you set security in applets?- using setSecurityManager() method 52. What is an event and what are the models available for event handling?- An event is an event object that describes a state of change in a source. In other words, event occurs when an action is generated, like pressing button, clicking mouse, selecting a list, etc. There are two types of models for handling events and they are: a) event-inheritance model and b) event-delegation model 53. What are the advantages of the model over the event-inheritance model?- The eventdelegation model has two advantages over the event-inheritance model. They are: a)It enables event handling by objects other than the ones that generate the events. This allows a clean separation between a components design and its use. b)It performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to be repeatedly process unhandled events as is the case of the event-inheritance. 54. What is source and listener?- source : A source is an object that generates an event. This occurs when the internal state of that object changes in some way. listener : A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications. 55. What is adapter class?- An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. You can define a new class to act listener by extending one of the adapter classes and implementing only those events in which you are interested. For example, the MouseMotionAdapter class has two methods, mouseDragged()and mouseMoved(). The signatures of these empty are exactly as defined in the MouseMotionListener interface. If you are interested in only mouse drag events, then you could simply extend MouseMotionAdapter and implement mouseDragged() . 56. What is meant by controls and what are different types of controls in AWT?Controls are components that allow a user to interact with your application and the AWT supports the following types of controls: Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components. These controls are subclasses of Component. 57. What is the difference between choice and list?- A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices and only one item may be selected from a choice. A List may be displayed in such a way that several list items are visible and it supports the selection of one or more list items.
-126-
58. What is the difference between scrollbar and scrollpane?- A Scrollbar is a Component, but not a Container whereas Scrollpane is a Conatiner and handles its own events and perform its own scrolling. 59. What is a layout manager and what are different types of layout managers available in java AWT?- A layout manager is an object that is used to organize components in a container. The different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout and GridBagLayout. 60. How are the elements of different layouts organized?- FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion. BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East and West) and the center of a container. CardLayout: The elements of a CardLayout are stacked, on top of the other, like a deck of cards. GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a grid. GridBagLayout: The elements of a GridBagLayout are organized according to a grid. However, the elements are of different size and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes. 61. Which containers use a Border layout as their default layout?- Window, Frame and Dialog classes use a BorderLayout as their layout. 62. Which containers use a Flow layout as their default layout?- Panel and Applet classes use the FlowLayout as their default layout. 63. What are wrapper classes?- Wrapper classes are classes that allow primitive types to be accessed as objects. 64. What are Vector, Hashtable, LinkedList and Enumeration?- Vector : The Vector class provides the capability to implement a growable array of objects. Hashtable : The Hashtable class implements a Hashtable data structure. A Hashtable indexes and stores objects in a dictionary using hash codes as the objects keys. Hash codes are integer values that identify objects. LinkedList: Removing or inserting elements in the middle of an array can be done using LinkedList. A LinkedList stores each object in a separate link whereas an array stores object references in consecutive locations. Enumeration: An object that implements the Enumeration interface generates a series of elements, one at a time. It has two methods, namely hasMoreElements() and nextElement(). HasMoreElemnts() tests if this enumeration has more elements and nextElement method returns successive elements of the series. 65. What is the difference between set and list?- Set stores elements in an unordered way but does not contain duplicate elements, whereas list stores elements in an ordered way but may contain duplicate elements. 66. What is a stream and what are the types of Streams and classes of the Streams?- A Stream is an abstraction that either produces or consumes information. There are two types of Streams and they are: Byte Streams: Provide a convenient means for handling input and output of bytes. Character Streams: Provide a convenient means for handling input & output of characters. Byte Streams classes: Are defined by using two abstract classes, namely InputStream and OutputStream. Character Streams classes: Are defined by using two abstract classes, namely Reader and Writer. 67. What is the difference between Reader/Writer and InputStream/Output Stream?The Reader/Writer class is character-oriented and the InputStream/OutputStream class is byte-oriented. -127-
68. What is an I/O filter?- An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another. 69. What is serialization and deserialization?- Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects. 70. What is JDBC?- JDBC is a set of Java API for executing SQL statements. This API consists of a set of classes and interfaces to enable programs to write pure Java Database applications. 71. What are drivers available?- a) JDBC-ODBC Bridge driver b) Native API Partly-Java driver c) JDBC-Net Pure Java driver d) Native-Protocol Pure Java driver 72. What is the difference between JDBC and ODBC?- a) OBDC is for Microsoft and JDBC is for Java applications. b) ODBC cant be directly used with Java because it uses a C interface. c) ODBC makes use of pointers which have been removed totally from Java. d) ODBC mixes simple and advanced features together and has complex options for simple queries. But JDBC is designed to keep things simple while allowing advanced capabilities when required. e) ODBC requires manual installation of the ODBC driver manager and driver on all client machines. JDBC drivers are written in Java and JDBC code is automatically installable, secure, and portable on all platforms. f) JDBC API is a natural Java interface and is built on ODBC. JDBC retains some of the basic features of ODBC. 73. What are the types of JDBC Driver Models and explain them?- There are two types of JDBC Driver Models and they are: a) Two tier model and b) Three tier model Two tier model: In this model, Java applications interact directly with the database. A JDBC driver is required to communicate with the particular database management system that is being accessed. SQL statements are sent to the database and the results are given to user. This model is referred to as client/server configuration where user is the client and the machine that has the database is called as the server. Three tier model: A middle tier is introduced in this model. The functions of this model are: a) Collection of SQL statements from the client and handing it over to the database, b) Receiving results from database to the client and c) Maintaining control over accessing and updating of the above. 74. What are the steps involved for making a connection with a database or how do you connect to a database?a) Loading the driver : To load the driver, Class. forName() method is used. Class. forName(sun. jdbc. odbc. JdbcOdbcDriver); When the driver is loaded, it registers itself with the java. sql. DriverManager class as an available database driver. b) Making a connection with database: To open a connection to a given database, DriverManager. getConnection() method is used. Connection con = DriverManager. getConnection (jdbc:odbc:somedb, user, password); c) Executing SQL statements : To execute a SQL query, java. sql. statements class is used. createStatement() method of Connection to obtain a new Statement object. Statement stmt = con. createStatement(); A query that returns data can be executed using the executeQuery() method of Statement. This method executes the statement and returns a java. sql. ResultSet that encapsulates the retrieved data: ResultSet rs = stmt. executeQuery(SELECT * FROM some table); d) Process the results : ResultSet returns one row at a time. Next() method of ResultSet object can be called to move to the next row. The getString() and getObject() methods are used for retrieving column values: -128-
while(rs. next()) { String event = rs. getString(event); Object count = (Integer) rs. getObject(count); 75. What type of driver did you use in project?- JDBC-ODBC Bridge driver (is a driver that uses native(C language) libraries and makes calls to an existing ODBC driver to access a database engine). 76. What are the types of statements in JDBC?- Statement: to be used createStatement() method for executing single SQL statement PreparedStatement To be used preparedStatement() method for executing same SQL statement over and over. CallableStatement To be used prepareCall() method for multiple SQL statements over and over. 77. What is stored procedure?- Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters. 78. How to create and call stored procedures?- To create stored procedures: Create procedure procedurename (specify in, out and in out parameters) BEGIN Any multiple SQL statement; END; To call stored procedures: CallableStatement csmt = con. prepareCall({call procedure name(?,?)}); csmt. registerOutParameter(column no. , data type); csmt. setInt(column no. , column name) csmt. execute(); 79. What is servlet?- Servlets are modules that extend request/response-oriented servers, such as java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a companys order database. 80. What are the classes and interfaces for servlets?- There are two packages in servlets and they are javax. servlet and 81. What is the difference between an applet and a servlet?- a) Servlets are to servers what applets are to browsers. b) Applets must have graphical user interfaces whereas servlets have no graphical user interfaces. 82. What is the difference between doPost and doGet methods?- a) doGet() method is used to get information, while doPost() method is used for posting information. b) doGet() requests cant send large amount of information and is limited to 240-255 characters. However, doPost()requests passes all of its data, of unlimited length. c) A doGet() request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas a doPost() request passes directly over the socket connection as part of its HTTP request body and the exchange are invisible to the client. 83. What is the life cycle of a servlet?- Each Servlet has the same life cycle: a) A server loads and initializes the servlet by init () method. b) The servlet handles zero or more clients requests through service() method. c) The server removes the servlet through destroy() method. 84. Who is loading the init() method of servlet?- Web server 85. What are the different servers available for developing and deploying Servlets?- a) Java Web Server b) JRun g) Apache Server h) Netscape Information Server i) Web Logic
-129-
86. How many ways can we track client and what are they?- The servlet API provides two ways to track client state and they are: a) Using Session tracking and b) Using Cookies. 87. What is session tracking and how do you track a user session in servlets?- Session tracking is a mechanism that servlets use to maintain state about a series requests from the same user across some period of time. The methods used for session tracking are: a) User Authentication - occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password. b) Hidden form fields - fields are added to an HTML form that are not displayed in the clients browser. When the form containing the fields is submitted, the fields are sent back to the server. c) URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change. d) Cookies - a bit of information that is sent by a web server to a browser and which can later be read back from that browser. e) HttpSession- places a limit on the number of sessions that can exist in memory. This limit is set in the session. maxresidents property. 88. What is Server-Side Includes (SSI)?- Server-Side Includes allows embedding servlets within HTML pages using a special servlet tag. In many servlets that support servlets, a page can be processed by the server to include output from servlets at certain points inside the HTML page. This is accomplished using a special internal SSINCLUDE, which processes the servlet tags. SSINCLUDE servlet will be invoked whenever a file with an. shtml extension is requested. So HTML files that include server-side includes must be stored with an . shtml extension. 89. What are cookies and how will you use them?- Cookies are a mechanism that a servlet uses to have a client hold a small amount of state-information associated with the user. a) Create a cookie with the Cookie constructor: public Cookie(String name, String value) b) A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of HttpServletResponse: public void HttpServletResponse. addCookie(Cookie cookie) c) A servlet retrieves cookies by calling the getCookies() method of HttpServletRequest: public Cookie[ ] HttpServletRequest. getCookie(). 90. Is it possible to communicate from an applet to servlet and how many ways and how?- Yes, there are three ways to communicate from an applet to servlet and they are: a) HTTP Communication(Text-based and object-based) b) Socket Communication c) RMI Communication 91. What is connection pooling?- With servlets, opening a database connection is a major bottleneck because we are creating and tearing down a new connection for every page request and the time taken to create connection will be more. Creating a connection pool is an ideal approach for a complicated servlet. With a connection pool, we can duplicate only the resources we need to duplicate rather than the entire servlet. A connection pool can also intelligently manage the size of the pool and make sure each connection remains valid. A number of connection pool packages are currently available. Some like DbConnectionBroker are freely available from Java Exchange Works by creating an object that dispenses connections and connection Ids on request. The ConnectionPool class maintains a Hastable, using Connection objects as keys and Boolean values as stored values. The Boolean value indicates whether a connection is in use or not. A -130-
program calls getConnection() method of the ConnectionPool for getting Connection object it can use; it calls returnConnection() to give the connection back to the pool. 92. Why should we go for interservlet communication?- Servlets running together in the same server communicate with each other in several ways. The three major reasons to use interservlet communication are: a) Direct servlet manipulation - allows to gain access to the other currently loaded servlets and perform certain tasks (through the ServletContext object) b) Servlet reuse - allows the servlet to reuse the public methods of another servlet. c) Servlet collaboration - requires to communicate with each other by sharing specific information (through method invocation) 93. Is it possible to call servlet with parameters in the URL?- Yes. You can call a servlet with parameters in the syntax as (?Param1 = xxx || m2 = yyy). 94. What is Servlet chaining?- Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request. In servlet chaining, one servlets output is piped to the next servlets input. This process continues until the last servlet is reached. Its output is then sent back to the client. 95. How do servlets handle multiple simultaneous requests?- The server has multiple threads that are available to handle requests. When a request comes in, it is assigned to a thread, which calls a service method (for example: doGet(), doPost() and service()) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once. 96. What is the difference between TCP/IP and UDP?- TCP/IP is a two-way communication between the client and the server and it is a reliable and there is a confirmation regarding reaching the message to the destination. It is like a phone call. UDP is a one-way communication only between the client and the server and it is not a reliable and there is no confirmation regarding reaching the message to the destination. It is like a postal mail. 97. What is Inet address?- Every computer connected to a network has an IP address. An IP address is a number that uniquely identifies each computer on the Net. An IP address is a 32-bit number. 98. What is Domain Naming Service(DNS)?- It is very difficult to remember a set of numbers(IP address) to connect to the Internet. The Domain Naming Service(DNS) is used to overcome this problem. It maps one particular IP address to a string of characters. For example, www. mascom. com implies com is the domain name reserved for US commercial sites, moscom is the name of the company and www is the name of the specific computer, which is mascoms server. 99. What is URL?- URL stands for Uniform Resource Locator and it points to resource files on the Internet. URL has four components: http://www. address. com:80/index.html, where http - protocol name, address - IP address or host name, 80 - port number and index.html - file path. 100. What is RMI and steps involved in developing an RMI object?- Remote Method Invocation (RMI) allows java object that executes on one machine and to invoke the method of a Java object to execute on another machine. The steps involved in developing an RMI object are: a) Define the interfaces b) Implementing these interfaces c) Compile the interfaces and their implementations with the java compiler d) Compile the server implementation with RMI compiler e) Run the RMI registry f) Run the application -131-
101. What is RMI architecture?- RMI architecture consists of four layers and each layer performs specific functions: a) Application layer - contains the actual object definition. b) Proxy layer - consists of stub and skeleton. c) Remote Reference layer gets the stream of bytes from the transport layer and sends it to the proxy layer. d) Transportation layer - responsible for handling the actual machine-to-machine communication. 102. what is UnicastRemoteObject?- All remote objects must extend UnicastRemoteObject, which provides functionality that is needed to make objects available from remote machines. 103. Explain the methods, rebind() and lookup() in Naming class?- rebind() of the Naming class(found in java. rmi) is used to update the RMI registry on the server machine. Naming. rebind(AddSever, AddServerImpl); lookup() of the Naming class accepts one argument, the rmi URL and returns a reference to an object of type AddServerImpl. 104. What is a Java Bean?- A Java Bean is a software component that has been designed to be reusable in a variety of different environments. 105. What is a Jar file?- Jar file allows to efficiently deploying a set of classes and their associated resources. The elements in a jar file are compressed, which makes downloading a Jar file much faster than separately downloading several uncompressed files. The package java. util. zip contains classes that read and write jar files. 106. What is BDK?- BDK, Bean Development Kit is a tool that enables to create, configure and connect a set of set of Beans and it can be used to test Beans without writing a code. 107. What is JSP?- JSP is a dynamic scripting capability for web pages that allows Java as well as a few special tags to be embedded into a web file (HTML/XML, etc). The suffix traditionally ends with .jsp to indicate to the web server that the file is a JSP files. JSP is a server side technology - you cant do any client side validation with it. The advantages are: a) The JSP assists in making the HTML more functional. Servlets on the other hand allow outputting of HTML but it is a tedious process. b) It is easy to make a change and then let the JSP capability of the web server you are using deal with compiling it into a servlet and running it. 108. What are JSP scripting elements?- JSP scripting elements lets to insert Java code into the servlet that will be generated from the current JSP page. There are three forms: a) Expressions of the form <%= expression %> that are evaluated and inserted into the output, b) Scriptlets of the formthat are inserted into the servlets service method, and c) Declarations of the form <%! Code %>that are inserted into the body of the servlet class, outside of any existing methods. 109. What are JSP Directives?- A JSP directive affects the overall structure of the servlet class. It usually has the following form:<%@ directive attribute=value %> However, you can also combine multiple attribute settings for a single directive, as follows:<%@ directive attribute1=value1 attribute 2=value2 . . . attributeN =valueN %> There are two main types of directive: page, which lets to do things like import classes, customize the servlet superclass, and the like; and include, which lets to insert a file into the servlet class at the time the JSP file is translated into a servlet 110. What are Predefined variables or implicit objects?- To simplify code in JSP expressions and scriptlets, we can use eight automatically defined variables, sometimes -132-
called implicit objects. They are request, response, out, session, application, config, pageContext, and page. 111. What are JSP ACTIONS?- JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. Available actions include: jsp:include - Include a file at the time the page is requested. jsp:useBean - Find or instantiate a JavaBean. jsp:setProperty - Set the property of a JavaBean. jsp:getProperty - Insert the property of a JavaBean into the output. jsp:forward - Forward the requester to a newpage. Jsp: plugin - Generate browser-specific code that makes an OBJECT or EMBED 112. How do you pass data (including JavaBeans) to a JSP from a servlet?- (1) Request Lifetime: Using this technique to pass beans, a request dispatcher (using either include or forward) can be called. This bean will disappear after processing this request has been completed. Servlet: request. setAttribute(theBean, myBean); RequestDispatcher rd = getServletContext(). getRequestDispatcher(thepage. jsp); rd. forward(request, response); JSP PAGE:<jsp: useBean id=theBean scope=request class=. . . . . />(2) Session Lifetime: Using this technique to pass beans that are relevant to a particular session (such as in individual user login) over a number of requests. This bean will disappear when the session is invalidated or it times out, or when you remove it. Servlet: HttpSession session = request. getSession(true); session. putValue(theBean, myBean); /* You can do a request dispatcher here, or just let the bean be visible on the next request */ JSP Page:<jsp:useBean id=theBean scope=session class=. . . /> 3) Application Lifetime: Using this technique to pass beans that are relevant to all servlets and JSP pages in a particular app, for all users. For example, I use this to make a JDBC connection pool object available to the various servlets and JSP pages in my apps. This bean will disappear when the servlet engine is shut down, or when you remove it. Servlet: GetServletContext(). setAttribute(theBean, myBean); JSP PAGE:<jsp:useBean id=theBean scope=application class=. . . /> 113. How can I set a cookie in JSP?- response. setHeader(Set-Cookie, cookie string); To give the response-object to a bean, write a method setResponse (HttpServletResponse response) - to the bean, and in jsp-file:<% bean. setResponse (response); %> 114. How can I delete a cookie with JSP?- Say that I have a cookie called foo, that I set a while ago & I want it to go away. I simply: <% Cookie killCookie = new Cookie(foo, null); KillCookie. setPath(/); killCookie. setMaxAge(0); response. addCookie(killCookie); %> 115. How are Servlets and JSP Pages related?- JSP pages are focused around HTML (or XML) with Java codes and JSP tags inside them. When a web server that has JSP support is asked for a JSP page, it checks to see if it has already compiled the page into a servlet. Thus, JSP pages become servlets and are transformed into pure Java and then compiled, loaded into the server and executed. Serlets What is the difference between application server and web server?
-133-
An web server is responsible for handling HttpRequests whereas appliation server is responsible for handling business logics. app server has inbuilt features like load balancing, clusters, caches and resource & connection pooling etc. Using application server we can develop reusable components. Application server is a super set of web server. web server is used for executing JSP and servlets. application server is used for executing EJB related components
Difference between throw and throws : throw -- to explicitly throw an exception throws --- means that exception will be handled by the called method. 1. Difference between HashTable and hashMap ? --------------------------------------------Both provide key-value access to data. The Hashtable is one of the original collection classes in Java. HashMap is part of the new Collections Framework, added with Java 2, v1.2. The key difference between the two is that access to the Hashtable is synchronized on the table while access to the HashMap isn't. You can add it, but it isn't there by default. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If you change the map while iterating, you'll know. And, a third difference is that HashMap permits null values in it, while Hashtable doesn't. For new code,we can use HashMap. 2.What is the diffrence between Array,Vector,ArryList,LinkedList and HashTable with HashMap with example and situation? Once u create an array (of any type) u can't change the array size at dynamically. it is not synchronized. U can view a Vector as a dynamic array. U can resize the vector at runtime. u can add/remove element in a vector at runtime. it is synchronized. An ArrayList is a class which implements the List interface. This again is resizable and u hav all the functionalities of a list. it is not synchronized. Note : u can hav duplicates in ArrayList. A LinkedList is an implementation of the calssical 'C' linked list. U can get, remove or insert elements. HashTable is basically a keyvalue pair collection. Key has to be unique. U can do get and put. HashMap is implementation of Map interface. U can hav null key or null value. Use when u require constant time performance.
-134-
3.What is the difference between servlet & CGI? ----------------------------------------------For each HTTP request, CGI will start a new process. whereas in servlet, init() method will be called, only when first HTTP request came. for subsequent request an thread is created. 4.What is the difference between the Serlvet single threaded model and multi threaded model? -------------------------------------------------------------------------------------------Typically, a servlet class is instantiated the first time it is invoked. The same instance will be used over several client requests, so all members that are declared in that servlet are shared accross clients. That is what is meant by multi threaded model, multiple clients that access the same instance. There are situations where you want to protect your servlet member variables from being modified by different clients. In this case, you can have your servlet implement the marker interface SingleThreadModel. Every time a client makes a request to a servlet that implements this interface, the engine will create a new instance of the servlet. For performance reasons, the engine can also maintain a instance pool, handing out instances as they are needed. Or it could also serialize client requests, executing one after another. 5. How to read environment variables from a Servlet? A:ServletConfig.getParameter(String param_name) Q: What is the difference between an Interface and an Abstract class? A: An Abstract class declares have at least one instance method that is declared abstract which will be implemented by the subclasses. An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior. All memeber variable of an interface is "public static final" Q: What is the purpose of garbage collection in Java, and when is it used? A: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. Q: Describe synchronization in respect to multithreading. A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.
-135-
Q: Explain different way of using thread? A: The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help. Q: What are pass by reference and passby value? A: Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed. Q: What is HashMap and Map? A: Map is Interface and Hashmap is class that implements that. Q: Difference between HashMap and HashTable? A: The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is non synchronized and Hashtable is synchronized. Q: Difference between Vector and ArrayList? A: Vector is synchronized whereas arraylist is not. Q: Difference between Swing and Awt? A: AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT. Q: What is the difference between a constructor and a method? A: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator. Q: What is an Iterators? A: Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator. -136-
Q: What is an abstract class? A: Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated. Q: What is static in java? A: Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass. Q: What is final? A: A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant). Q: What if the main method is declared as private? A: The program compiles properly but at runtime it will give "Main method not public." message. Q: What if the static modifier is removed from the signature of the main method? A: Program compiles. But at runtime throws an error "NoSuchMethodError". Q: What if I write static public void instead of public static void? A: Program compiles and runs properly. Q: What if I do not provide the String array as the argument to the method? A: Program compiles but throws a runtime error "NoSuchMethodError".
Q: What is the first argument of the String array in main method? -137-
A: The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name. Q: If I do not provide any arguments on the command line, then the String array of Main method will be empty of null? A: It is empty. But not null. Q: How can one prove that the array is not null but empty? A: Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length. Q: What environment variables do I need to set on my machine in order to be able to run Java programs? A: CLASSPATH and PATH are the two variables. Q: Can an application have multiple classes having main method? A: Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method. Q: Can I have multiple main methods in the same class? A: No the program fails to compile. The compiler says that the main method is already defined in the class. Q: Do I need to import java.lang package any time? Why ? A: No. It is by default loaded internally by the JVM. Q: Can I import same package/class twice? Will the JVM load the package twice at runtime? A: One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.
A: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be. Q: What is Overriding? A: When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass. When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private. Q: What are different types of inner classes? A: Nested top-level classes, Member classes, Local classes, Anonymous classes Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety. Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class. Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable. Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor. -139-
Q: What is the difference between declaring a variable and defining a variable? A: In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization. e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions. Q: What is the default value of an object reference declared as an instance variable? A: null unless we define it explicitly. Q: What type of parameter passing does Java support? A: Java supports both pass by value as well as pass by reference. Q: Primitive data types are passed by reference or pass by value? A: Primitive data types are passed by value. Q: Objects are passed by value or by reference? A: Objects are always passed by reference. Thus any modifications done to an object inside the called method will always reflect in the caller method. Q: What is serialization? A: Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream. Q: Which methods of Serializable interface should I implement? A: The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods. Q: What is the common usage of serialization? A: Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed. Q: What is Externalizable interface? A: Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods. -140-
Q: What happens to the object references included in the object? A: The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original object. Q: What one should take care of while serializing the object? A: One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException. Q: What happens to the static fields of a class during serialization? Are these fields serialized as a part of each serialized object? A: Yes the static fields do get serialized. If the static field is an object then it must have implemented Serializable interface. The static fields are serialized as a part of every object. But the commonness of the static fields across all the instances is maintained even after serialization. Q: Does Java provide any construct to find out the size of an object? A: No there is not sizeof operator in Java. So there is not direct way to determine the size of an object directly in Java. [ Received from Sandesh Sadhale] TOP Q: What are wrapper classes? A: Java provides specialized classes corresponding to each of the primitive data types. These are called wrapper classes. They are e.g. Integer, Character, Double etc. Q: Why do we need wrapper classes? A: It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object.
-141-
A: Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions. Q: What are runtime exceptions? A: Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time. Q: What is the difference between error and an exception? A: An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.). Q: How to create custom exceptions? A: Your class should extend class Exception, or some more specific type thereof. Q: What happens to an unhandled exception? A: One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well. Q: How does an exception permeate through the code? A: An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates. Q: What are the different ways to handle exceptions? A: There are two ways to handle exceptions, 1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and 2. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions.
-142-
1. How can you achieve Multiple Inheritance in Java? Java's interface mechanism can be used to implement multiple inheritance, with one important difference from c++ way of doing MI: the inherited interfaces must be abstract. This obviates the need to choose between different implementations, as with interfaces there are no implementations. 3. Searching a String String string = "aString"; // First occurrence. int index = string.indexOf('S'); // 1 // Last occurrence. index = string.lastIndexOf('i'); // 4 // Not found. index = string.lastIndexOf('z'); // -1 4. Connecting to a Database and Strings Handling Constructing a String If you are constructing a string with several appends, it may be more efficient to construct it using a StringBuffer and then convert it to an immutable String object. StringBuffer buf = new StringBuffer("Initial Text"); // Modify int index = 1; buf.insert(index, "abc"); buf.append("def"); // Convert to string String s = buf.toString(); Getting a Substring from a String int start = 1; int end = 4; String substr = "aString".substring(start, end); // Str 5. What is a transient variable? A transient variable is a variable that may not be serialized. If you don't want some field not to be serialized, you can mark that field transient or static. 6. What is the difference between Serializalble and Externalizable interface? When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject()two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process. 7. How many methods in the Externalizable interface? There are two methods in the Externalizable interface. You have to implement these two methods in order to make your class externalizable. These two methods are readExternal() and writeExternal(). 8. How many methods in the Serializable interface? -143-
There is no method in the Serializable interface. The Serializable interface acts as a marker, telling the object serialization tools that your class is serializable. 9. How to make a class or a bean serializable? By implementing either the java.io.Serializable interface, or the java.io.Externalizable interface. As long as one class in a class's inheritance hierarchy implements Serializable or Externalizable, that class is serializable. 10. What is the serialization? The serialization is a kind of mechanism that makes a class or a bean persistence by having its properties or fields and state information saved and restored to and from storage. 11. What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. 12. What is synchronization and why is it important? With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often causes dirty data and leads to significant errors. 13. What is the purpose of finalization? The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. 14. What classes of exceptions may be caught by a catch clause? A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.
15. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy? The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented. 16. What happens when a thread cannot acquire a lock on an object? -144-
If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available. 17. What restrictions are placed on method overriding? Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method. 18. What restrictions are placed on method overloading? Two methods may not have the same name and argument list but different return types. 19. How does multithreading take place on a computer with a single CPU? Java Interview Questions Subscribe to FREE & Exclusive career resources at The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially. 20. How is it possible for two String objects with identical values not to be equal under the == operator? The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory. 21. How are this() and super() used with constructors? this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor. 22. What class allows you to read objects directly from a stream? The ObjectInputStream class supports the reading of objects from input streams. 23. What is the ResourceBundle class? The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run. 24. What interface must an object implement before it can be written to a stream as an object? An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object. 25. What is Serialization and deserialization? Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects. 26. What are the Object and Class classes used for? The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program. 27. Can you write Java code for declaration of multiple inheritance in Java ? Class C extends A implements B { -145-
} 28. What do you mean by multiple inheritance in C++ ? Java Interview Questions Multiple inheritance is a feature in C++ by which one class can be of different types. Say class teachingAssistant is inherited from two classes say teacher and Student. 29. Write the Java code to declare any constant (say gravitational constant) and to get its value. Class ABC { static final float GRAVITATIONAL_CONSTANT = 9.8; public void getConstant() { system.out.println("Gravitational_Constant: " + GRAVITATIONAL_CONSTANT); } } 30. What are the disadvantages of using threads? DeadLock. 31. Given two tables Student(SID, Name, Course) and Level(SID, level) write the SQL statement to get the name and SID of the student who are taking course = 3 and at freshman level. SELECT Student.name, Student.SID FROM Student, Level WHERE Student.SID = Level.SID AND Level.Level = "freshman" AND Student.Course = 3; 32. What do you mean by virtual methods? virtual methods are used to use the polymorhism feature in C++. Say class A is inherited from class B. If we declare say fuction f() as virtual in class B and override the same function in class A then at runtime appropriate method of the class will be called depending upon the type of the object. 33. What do you mean by static methods? By using the static method there is no need creating an object of that class to use that method. We can directly call that method on that class. For example, say class A has static function f(), then we can call f() function as A.f(). There is no need of creating an object of class A. 34. What do mean by polymorphism, inheritance, encapsulation? Polymorhism: is a feature of OOPl that at run time depending upon the type of object the appropriate method is called. Inheritance: is a feature of OOPL that represents the "is a" relationship between different objects(classes). -146-
Say in real life a manager is a employee. So in OOPL manger class is inherited from the employee class. Encapsulation: is a feature of OOPL that is used to hide the information. 35. What are the advantages of OOPL? Object oriented programming languages directly represent the real life objects. The features of OOPL as inhreitance, polymorphism, encapsulation makes it powerful. 36. How many methods do u implement if implement the Serializable Interface? The Serializable interface is just a "marker" interface, with no methods of its own to implement. 37. Are there any other 'marker' interfaces? java.rmi.Remote java.util.EventListener 38. What is the difference between instanceof and isInstance? instanceof is used to check to see if an object can be cast into a specified type without throwing a cast class exception. isInstance() determines if the specified object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is nonnull and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise. 39. why do you create interfaces, and when MUST you use one? You would create interfaces when you have two or more functionalities talking to each other. Doing it this way help you in creating a protocol between the parties involved. 40. What's the difference between the == operator and the equals() method? What test does Object.equals() use, and why? The == operator would be used, in an object sense, to see if the two objects were actually the same object. This operator looks at the actually memory address to see if it actually the same object. The equals() method is used to compare the values of the object respectively. This is used in a higher level to see if the object values are equal. Of course the the equals() method would be overloaded in a meaningful way for whatever object that you were working with. } 42. Given a text file, input.txt, provide the statement required to open this file with the appropriate I/O stream to be able to read and process this file. 43. Name four methods every Java class will have. public String toString(); public Object clone(); -147-
public boolean equals(); public int hashCode(); 44. What does the "abstract" keyword mean in front of a method? A class? Abstract keyword declares either a method or a class. If a method has a abstract keyword in front of it, it is called abstract method.Abstract method has no body. It has only arguments and return type. Abstract methods act as placeholder methods that are implemented in the subclasses. Abstract classes can't be instantiated.If a class is declared as abstract,no objects of that class can be created.If a class contains any abstract method it must be declared as abstract. 45. Does Java have destructors? No garbage collector does the job working in the background 46. Are constructors inherited? Can a subclass call the parent's class constructor? When? You cannot inherit a constructor. That is, you cannot create a instance of a subclass using a constructor of one of it's superclasses. One of the main reasons is because you probably don't want to overide the superclasses constructor, which would be possible if they were inherited. By giving the developer the ability to override a superclasses constructor you would erode the encapsulation abilities of the language. 49. Does Java have "goto"? No 50. What does the "final" keyword mean in front of a variable? A method? A class? FINAL for a variable : value is constant FINAL for a method : cannot be overridden FINAL for a class : cannot be derived .
Reference Books
1. Web Programming, building Internet applications, Chris Bates 2nd edition, WILEY Dreamtech 2. The complete Reference Java 2 Fifth Edition by Patrick Naughton and Herbert Schildt. TMH -148-
3. Java Server Pages Hans Bergsten, SPD OReilly 4. Internet and World Wide Web How to program by Dietel and Nieto PHI/Pearson Education Asia. 5. Jakarta Struts Cookbook, Bill Siggelkow, S P D OReilly.
-149-