Web-Programming Notes MRIET
Web-Programming Notes MRIET
UNIT II JAVA
Introduction to object oriented programming-Features of Java – Data types,
variables and arrays – Operators – Control statements – Classes and Methods
– Inheritance. Packages and Interfaces – Exception Handling – Multithreaded
Programming – Input/Output – Files – Utility Classes – String Handling.
TEXT BOOKS:
1. Harvey Deitel, Abbey Deitel, Internet and World Wide Web: How To
Program 5th Edition.
2. Herbert Schildt, Java - The Complete Reference, 7th Edition. Tata
McGraw- Hill Edition.
3. Michael Morrison XML Unleashed Tech media SAMS.
REFERENCES:
1. John Pollock, Javascript - A Beginners Guide, 3rd Edition –- Tata
McGraw-Hill Edition.
2. Keyur Shah, Gateway to Java Programmer Sun Certification, Tata
McGraw Hill, 2002.
UNIT-I SCRIPTING
PART-A
1. What are some of the common lists that can be used when designing a page?
Some of the common lists that can be used are:
a) Ordered list
b) Unordered list
c) Definition list
d) Menu list
e) Directory list
2. What are new Media Elements in HTML5?
Following are the New Media Elements are present in HTML5:
1. <audio> tag : For playing audio.
2. <video> tag : For playing video.
3. <source> tag : For media resources for media elements.
4. <embed> tag : For embedded content.
5. <track> tag : For text tracks used in media players.
3. What is difference between HTML and HTML5?
The differences between HTML and HTML5 are:
1. Document of HTML is very large as compare to the HTML5.
2. Audio and Video tags are not present in HTML whereas HTML5 contains audio and
video tags.
3. Vector technology is not integral part of HTML whereas HTML5 Vector technology is
the integral part of it.
4. HTML supported by all old browsers whereas HTML5 is supported by new browser.
5. In HTML web sockets are not available whereas in HTML5 Full duplex
communication channel is present.
4. What is the importance of Doctype in HTML?
The doctype declaration should be the very first thing in an HTML document, before the
html tag.
The doctype declaration is not an HTML tag; it is an instruction to the web browser about
what version of the markup language the page is written in.
The doctype declaration refers to a Document Type Definition (DTD). The DTD
specifies the rules for the markup language, so that the browsers can render the content
correctly.
5. What is the purpose of canvas in HTML?
Canvas is an element that is used for the graphics for the web page. It uses JavaScript to
bring the graphics functionality live. It allows easy way to draw the graphics and use different
types of tools to create drawing on the web page. Canvas is just a rectangular area that controls
the pixel of every element that is used in the web page. Canvas uses methods like paths, circles,
etc.
The canvas element will be used as follows:
<canvas id="can" width="200" height="100"></canvas>
6. What are the different types of frames tags used in HTML?
Frames consists of different types of tags and they are as follows:
1. <frameset>...</frameset> : It consists of the frames that includes the layout using the
attributes of rows and cols.
2. <frame> or <frame/> : It consists of a single frame and gets included within the
frameset. It is always come up with a src attribute that provides the source that has to be
shown in a particular frame.
3. <noframes>...</noframes> : It consists of the normal HTML content that is used to
show no frames.
4. <iframe>...</iframe> : It consists of internal frame that will contain the src attribute
to include the frame that is internal to a particular region.
7. What is the difference between HTML elements and tags?
HTML elements communicate to the browser to render text. When the elements are
surrounded by brackets <>, they form HTML tags. Most of the time, tags come in pair and
surround content.
8. What is a marquee?
Marquee is used to put the scrolling text on a web page. You should put the text which
you want to scroll within the <marquee> </marquee> tag.
9. What is the difference between HTML tags <div> and <span>?
The difference between span and div is that a span element is in-line and usually used
for a small chunk of HTML inside a line (such as inside a paragraph) whereas a div (division)
element is block-line (which is basically equivalent to having a line-break before and after it) and
used to group larger chunks of code.
10. What is CSS?
Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended
to simplify the process of making web pages presentable.
11. What are the components of a CSS Style?
A style rule is made of three parts −
Selector − A selector is an HTML tag at which a style will be applied. This could be any
tag like <h1> or <table> etc.
Property − A property is a type of attribute of HTML tag. Put simply, all the HTML
attributes are converted into CSS properties. They could be color, border etc.
Value − Values are assigned to properties. For example, color property can have value
either red or #F1F1F1 etc.
12. What are the various ways of using CSS in an HTML page?
There are four ways to associate styles with your HTML document. Most commonly used
methods are inline CSS and External CSS.
Embedded CSS − The <style> Element: You can put your CSS rules into an HTML
document using the <style> element.
Inline CSS − The style Attribute: You can use style attribute of any HTML element to
define style rules.
External CSS − The <link> Element: The <link> element can be used to include an
external stylesheet file in your HTML document.
Imported CSS − @import Rule: @import is used to import an external stylesheet in a
manner similar to the <link> element.
13. What is the difference between form get and form post?
Get
With GET the form data is encoded into a URL by the browser. The form data is visible
in the URL allowing it to be bookmarked and stored in web history. The form data is
restricted to ASCII codes. Because URL lengths are limited there can be limitations on
how much form data can be sent.
Post
With POST all the name value pairs are submitted in the message body of the HTTP
request which has no restrictions on the length of the string. The name value pairs cannot
be seen in the web browser bar.
POST and GET correspond to different HTTP requests and they differ in how they are
submitted. Since the data is encoded in differently, different decoding may be needed.
14. What is BOM?
BOM stands for Browser Object Model. It provides interaction with the browser. The
default object of browser is window.
15. What is DOM? What is the use of document object?
DOM stands for Document Object Model. A document object represent the html
document. It can be used to access and change the content of html.
16. What is the use of history object?
The history object of browser can be used to switch to history pages such as back and
forward from current page or another page. There are three methods of history object.
history.back()
history.forward()
history.go(number): number may be positive for forward, negative for backward.
17. What is the difference between == and ===?
The == operator checks equality only whereas === checks equality and data type i.e.
value must be of same type.
18. What does the isNaN() function?
The isNan() function returns true if the variable value is not a number.
19. Difference between Client side JavaScript and Server side JavaScript?
Client side JavaScript comprises the basic language and predefined objects which are
relevant to running java script in a browser. The client side JavaScript is embedded directly by in
the HTML pages. This script is interpreted by the browser at run time.
Server side JavaScript also resembles like client side java script. It has relevant java
script which is to run in a server. The server side JavaScript are deployed only after compilation.
20. What is the difference between undefined value and null value?
Undefined value: A value that is not defined and has no keyword is known as undefined
value. For example:
int number;//Here, number has undefined value.
Null value: A value that is explicitly specified by the keyword "null" is known as null
value. For example:
String str=null;//Here, str has a null value.
21. What are the pop up boxes available in JavaScript?
Alert Box
Confirm Box
Prompt Box
PART-B
1. Explain in detail about basic comments in HTML for designing a web
page
➢ HTML is a markup language for describing web documents (web pages).
➢ HTML stands for Hyper Text Markup Language
➢ A markup language is a set of markup tags
➢ HTML documents are described by HTML tags
➢ Each HTML tag describes different document content
Example
!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
Explaination
➢ The DOCTYPE declaration defines the document type to be HTML
➢ The text between <html> and </html> describes an HTML document
➢ The text between <head> and </head> provides information about the document
➢ The text between <title> and </title> provides a title for the document
➢ The text between <body> and </body> describes the visible page content
➢ The text between <h1> and </h1> describes a heading
➢ The text between <p> and </p> describes a paragraph
HTML Tags
➢ HTML tags are keywords (tag names) surrounded by angle brackets:
<tagname>content</tagname>
➢ HTML tags normally come in pairs like <p> and </p>
➢ The first tag in a pair is the start tag, the second tag is the end tag
➢ The end tag is written like the start tag, but with a slash before the tag name
HTML Editors
➢ HTML can be edited by using a professional HTML editor like:
• Adobe Dreamweaver
• Microsoft Expression Web
• CoffeeCup HTML Editor
• However, for learning HTML we recommend a text editor like Notepad (PC) or TextEdit
(Mac).
• We believe using a simple text editor is a good way to learn HTML.
➢ Follow the 4 steps below to create your first web page with Notepad.
Step 1: Open Notepad
➢ To open Notepad in Windows 7 or earlier:
➢ Click Start (bottom left on your screen). Click All Programs. Click Accessories. Click
Notepad.
Step 2: Write Some HTML
➢ Write or copy some HTML into Notepad.
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
Step 3: Save the HTML Page
➢ Save the file on your computer.
➢ Select File > Save as in the Notepad menu.
➢ Name the file "index.htm" or any other name ending with htm.
➢ UTF-8 is the preferred encoding for HTML files.
➢ ANSI encoding covers US and Western European characters only.
Step 4: View HTML Page in Your Browser
➢ Open the saved HTML file in your favorite browser.
HTML Elements
➢ HTML documents are made up by HTML elements.
➢ HTML elements are written with a start tag, with an end tag, with the content in
between: <tagname>content</tagname>
<p>My first HTML paragraph.</p>
Start tag Element content End tag
<h1> My First Heading </h1>
My first
<p> </p>
paragraph.
Nested HTML Elements
➢ HTML elements can be nested (elements can contain elements).
➢ All HTML documents consist of nested HTML elements.
➢ This example contains 4 HTML elements:
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
➢ The <body> element defines the document body.
➢ It has a start tag <body> and an end tag </body>.
➢ The element content is two other HTML elements (<h1> and <p>).
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
➢ The <h1> element defines a heading.
➢ It has a start tag <h1> and an end tag </h1>.
➢ The element content is: My First Heading.
<h1>My First Heading</h1>
➢ The <p> element defines a paragraph.
➢ It has a start tag <p> and an end tag </p>.
➢ The element content is: My first paragraph.
HTML Attributes
➢ Attributes provide additional information about HTML elements.
➢ HTML elements can have attributes
➢ Attributes provide additional information about an element
➢ Attributes are always specified in the start tag
➢ Attributes come in name/value pairs like: name="value"
The lang Attribute
➢ The document language can be declared in the <html> tag.
➢ The language is declared in the lang attribute.
➢ Declaring a language is important for accessibility applications (screen readers) and
search engines:
<!DOCTYPE html>
<html lang="en-US">
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
The title Attribute
➢ HTML paragraphs are defined with the <p> tag.
➢ In this example, the <p> element has a title attribute. The value of the attribute is "About
W3Schools":
<p title="About W3Schools">
W3Schools is a web developer's site.
It provides tutorials and references covering many aspects of web programming, including
HTML, CSS, JavaScript, XML, SQL, PHP, ASP, etc.
The href Attribute
➢ HTML links are defined with the <a> tag. The link address is specified in the href
attribute:
<a href="http://www.w3schools.com">This is a link</a>
Size Attributes
➢ HTML images are defined with the <img> tag.
➢ The filename of the source (src), and the size of the image (width and height) are all
provided as attributes:
<img src="w3schools.jpg" width="104" height="142">
The alt Attribute
➢ The alt attribute specifies an alternative text to be used, when an HTML element cannot
be displayed.
➢ The value of the attribute can be read by "screen readers". This way, someone "listening"
to the webpage, i.e. a blind person, can "hear" the element.
<img src="w3schools.jpg" alt="W3Schools.com" width="104" height="142">
HTML Headings
➢ Headings are important in HTML documents.
➢ Headings are defined with the <h1> to <h6> tags.
<h1> defines the most important heading. <h6> defines the least important heading.
<h1>This is a heading</h1>
<h2>This is a heading</h2>
<h3>This is a heading</h3>
The HTML <head> Element
➢ The HTML <head> element has nothing to do with HTML headings.
➢ The HTML <head> element contains meta data. Meta data are not displayed.
➢ The HTML <head> element is placed between the <html> tag and the <body> tag:
<!DOCTYPE html>
<html>
<head>
<title>My First HTML</title>
<meta charset="UTF-8">
</head>
<body>
<p>The HTML head element contains meta data.</p>
<p>Meta data is data about the HTML document.</p>
</body>
</html>
The HTML <title> Element
➢ The HTML <title> element is meta data. It defines the HTML document's title.
➢ The title will not be displayed in the document, but might be displayed in the browser tab.
The HTML <meta> Element
➢ The HTML <meta> element is also meta data.
➢ It can be used to define the character set, and other information about the HTML
document.
HTML Paragraphs
➢ HTML documents are divided into paragraphs.
➢ The HTML <p> element defines a paragraph.
<p>This is a paragraph</p>
<p>This is another paragraph</p>
HTML Display
➢ You cannot be sure how HTML will be displayed.
➢ Large or small screens, and resized windows will create different results.
➢ With HTML, you cannot change the output by adding extra spaces or extra lines in your
HTML code.
➢ The browser will remove extra spaces and extra lines when the page is displayed.
➢ Any number of spaces, and any number of new lines, count as only one space.
<p>
This paragraph
contains a lot of lines
in the source code,
but the browser
ignores it.
</p>
<p>
This paragraph
contains a lot of spaces
in the source code,
but the browser
ignores it.
HTML Line Breaks
➢ The HTML <br> element defines a line break.
➢ Use <br> if you want a line break (a new line) without starting a new paragraph:
<p>This is<br>a para<br>graph with line breaks</p>
The HTML <pre> Element
➢ The HTML <pre> element defines preformatted text.
➢ The text inside a <pre> element is displayed in a fixed-width font (usually Courier), and
it preserves both spaces and line breaks:
< pre>
My Bonnie lies over the ocean.
My Bonnie lies over the sea.
Oh, bring back my Bonnie to me.
</pre>
HTML Styling
➢ Every HTML element has a default style (background color is white and text color is
black).
➢ Changing the default style of an HTML element, can be done with the style attribute.
➢ This example changes the default background color from white to lightgrey:
<body style="background-color:lightgrey">
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
The HTML Style Attribute
➢ The HTML style attribute has the following syntax:
style="property:value"
HTML Text Color
➢ The color property defines the text color to be used for an HTML element:
<h1 style="color:blue">This is a heading</h1>
<p style="color:red">This is a paragraph.</p>
HTML Fonts
➢ The font-family property defines the font to be used for an HTML element:
<h1 style="font-family:verdana">This is a heading</h1>
<p style="font-family:courier">This is a paragraph.</p>
HTML Text Size
➢ The font-size property defines the text size to be used for an HTML element:
<h1 style="font-size:300%">This is a heading</h1>
<p style="font-size:160%">This is a paragraph.</p>
HTML Text Alignment
➢ The text-align property defines the horizontal text alignment for an HTML element:
<h1 style="text-align:center">Centered Heading</h1>
<p>This is a paragraph.</p>
HTML Formatting Elements
➢ HTML uses elements like <b> and <i> for formatting output, like bold or italic text.
➢ Formatting elements were designed to display special types of text:
• Bold text
• Important text
• Italic text
• Emphasized text
• Marked text
• Small text
• Deleted text
• Inserted text
• Subscripts
• Superscripts
HTML Bold and Strong Formatting
➢ The HTML <b> element defines bold text, without any extra importance.
Example
<p>This text is normal.</p>
<p>This is a paragraph.</p>
<!-- Remember to add more information here -->
Conditional Comments
You might stumble upon conditional comments in HTML:
<!--[if IE 8]>
.... some HTML here ....
<![endif]-->
HTML Links
➢ Links are found in nearly all web pages. Links allow users to click their way from page to
page.
HTML Links - Hyperlinks
➢ HTML links are hyperlinks.
➢ A hyperlink is a text or an image you can click on, and jump to another document.
HTML Links - Syntax
➢ In HTML, links are defined with the <a> tag:
<a href="url">link text</a>
Local Links
➢ The example above used an absolute URL (A full web address).
➢ A local link (link to the same web site) is specified with a relative URL (without
http://www ... ).
Example:
<a href="html_images.asp">HTML Images</a>
HTML Links - Colors and Icons
➢ When you move the mouse cursor over a link, two things will normally happen:
• The mouse arrow will turn into a little hand
• The color of the link element will change
➢ By default, links will appear as this in all browsers:
• An unvisited link is underlined and blue
• A visited link is underlined and purple
• An active link is underlined and red
➢ You can change the defaults, using styles:
<style>
a:link {color:#000000; background-color:transparent; text-decoration:none}
a:visited {color:#000000; background-color:transparent; text-decoration:none}
a:hover {color:#ff0000; background-color:transparent; text-decoration:underline}
a:active {color:#ff0000; background-color:transparent; text-decoration:underline}
</style>
HTML Links - The target Attribute
➢ The target attribute specifies where to open the linked document.
➢ This example will open the linked document in a new browser window or in a new tab:
Example
<a href="http://www.w3schools.com/" target="_blank">Visit W3Schools!</a>
HTML Links - Image as Link
➢ It is common to use images as links:
Example
<a href="default.asp">
<img src="smiley.gif" alt="HTML tutorial" style="width:42px;height:42px;border:0">
</a>
HTML Links - The id Attribute
➢ The id attribute can be used to create bookmarks inside HTML documents.
➢ Bookmarks are not displayed in any special way. They are invisible to the reader.
Example
Add an id attribute to any <a> element:
<a id="tips">Useful Tips Section</a>
HTML Images
Syntax
➢ In HTML, images are defined with the <img> tag.
➢ The <img> tag is empty, it contains attributes only, and does not have a closing tag.
➢ The src attribute specifies the URL (web address) of the image:
<img src="url" alt="some_text"
Image Size - Width and Height
➢ You can use the style attribute to specify the width and height of an image.
➢ The values are specified in pixels (use px after the value):
Example
<img src="html5.gif" alt="HTML5 Icon" style="width:128px;height:128px;">
Animated Images
➢ The GIF standard allows animated images:
Example
<img src="programming.gif" alt="Computer Man" style="width:48px;height:48px;">
Image Floating
➢ Use the CSS float property to let the image float.
➢ The image can float to the right or to the left of a text:
Example
<p>
<img src="smiley.gif" alt="Smiley face" style="float:right;width:42px;height:42px;">
The image will float to the right of the text.
</p>
<p>
<img src="smiley.gif" alt="Smiley face" style="float:left;width:42px;height:42px;">
The image will float to the left of the text.
</p>
Image Maps
➢ Use the <map> tag to define an image-map. An image-map is an image with clickable
areas.
➢ The name attribute of the <map> tag is associated with the <img>'s usemap attribute and
creates a relationship between the image and the map.
➢ The <map> tag contains a number of <area> tags, that defines the clickable areas in the
image-map:
Example
<img src="planets.gif" alt="Planets" usemap="#planetmap" style="width:145px;height:126px;">
<map name="planetmap">
<area shape="rect" coords="0,0,82,126" alt="Sun" href="sun.htm">
<area shape="circle" coords="90,58,3" alt="Mercury" href="mercur.htm">
<area shape="circle" coords="124,58,8" alt="Venus" href="venus.htm">
</map>
HTML Tables
<table style="width:100%">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
➢ Tables are defined with the <table> tag.
➢ Tables are divided into table rows with the <tr> tag.
➢ Table rows are divided into table data with the <td> tag.
➢ A table row can also be divided into table headings with the <th> tag.
Table with a Border Attribute
➢ If you do not specify a border for the table, it will be displayed without borders.
➢ A border can be added using the border attribute:
<table border="1" style="width:100%">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
Table with Collapsed Borders
➢ If you want the borders to collapse into one border, add CSS border-collapse:
Example
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
Table with Cell Padding
➢ Cell padding specifies the space between the cell content and its borders.
➢ If you do not specify a padding, the table cells will be displayed without padding.
➢ To set the padding, use the CSS padding property:
Example
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
}
Table Headings
➢ Table headings are defined with the <th> tag.
➢ By default, all major browsers display table headings as bold and centered:
Example
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Points</th>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
Table with Border Spacing
➢ Border spacing specifies the space between the cells.
➢ To set the border spacing for a table, use the CSS border-spacing property:
Example
table {
border-spacing: 5px;
}
T able Cells that Span Many Columns
➢ To make a cell span more than one column, use the colspan attribute:
Example
<table style="width:100%">
<tr>
<th>Name</th>
<th colspan="2">Telephone</th>
</tr>
<tr>
<td>Bill Gates</td>
<td>555 77 854</td>
<td>555 77 855</td>
</tr>
</table>
HTML Lists
➢ HTML can have Unordered lists, Ordered lists, or Description lists:
Unordered HTML Lists
➢ An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
➢ The list items will be marked with bullets (small black circles).
Unordered List:
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Ordered HTML Lists
➢ An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.
➢ The list items will be marked with numbers.
Ordered List:
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
HTML Classes
<!DOCTYPE html>
<html>
<head>
<style>
.cities {
background-color:black;
color:white;
margin:20px;
padding:20px;
}
</style>
</head>
<body>
<div class="cities">
<h2>London</h2>
<p>
London is the capital city of England. It is the most populous city in the United Kingdom, with a
metropolitan area of over 13 million inhabitants.
</p>
</div>
</body>
</html>
Classing Block Elements
• The HTML <div> element is a block level element. It can be used as a container for
other HTML elements.
• Classing <div> elements, makes it possible to define equal styles for equal <div>
elements:
<!DOCTYPE html>
<html>
<head>
<style>
.cities {
background-color:black;
color:white;
margin:20px;
padding:20px;
}
</style>
</head>
<body>
<div class="cities">
<h2>London</h2>
<p>London is the capital city of England. It is the most populous city in the United Kingdom,
with a metropolitan area of over 13 million inhabitants.</p>
</div>
<div class="cities">
<h2>Paris</h2>
<p>Paris is the capital and most populous city of France.</p>
</div>
<div class="cities">
<h2>Tokyo</h2>
<p>Tokyo is the capital of Japan, the center of the Greater Tokyo Area,
and the most populous metropolitan area in the world.</p>
</div>
</body>
</html>
Classing Inline Elements
• The HTML <span> element is an inline element that can be used as a container for text.
• Classing <span> elements makes it possible to design equal styles for equal <span>
elements.
Example
<!DOCTYPE html>
<html>
<head>
<style>
span.red {color:red;}
</style> </head>
<body><h1>My <span class="red">Important</span> Heading</h1>
</body>
</html>
Example
var x; // Now x is undefined
var x = 5; // Now x is a Number
var x = "John"; // Now x is a String
JavaScript Numbers
➢ JavaScript has only one type of numbers.
➢ Numbers can be written with, or without decimals:
Example
var x1 = 34.00; // Written with decimals
var x2 = 34; // Written without decimals
JavaScript Booleans
➢ Booleans can only have two values: true or false.
Example
var x = true;
var y = false;
➢ Very often when you write code, you want to perform different actions for different
decisions.
➢ You can use conditional statements in your code to do this.
➢ In JavaScript we have the following conditional statements:
The if Statement
➢ Use the if statement to specify a block of JavaScript code to be executed if a condition is
true.
Syntax
if (condition) {
block of code to be executed if the condition is true
}
Example
Make a "Good day" greeting if the hour is less than 18:00:
if (hour < 18) {
greeting = "Good day";
}
The result of greeting will be:
Good day
Syntax
if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is true
} else {
block of code to be executed if the condition1 is false and condition2 is false
}
Example
➢ If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than
20:00, create a "Good day" greeting, otherwise a "Good evening":
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
Example
❖ The getDay() method returns the weekday as a number between 0 and 6. (Sunday=0,
Monday=1, Tuesday=2 ..)
❖ Use the weekday number to calculate weekday name:
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
}
The result of day will be:
Tuesday
The break Keyword
➢ When the JavaScript code interpreter reaches a break keyword, it breaks out of the
switch block.
➢ This will stop the execution of more code and case testing inside the block.
Text Input
➢ <input type="text"> defines a one-line input field for text input:
Example
<form>
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
</form>
Radio Button Input
➢ <input type="radio"> defines a radio button.
➢ Radio buttons let a user select ONE of a limited number of choices:
Example
<form>
<input type="radio" name="sex" value="male" checked>Male
<br>
<input type="radio" name="sex" value="female">Female
</form>
➢ The HTML <canvas> element is used to draw graphics, on the fly, via scripting (usually
JavaScript).
➢ The <canvas> element is only a container for graphics. You must use a script to actually
draw the graphics.
➢ Canvas has several methods for drawing paths, boxes, circles, text, and adding images.
Canvas Examples
➢ A canvas is a rectangular area on an HTML page. By default, a canvas has no border and
no content.
➢ The markup looks like this:
<canvas id="myCanvas" width="200" height="100"></canvas>
➢ Always specify an id attribute (to be referred to in a script), and a width and height
attribute to define the size of the canvas.
➢ To add a border, use the style attribute:
Basic Canvas Example
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>
Drawing with JavaScript
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,150,75);
Draw a Line
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
Draw a Circle
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
Draw a Text
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50);
Stroke Text
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.strokeText("Hello World",10,50);
Draw Image
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img,10,10);
Frames
• To use frames on a page we use <frameset> tag instead of <body> tag.
• The <frameset> tag defines how to divide the window into frames.
• The rows attribute of <frameset> tag defines horizontal frames and cols attribute
defines vertical frames.
• Each frame is indicated by <frame> tag and it defines which HTML document
shall open into the frame.
Format
<frameset rows="pixels|%|*">
Attribute Values
Value Description
pixels The row height in pixels (like "100px" or just "100")
% The row height in percent of the available space (like "50%")
* The rest of the available space should be assigned this row
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
"http://www.w3.org/TR/html4/frameset.dtd">
<html>
<head>
<title>Web Technology</title>
</head>
<frameset cols="200,*" frameborder="0" border="0" framespacing="0">
<frame name="menu" src="menu_1.html" marginheight="0" marginwidth="0"
scrolling="auto" noresize>
<frame name="content" src="content.html" marginheight="0" marginwidth="0"
scrolling="auto" noresize>
<noframes>
<p> Frame Example
</frameset>
</html>
8. Explain in detail about Client side scripting and server side scripting
Client-side scripting
➢ Client-side scripting generally refers to the class of computer programs on the web that
are executed client-side, by the user's web browser, instead of server-side (on the web
server).
➢ This type of computer programming is an important part of the Dynamic HTML
(DHTML) concept, enabling web pages to be scripted; that is, to have different and
changing content depending on user input, environmental conditions (such as the time of
day), or other variables.
➢ Client-side scripts are often embedded within an HTML or XHTML document (hence
known as an "embedded script"),
➢ but they may also be contained in a separate file, to which the document (or documents)
that use it make reference (hence known as an "external script").
➢ Upon request, the necessary files are sent to the user's computer by the web server (or
servers) on which they reside.
➢ The user's web browser executes the script, then displays the document, including any
visible output from the script.
➢ Client-side scripts may also contain instructions for the browser to follow in response to
certain user actions, (e.g., clicking a button).
➢ Often, these instructions can be followed without further communication with the server.
➢ By viewing the file that contains the script, users may be able to see its source code.
➢ Many web authors learn how to write client-side scripts partly by examining the source
code for other authors' scripts.
➢ In contrast, server-side scripts, written in languages such as PHP, ASP.NET, Java,
ColdFusion, Perl, Ruby, Go, Python, and server-side JavaScript, are executed by the web
server when the user requests a document.
➢ They produce output in a format understandable by web browsers (usually HTML),
which is then sent to the user's computer.
➢ The user cannot see the script's source code (unless the author publishes the code
separately), and may not even be aware that a script was executed.
➢ Documents produced by server-side scripts may, in turn, contain client-side scripts.
➢ Server-side scripts require that their language's interpreter be installed on the server, and
produce the same output regardless of the client's browser, operating system, or other
system details.
➢ Client-side scripts do not require additional software on the server (making them popular
with authors who lack administrative access to their servers); however, they do require
that the user's web browser understands the scripting language in which they are
written.
➢ It is therefore impractical for an author to write scripts in a language that is not supported
by popular web browsers.
➢ Due to security restrictions, client-side scripts may not be allowed to access the user's
computer beyond the web browser application.
➢ Techniques like ActiveX controls can be used to sidestep this restriction.
➢ Client-side scripting is not inherently unsafe. Users, though, are encouraged to always
keep their web browsers up-to-date to avoid exposing their computer and data to new
vulnerabilities.
➢ The latest group of web browsers and web pages tend to employ a heavy amount of
client-side scripting, accounting for an improved user interface in which the user does not
experience the unfriendly "refreshing" of the web page,
➢ but instead sees perhaps an animated GIF file indicating that the request occurred and the
page will be updated shortly.
➢ Ajax is an important addition to the JavaScript language, allowing web developers to
communicate with the web server in the background without requiring a completely new
version of the page to be requested and rendered.
➢ This leads to a much improved user experience in general.
➢ Unfortunately, even languages that are supported by a wide variety of browsers may not
be implemented in precisely the same way across all browsers and operating systems.
➢ Authors are well-advised to review the behaviour of their client-side scripts on a variety
of platforms before they put them into use.
Server-side scripting
➢ Server-side scripting is a technique used in web development which involves employing
scripts on a web server which produce a response customized for each user's (client's)
request to the website.
➢ The alternative is for the web server itself to deliver a static web page. Scripts can be
written in any of a number of server-side scripting languages that are available (see
below).
➢ Server-side scripting is distinguished from client-side scripting where embedded scripts,
such as JavaScript, are run client-side in a web browser, but both techniques are often
used together.
➢ Server-side scripting is often used to provide a customized interface for the user.
➢ These scripts may assemble client characteristics for use in customizing the response
based on those characteristics, the user's requirements, access rights, etc.
➢ Server-side scripting also enables the website owner to hide the source code that
generates the interface, whereas with client-side scripting, the user has access to all the
code received by the client.
➢ A down-side to the use of server-side scripting is that the client needs to make further
requests over the network to the server in order to show new information to the user via
the web browser.
➢ These requests can slow down the experience for the user, place more load on the server,
and prevent use of the application when the user is disconnected from the server.
➢ When the server serves data in a commonly used manner, for example according to the
HTTP or FTP protocols, users may have their choice of a number of client programs
(most modern web browsers can request and receive data using both of those
protocols).
➢ In the case of more specialized applications, programmers may write their own server,
client, and communications protocol, that can only be used with one another.
➢ Programs that run on a user's local computer without ever sending or receiving data over
a network are not considered clients, and so the operations of such programs would not
be considered client-side operations.
➢ The border-image property takes the image and slices it into nine sections, like a tic-tac-
toe board. It then places the corners at the corners, and the middle sections are repeated or
stretched as you specify.
➢ Here, the middle sections of the image are repeated to create the border:
➢ An image as a border!
Here is the code:
Example
#borderimg {
border: 10px solid transparent;
padding: 15px;
-webkit-border-image: url(border.png) 30 round; /* Safari 3.1-5 */
order-image: url(border.png) 30 round; /* Opera 11-12.1
*/border-image: url(border.png) 30 round;
}
CSS3 Backgrounds
➢ CSS3 contains a few new background properties, which allow greater control of the
background element.
➢ how to add multiple background images to one element.
➢ You will also learn about the following new CSS3 properties:
• background-size
• background-origin
• background-clip
CSS3 Multiple Backgrounds
➢ CSS3 allows you to add multiple background images for an element, through the
background-image property.
➢ The different background images are separated by commas, and the images are stacked
on top of each other, where the first image is closest to the viewer.
➢ The following example has two background images, the first image is a flower (aligned
to the bottom and right) and the second image is a paper background (aligned to the top-
left corner):
Example
#example1 {
background-image: url(img_flwr.gif), url(paper.gif);
background-position: right bottom, left top;
background-repeat: no-repeat, repeat;
}
#div1 {
background: url(img_flower.jpg);
background-size: 100px 80px;
background-repeat: no-repeat;
} Full Size Background Image
➢ Now we want to have a background image on a website that covers the entire browser
window at all times.
➢ The requirements are as follows:
• Fill the entire page with the image (no white space)
• Scale image as needed
• Center image on page
• Do not cause scrollbars
➢ The following example shows how to do it; Use the html element (the html element is
always at least the height of the browser window).
➢ Then set a fixed and centered background on it. Then adjust its size with the background-
size property:
Example
html {
background: url(img_flower.jpg) no-repeat center center fixed;
background-size: cover;
Example
#example1 {
border: 10px solid black;
padding:35px;
background:url(img_flwr.gif);
background-repeat: no-repeat;
background-origin: content-box; }
CSS3 Colors
➢ CSS supports color names, hexadecimal and RGB colors.
➢ In addition, CSS3 also introduces:
• RGBA colors
• HSL colors
• HSLA colors
• opacity
➢ RGBA Colors
• RGBA color values are an extension of RGB color values with an alpha channel -
which specifies the opacity for a color.
• An RGBA color value is specified with: rgba(red, green, blue, alpha). The alpha
parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque)
Example
#p1 {background-color: rgba(255, 0, 0, 0.3);} /* red with opacity */
#p2 {background-color: rgba(0, 255, 0, 0.3);} /* green with opacity */
#p3 {background-color: rgba(0, 0, 255, 0.3);} /* blue with opacity */
➢ HSL Colors
• HSL stands for Hue, Saturation and Lightness.
• An HSL color value is specified with: hsl(hue, saturation, lightness).
✓ Hue is a degree on the color wheel (from 0 to 360):
➢ HSLA Colors
• HSLA color values are an extension of HSL color values with an alpha channel -
which specifies the opacity for a color.
• An HSLA color value is specified with: hsla(hue, saturation, lightness, alpha), where
the alpha parameter defines the opacity.
• The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully
opaque).
Example
#p1 {background-color: hsla(120, 100%, 50%, 0.3);} /* green with opacity */
#p2 {background-color: hsla(120, 100%, 75%, 0.3);} /* light green with opacity */
#p3 {background-color: hsla(120, 100%, 25%, 0.3);} /* dark green with opacity */
#p4 {background-color: hsla(120, 60%, 70%, 0.3);} /* pastel green with opacity */
Opacity
• The CSS3 opacity property sets the opacity for a specified RGB value.
• The opacity property value must be a number between 0.0 (fully transparent) and 1.0
#p1 {background-color:rgb(255,0,0);opacity:0.6;} /* red with opacity */
#p2 {background-color:rgb(0,255,0);opacity:0.6;} /* green with opacity */
#p3 {background-color:rgb(0,0,255);opacity:0.6;} /* blue with opacity */
CSS3 Gradients
• CSS3 gradients let you display smooth transitions between two or more specified colors.
• Earlier, you had to use images for these effects.
• However, by using CSS3 gradients you can reduce download time and bandwidth usage.
• In addition, elements with gradients look better when zoomed, because the gradient is
generated by the browser.
CSS3 defines two types of gradients:
• Linear Gradients (goes down/up/left/right/diagonally)
• Radial Gradients (defined by their center)
• You can also set a starting point and a direction (or an angle) along with the gradient
effect.
Syntax
background: linear-gradient(direction, color-stop1, color-stop2, ...);
UNIT-II JAVA
PART A
1. When super keyword is used?
If the method overrides one of its superclass's methods, overridden method can be
invoked through the use of the keyword super. It can be also used to refer to a hidden field.
2. Explain Runtime Exceptions?
It is an exception that occurs that probably could have been avoided by the programmer.
As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.
3. What do you mean by Checked Exceptions?
It is an exception that is typically a user error or a problem that cannot be foreseen by the
programmer. For example, if a file is to be opened, but the file cannot be found, an exception
occurs. These exceptions cannot simply be ignored at the time of compilation.
4. What is the difference between StringBuffer and StringBuilder class?
Use StringBuilder whenever possible because it is faster than StringBuffer. But, if thread
safety is necessary then use StringBuffer objects.
5. What is Abstract class?
These classes cannot be instantiated and are either partially implemented or not at all
implemented. This class contains one or more abstract methods which are simply method
declarations without a body.
6. What is an Interface?
An interface is a collection of abstract methods. A class implements an interface, thereby
inheriting the abstract methods of the interface.
7. What are the two ways in which Thread can be created?
Thread can be created by:
1. implementing Runnable interface
2. extending the Thread class
8. Difference between throw and throws?
It includes:
Throw is used to trigger an exception where as throws is used in declaration of exception.
Without throws, Checked exception cannot be handled where as checked exception can be
propagated with throws.
9. What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state. When a task invokes
its sleep() method, it returns to the waiting state.
10. 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 theInputStream/OutputStream class
hierarchy is byte-oriented.
11. What's the difference between the methods sleep() and wait()?
The code sleep(2000); puts thread aside for exactly two seconds. The code wait(2000),
causes a wait of up to two second. A thread could stop waiting earlier if it receives the notify() or
notifyAll() call. The method wait() is defined in the class Object and the method sleep() is
defined in the class Thread.
12. What is the difference between error and an exception?
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error.
Exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will
be thrown if the specified file does not exist.
13. What is 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.
14. Difference between the super and this keyword.
In the constructor, this() calls a constructor defined in the current class. super() calls a
constructor defined in the parent class.
15. Does java support multiple inheritance? Justify.
Java does not support multiple inheritance using class, but it provides the facility by
interface in order to avoid multiple instances parent class for child classes.
16. What is the need for Buffered Reader and BufferedInputStream class? What is the
difference between Reader/writer and InputStream/outputStream?
Buffered reader-character oriented, used o read text data and faster.
BufferedInputStream-byte oriented, used to read image, binary and sequential data ,
slower.
17. What is the importance of == and equals () methods with respect to string object?
Both equals() method and == operator is used to compare two objects in Java. == is an
operator and equals() is method. But == operator compare reference or memory location of
objects in the heap, whether they point to the same location or not .
equals() method the main purpose is to compare the state of two objects or contents of the
object are equal or not.
18. What is Inheritance?
Inheritance is a mechanism in which one object acquires all the properties and behaviour
of another object of another class. It represents IS-A relationship. It is used for Code Resusability
and Method Overriding.
19. What is cloning?
The object cloning is a way to create exact copy of an object. For this purpose, clone()
method of Object class is used to clone an object. Less processing task.
20. Mention the purpose of the Keyword 'final'.
It is used with variables to make its values not to be changed.
The final keyword can be applied with the variables, a final variable that have no value
it is called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blankfinal variable can be static also which will be initialized in the static
block only.
21. Write down the fundamentals of exception handling?
o Exception is an event that occurs at the time of execution of a program.
o It disrupts the normal flow of the program.
o It is an object that describes the exceptional condition that occurs at the runtime of
the program.
o Exception will happen due to improper input, resource not found and so on..
Exception Handling: Java exception handling is done using five keywords: try, catch,
throw, throws, finally.
Try: This block helps program to monitor whether an exception arises or not.
catch: The exception is catched and handled here.
throw:Manually throws an exception out of the method.
throws:Any exception that is thrown out is specified here.
finally: Any code that has to be executed before a method returns is placed here.
Exception handling block:
Try
{ //code to monitor whether an exception arises or not }
catch (ExceptionType_1 exobject)
{ //Exception handler }
Finally
{ // code to be executed before try block ends }
22. What are Java Packages? What’s the significance of packages?
In Java, package is a collection of classes and interfaces which are bundled together as
they are related to each other. Use of packages helps developers to modularize the code and
group the code for proper re-use. Once code has been packaged in Packages, it can be imported
in other classes and used.
23. How an object is serialized in java?
In java, to convert an object into byte stream by serialization, an interface with the name
Serializable is implemented by the class. All objects of a class implementing serializable
interface get serialized and their state is saved in byte stream.
24. When we should use serialization?
Serialization is used when data needs to be transmitted over the network. Using
serialization, object’s state is saved and converted into byte stream .The byte stream is
transferred over the network and the object is re-created at destination.
25. Why Strings in Java are called as Immutable?
In java, string objects are called immutable as once value has been assigned to a string, it
can’t be changed and if changed, a new object is created.
26. What is multi-threading?
Multi threading is a programming concept to run multiple tasks in a concurrent manner
within a single program. Threads share same process stack and running in parallel. It helps in
performance improvement of any program.
27. How garbage collection is done in Java?
In java, when an object is not referenced any more, garbage collection takes place and the
object is destroyed automatically. For automatic garbage collection java calls either System.gc()
method or Runtime.gc() method.
28. How destructors are defined in Java?
In Java, there are no destructors defined in the class as there is no need to do so. Java has
its own garbage collection mechanism which does the job automatically by destroying the
objects when no longer referenced.
29. What’s meant by anonymous class?
An anonymous class is a class defined without any name in a single line of code using
new keyword.
30. Can we override static methods of a class?
We cannot override static methods. Static methods belong to a class and not to individual
objects and are resolved at the time of compilation (not at runtime).Even if we try to override
static method,we will not get an complitaion error, nor the impact of overriding when running
the code.
PART-B
1. Explain briefly the following object oriented concepts.
(i) Abstraction and Encapsulation.
(ii) Methods and messages.
(iii) Inheritance.
(iv) Polymorphism.
(v) Object and Class
OBJECT:
➢ Objects are key to understanding object-oriented technology.
➢ Examples of real-world objects: dog,desk, television set, your bicycle.
➢ Real-world objects share two characteristics: They all have state and behavior.
➢ Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging
tail).
A software object.
➢ Software objects are conceptually similar to real-world objects: they too consist of state
and related behavior.
➢ An object stores its state in fields (variables in some programming languages) and
exposes its behavior through methods (functions in some programming languages).
➢ Methods operate on an object's internal state and serve as the primary mechanism for
object-to-object communication. Hiding internal state and requiring all interaction to be
performed through an object's methods is known as data encapsulation — a fundamental
principle of object-oriented programming.
Consider a bicycle, for example:
➢ Sometimes the receiving object needs more information so that it knows exactly what to
do—
➢ For example, when you want to change gears on your bicycle, you have to indicate which
gear you want. This information is passed along with the message as parameters.
➢ Three components comprise a message:
❖ The object to whom the message is addressed (Your Bicycle)
❖ The name of the method to perform (changeGears)
❖ Any parameters needed by the method (lower gear)
Local Variable
➢ A variable that is declared inside the method is called local variable.
Instance Variable
➢ A variable that is declared inside the class but outside the method is called instance
variable . It is not declared as static.
Static variable
➢ A variable that is declared as static is called static variable. It cannot be local.
Example
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class
Data Types
➢ In java, there are two types of data types
• primitive data types
• non-primitive data types
➢ Java provides a data structure, the array, which stores a fixed-size sequential collection
of elements of the same type.
➢ An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.
➢ Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
Declaring Array Variables:
➢ To use an array in a program, you must declare a variable to reference the array, and you
must specify the type of array the variable can reference.
➢ Here is the syntax for declaring an array variable:
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Example:
The following code snippets are examples of this syntax:
double[] myList; // preferred way.
or
double myList[]; // works but not preferred way.
Creating Arrays:
➢ You can create an array by using the new operator with the following syntax:
arrayRefVar = new dataType[arraySize];
➢ The above statement does two things:
• It creates an array using new dataType[arraySize];
• It assigns the reference of the newly created array to the variable arrayRefVar.
➢ Declaring an array variable, creating an array, and assigning the reference of the array to
the variable can be combined in one statement, as shown below:
dataType[] arrayRefVar = new dataType[arraySize];
➢ Alternatively you can create arrays as follows:
dataType[] arrayRefVar = {value0, value1, ..., valuek};
➢ The array elements are accessed through the index. Array indices are 0-based; that is,
they start from 0 to arrayRefVar.length-1.
Example:
➢ Following statement declares an array variable, myList, creates an array of 10 elements
of double type, and assigns its reference to myList.:
double[] myList = new double[10];
➢ Following picture represents array myList. Here myList holds ten double values and the
indices are from 0 to 9.
Processing Arrays:
➢ When processing array elements, we often use either for loop or foreach loop because all
of the elements in an array are of the same type and the size of the array is known.
Example:
➢ Here is a complete example of showing how to create, initialize and process arrays:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}}
Passing Arrays to Methods:
➢ Just as you can pass primitive type values to methods, you can also pass arrays to
methods.
➢ For example, the following method displays the elements in an int array:
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " "); }}
➢ You can invoke it by passing an array. For example, the following statement invokes the
printArray method to display 3, 1, 2, 6, 4, and 2:
printArray(new int[]{3, 1, 2, 6, 4, 2});
Returning an Array from a Method:
➢ A method may also return an array. For example, the method shown below returns an
array that is the reversal of another array:
➢ Example
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
result[j] = list[i];
} return result; }
THE ARRAYS CLASS:
➢ The java.util.Arrays class contains various static methods for sorting and searching
arrays, comparing arrays, and filling array elements.
➢ These methods are overloaded for all primitive types.
public static int binarySearch(Object[] a, Object key)
5. Briefly explain the various operator in java
➢ Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups:
▪ Arithmetic Operators
▪ Relational Operators
▪ Bitwise Operators
▪ Logical Operators
▪ Assignment Operators
The Arithmetic Operators:
➢ Arithmetic operators are used in mathematical expressions in the same way that they are
used in algebra. The following table lists the arithmetic operators:
➢ Assume integer variable A holds 10 and variable B holds 20, then:
Operator Description Example
+ Addition - Adds values on either side of the operator A + B will give 30
- Subtraction - Subtracts right hand operand from left hand operand A - B will give -10
A * B will give
* Multiplication - Multiplies values on either side of the operator
200
/ Division - Divides left hand operand by right hand operand B / A will give 2
Modulus - Divides left hand operand by right hand operand and
% B % A will give 0
returns remainder
++ Increment - Increases the value of operand by 1 B++ gives 21
-- Decrement - Decreases the value of operand by 1 B-- gives 19
Hybrid Inheritance:
➢ More than one type of inheritance is used. (Eg. Hierarchical and multilevel).
public class Super {
int A;
void printA()
{
System.out.println("A="+A);
}}
public class SubSuper extends Super {
int B=20;
{
A = 10;
}
void printB()
{
System.out.println("B="+B);
} }
public class Sub1 extends Super {
int B=2;
{
A=1;
}
void print()
{ printA();
System.out.println("B="+B);
}}
public class Sub2 extends SubSuper {
int C=30;
void print()
{ printA();
printB();
System.out.println("C="+C);
} }
public class Sample {
public static void main(String[] args) {
Sub1 a=new Sub1();
Sub2 b=new Sub2();
System.out.println("Subclass 1");
a.print();
System.out.println("Subclass 2");
b.print();
} }
Creation of Package:
Package <Package Name>
Importing classes
Method1:
java.util.Date birthday=new java.util.Date();
➢ util is the package within the package java. Date is the class name.
Method 2:
Import java.awt.Button; // imports Button class in that package
Import java.awt.*; // * imports all class in that package
Method 3:
Imort static MyPackage.A.display(); // Import static members(display() only) in that package
Imort static MyPackage.A.*; // Import All static members in that package
import java.applet.*;
import java.awt.*;
public class AnimApplet extends Applet implements Runnable
{ Image[] images = new Image[2];
int frame = 0;
volatile Thread thread;
public void init() {
images[0] = getImage(getDocumentBase(),
"http://hostname/image0.gif");
images[1] = getImage(getDocumentBase(),
"http://hostname/image1.gif");
}
public void start() {
(thread = new Thread(this)).start(); }
public void stop() {
thread = null; }
public void paint(Graphics g) {
g.drawImage(images[frame], 0, 0, this); }
public void run() {
int delay = 1000; // 1 second
try {
while (thread == Thread.currentThread()) {
frame = (frame+1)%images.length;
repaint();
Thread.sleep(delay);
} } catch (Exception e) {
} }}
Syntax
[visibility] interface InterfaceName [extends other interfaces]
{
constant declarations
}
public interface Comparable
{ boolean less(Object m);
boolean greater(Object m);
boolean lessEqual(Object m);
boolean greaterEqual(Object m);
}
➢ All instance methods are implicitly public and abstract. You can mark them as such, but
are discouraged from doing so as the marking is considered obsolete practice.
➢ The interfaces themselves need not be public and several interfaces in the standard
libraries are not public and thus used only internally.
➢ An interface creates a protocol that classes may implement. Note that one can extend an
interface (to get a new interface) just as you can extend a class.
➢ One can actually extend several interfaces.
➢ Interfaces thus enjoy the benefits of multiple inheritance. (Classes do not.) There are
almost no disadvantages to multiple inheritance of interface.
➢ There are large disadvantages to multiple inheritance of implementation as in C++.
➢ These include efficiency considerations as well as the semantic difficulty of determining
just what code will be executed in some circumstances.
➢ The Polynomial class that implements Comparable will need to implement all of the
functions declared in the interface.
public class Polynomial implements Comparable
{ ...
boolean less(Object m){ . . . }
boolean greater(Object m){ . . . }
boolean lessEqual(Object m){ . . . }
boolean greaterEqual(Object m){ . . . }
Interface IntExample
{
public void sayHello();
}
public class JavaInterfaceExample implements IntExample
{
public void sayHello()
{
System.out.println("Hello Visitor !");
}
public static void main(String args[])
{
JavaInterfaceExample javaInterfaceExample = new JavaInterfaceExample();
javaInterfaceExample.sayHello();
}}
10. Briefly explain about string class and its methods
STRINGS
➢ Strings, which are widely used in Java programming, are a sequence of characters. In the
Java programming language, strings are objects.
➢ The Java platform provides the String class to create and manipulate strings.
Creating Strings:
String greeting = "Hello world!";
➢ Whenever it encounters a string literal in your code, the compiler creates a String object
with its value in this case, "Hello world!'.
➢ As with any other object, you can create String objects by using the new keyword and a
constructor.
➢ The String class has eleven constructors that allow you to provide the initial value of the
string using different sources, such as an array of characters.
public class StringDemo{
public static void main(String args[]){
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new String(helloArray);
System.out.println( helloString ); }}
String Methods:
➢ Here is the list of methods supported by String class:
SN Methods with Description
char charAt(int index)
1
Returns the character at the specified index.
int compareTo(Object o)
2
Compares this String to another Object.
int compareTo(String anotherString)
3
Compares two strings lexicographically.
int compareToIgnoreCase(String str)
4
Compares two strings lexicographically, ignoring case differences.
String concat(String str)
5
Concatenates the specified string to the end of this string.
boolean contentEquals(StringBuffer sb)
6 Returns true if and only if this String represents the same sequence of characters as the
specified StringBuffer.
static String copyValueOf(char[] data)
7
Returns a String that represents the character sequence in the array specified.
static String copyValueOf(char[] data, int offset, int count)
8
Returns a String that represents the character sequence in the array specified.
boolean endsWith(String suffix)
9
Tests if this string ends with the specified suffix.
EXCEPTION HIERARCHY:
TYPES OF ECEPTION HANDLIG:
➢ Checked exceptions – inability to acquire system resources (such as insufficient
memory, file does not exist)
❖ Java checks at compile time that some mechanism is explicitly in place to receive
and process an exception object that may be created during runtime due to one of
these exceptions occurring.
➢ Unchecked exceptions – exceptions that occur because of the user entering bad data,
or failing to enter data at all.
❖ Unchecked exceptions can be avoided by writing more robust code that protects
against bad input values. Java does not check at compile time to ensure that there
is a mechanism in place to handle such errors.
GENERAL SYNTAX:
try {
//statements – one of which is capable of throwing an exception
}
catch (ExceptionTypeName objName)
{
//one or more statements to execute if this exception occurs
}
finally
{
//statements to be executed whether or not exception occurs
}
EXAMPLE:
package Exception;
public class MainClass {
public static void main(String args[]) {
int d, a;
try {
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e) {
System.out.println("Division by zero."); }
System.out.println("After catch statement.");
} }
FINALLY BLOCK
➢ An optional finally block can be added at the end of the catch blocks to provide a set of
statements that are always executed whether or not an exception occurs. Finally block is
executed independent of exception and catch. It is executed before return statement.
Example:
package Exception;
class FinallyDemo {
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally
{ System.out.println("procA's finally");
} }
static void procB() {
try {
System.out.println("inside procB");
return;
} finally
{ System.out.println("procB's finally");
} }
static void procC() {
try { System.out.println("inside procC");
} finally {
System.out.println("procC's finally"); } }
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
} }
NESTED TRY – CATCH AND MULTIPLE CATCH BLOCK
➢ Each catch block works like a method definition. If the catch parameter matches with the
type of exception object thrown, then exception is caught and statements in the catch
block will be executed.
➢ The try and catch block within outer try block behaves like independent try and catch
block
Example
public class NestedTry
{
public static void main (String args[])throws IOException
{
int num=2,res=0;
try
{ FileInputStream fis=null;
fis = new FileInputStream (new File (args[0]));
try
{ res=num/0;
System.out.println("The result is"+res);
}
catch(ArithmeticException e)
{ System.out.println("divided by Zero");
} }
catch (FileNotFoundException e)
{ System.out.println("File not found!"); }
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println("Array index is Out of bound! Argument required"); }}}
➢ A multithreaded program contains two or more parts that can run concurrently and each
part can handle different task at the same time making optimal use of the available
resources specially when your computer has multiple CPUs.
➢ By definition multitasking is when multiple processes share common processing
resources such as a CPU. Multithreading extends the idea of multitasking into
applications where you can subdivide specific operations within a single application into
individual threads. Each of the threads can run in parallel. The OS divides processing
time not only among different applications, but also among each thread within an
application.
➢ Multithreading enables you to write in a way where multiple activities can proceed
concurrently in the same program.
Life Cycle of a Thread:
➢ New: A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
➢ Runnable: After a newly born thread is started, the thread becomes runnable. A thread in
this state is considered to be executing its task.
➢ Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task.A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
➢ Timed waiting: A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when that
time interval expires or when the event it is waiting for occurs.
➢ Terminated: A runnable thread enters the terminated state when it completes its task or
otherwise terminates
Thread Priorities:
➢ Every Java thread has a priority that helps the operating system determine the order in
which threads are scheduled.
➢ Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Create Thread by Implementing Runnable Interface:
➢ If your class is intended to be executed as a thread then you can achieve this by
implementing Runnable interface. You will need to follow three basic steps:
Step 1:
➢ As a first step you need to implement a run() method provided by Runnable interface.
This method provides entry point for the thread and you will put you complete business
logic inside this method. Following is simple syntax of run() method:
public void run( )
Step 2:
➢ At second step you will instantiate a Thread object using the following constructor:
Thread(Runnable threadObj, String threadName);
➢ Where, threadObj is an instance of a class that implements the Runnable interface and
threadName is the name given to the new thread.
Step 3
➢ Once Thread object is created, you can start it by calling start( ) method, which executes
a call to run( ) method. Following is simple syntax of start() method:
void start( );
Example
class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo( String name){
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
} System.out.println("Thread " + threadName + " exiting.");
}
public void start ()
{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start (); } }}
public class TestThread {
public static void main(String args[]) {
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start(); } }
Create Thread by Extending Thread Class:
➢ The second way to create a thread is to create a new class that extends Thread class
using the following two simple steps.
➢ This approach provides more flexibility in handling multiple threads created using
available methods in Thread class.
Step 1
➢ You will need to override run( ) method available in Thread class.
➢ This method provides entry point for the thread and you will put you complete business
logic inside this method. Following is simple syntax of run() method:
public void run( )
Step 2
➢ Once Thread object is created, you can start it by calling start( ) method, which executes
a call to run( ) method. Following is simple syntax of start() method:
void start( )
Example
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
ThreadDemo( String name){
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
} } catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
} System.out.println("Thread " + threadName + " exiting.");
}
public void start ()
{
System.out.println("Starting " + threadName );
if (t == null)
{ t = new Thread (this, threadName);
t.start ();
} }}
public class TestThread {
public static void main(String args[]) {
ThreadDemo T1 = new ThreadDemo( "Thread-1");
T1.start();
ThreadDemo T2 = new ThreadDemo( "Thread-2");
T2.start();
} }
Thread Methods:
public void start()
➢ Starts the thread in a separate path of execution, then invokes the run() method on this
Thread object.
public void run()
➢ If this Thread object was instantiated using a separate Runnable target, the run() method
is invoked on that Runnable object.
public final void setName(String name)
➢ Changes the name of the Thread object. There is also a getName() method for retrieving
the name.
public final void setPriority(int priority)
➢ Sets the priority of this Thread object. The possible values are between 1 and 10.
public final void setDaemon(boolean on)
➢ A parameter of true denotes this Thread as a daemon thread.
public final void join(long millisec)
➢ The current thread invokes this method on a second thread, causing the current thread to
block until the second thread terminates or the specified number of milliseconds passes.
public void interrupt()
➢ Interrupts this thread, causing it to continue execution if it was blocked for any reason.
public final boolean isAlive()
➢ Returns true if the thread is alive, which is any time after the thread has been started but
before it runs to completion.
public static void yield()
➢ Causes the currently running thread to yield to any other threads of the same priority that
are waiting to be scheduled.
public static void sleep(long millisec)
➢ Causes the currently running thread to block for at least the specified number of
milliseconds.
public static boolean holdsLock(Object x)
➢ Returns true if the current thread holds the lock on the given Object.
public static Thread currentThread()
➢ Returns a reference to the currently running thread, which is the thread that invokes this
method.
public static void dumpStack() Prints the stack trace for the currently running thread, which
is useful when debugging a multithreaded application.
UNIT – III JDBC
PART A
1. What is JDBC?
JDBC is java database connectivity as name implies it’s a java API for communicating to
relational database, API has java classes and interfaces using that developer can easily interact
with database.
2. Difference between type 2 and type 4 JDBC drivers.
Type 1 JDBC Driver is called JDBC-ODBC Bridge driver (bridge driver)
Type 2 JDBC Driver is referred as Native-API/partly Java driver (native driver)
Type 3 JDBC Driver is called AllJava/Net-protocol driver (middleware driver)
Type 4 JDBC Driver is called All Java/Native-protocol driver (Pure java driver)
3. What are the main steps in java to make JDBC connectivity?
Main steps to connect to database.
➢ Load the Driver: First step is to load the database specific driver which communicates
with database.
➢ Make Connection: Next step is get connection from the database using connection
object, which is used to send SQL statement also and get result back from the database.
➢ Get Statement object: From connection object we can get statement object which is
used to query the database
➢ Execute the Query: Using statement object we execute the SQL or database query and
get result set from the query.
➢ Close the connection: After getting resultset and all required operation performed the
last step should be closing the database connection.
4. What are different types of Statement?
Statement object is used to send SQL query to database and get result from database, and
we get statement object from connection object.
There are three types of statement:
Statement: it’s a commonly used for getting data from database useful when we are using
static SQL statement at runtime. it will not accept any parameter.
Statement stmt = conn.createStatement( );
ResultSet rs = stmt.executeQuery();
PreparedStatement: when we are using same SQL statement multiple time its is useful and it
will accept parameter at runtime.
String SQL = "Update stock SET limit = ? WHERE stockType = ?";
PreparedStatement pstmt = conn.prepareStatement(SQL);
ResultSet rs = pstmt.executeQuery();
Callable Statement: when we want to access stored procedures then callable statement are
useful and they also accept runtime parameter. It is called like this
CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
5. How cursor works in scrollable result set?
There are three constant define in result set by which we can move cursor.
TYPE_FORWARD_ONLY: creates a nonscrollable result set, that is, one in which the cursor
moves only forward
TYPE_SCROLL_INSENSITIVE : a scrollable result set does not reflects changes that are
made to it while it is open
TYPE_SCROLL_SENSITIVE: a scrollable result set reflects changes that are made to it while
it is open
6. What is connection pooling?
Connection pooling is the mechanism by which we reuse the recourse like connection
objects which are needed to make connection with database .In this mechanism client are not
required every time make new connection and then interact with database instead of that
connection objects are stored in connection pool and client will get it from there.
7. Does the JDBC-ODBC Bridge support multiple concurrent open statements per
connection?
No, we can open only one statement object when using JDBC-ODBC Bridge.
8. Is it possible to send an object using Sockets, if so, how it can be?
Yes it is Poosible to send an Object using Sockets. Objects that implement Serializable
may be sent across a socket connection using an ObjectInputStream and ObjectOutputStream
combination.
9. How does server know that a client is connected to it or not?
When a task invokes its yield() method, it returns to the ready state. When a task invokes its
sleep() method, it returns to the waiting state.
10. What is Domain Naming Service (DNS)?
DNS stands for Domain Name System, an Internet service that translates domain names
into IP addressess.
11. What is Inet address?
InetAddress is a class used to find the ip address of a host in a network. This InetAddress
is divided into two types,
1)Inet4address for the ip version 4(ipv4)=Which has 32bit ip address
2)Inet6address for the ip version 6(ipv6)=Which has 128bit ip address
There are subclasses & abstract in the InetAddress.
12. What is URL?
URL stands for Uniform Resource Locator and it points to resource files on the Internet.
URL has four components. http://www.allinterview.com:80/index.html http - protocol name,
allinterview - IP address or host name, 80 - port number, index.html - file
13. What is meant by TCP, IP, UDP?
TCP:its a protocal for transfering data that is reliable and commonly used. IP: It's
Internet Protocol, every computer available on the network has a unique IP. TCP and IP
both works together and this is called TCP/IP.
UDP:its unreliable but fast mode of transfering data.
14. What is the difference between TCP and UDP ?
• TCP is guaranteed delivery, UDP is not guaranteed.
• TCP guarantees order of messages, UDP doesn’t.
• Data boundary is not preserved in TCP, but UDP preserves it.
• TCP is slower compared to UDP.
15. What is the difference between TCP/IP and TCP?
The difference is that TCP is responsible for the data delivery of a packet and IP is
responsible for the logical addressing. In other words, IP obtains the address and TCP guarantees
delivery of data to that address.
16. What is meant by time-slicing?
Preemptive multitasking also called "time slicing". Interrupting the execution of a process
and passing control to another waiting process and performing a context switch after which the
context for the next pending process is restored, and the next process is executed for the duration
of its time slice or "quantum".
17. What is the difference between IO and NIO?
The main difference between NIO and IO is that NIO provides asynchronous, non
blocking IO, which is critical to write faster and scalable networking systems. On the other hand,
most of the utilities from the IO classes are blocking and slow. NIO takes advantage of
asynchronous system calls in UNIX systems such as the select() system call for network sockets.
Using select(), an application can monitor several resources at the same time and can also poll
for network activity without blocking. The select() system call identifies if data is pending or not,
then read() or write() may be used knowing that they will complete immediately.
18. What is javabean?
JavaBeans are classes that encapsulate many objects into a single object (the bean).
They are serializable, have a zero-argument constructor, and allow access to properties using
getter and setter methods.
19. What are advantage and disadvantage of java sockets?
Advantages:
a. Flexible and powerful.
b. Cause low network traffic if efficiently used.
c. Only updated information can be sent.
Disadvantages:
a. The Java applets can establish communication only with the machine requested and not with
any other machine on the network.
b. Sockets allow only raw data to be sent. This means that both client and server need to have
mechanisms to interpret the data.
20. What is Socket?
• A socket is an endpoint for communication between two machines.
• Java Socket programming can be connection-oriented or connection-less.
• Socket and ServerSocket classes are used for connection-oriented socket programming
and DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
• The client in socket programming must know two information:
1. IP Address of Server, and
2. Port number.
PART-B
1. Explain in detail about JDBC Architecture.
JDBC
• JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of
databases.
❖ The JDBC library includes APIs for each of the tasks mentioned below that are
commonly associated with database usage.
❖ Making a connection to a database.
❖ Creating SQL or MySQL statements.
❖ Executing SQL or MySQL queries in the database.
❖ Viewing & Modifying the resulting records.
➢ Fundamentally, JDBC is a specification that provides a complete set of interfaces that
allows for portable access to an underlying database.
➢ Java can be used to write different types of executables, such as −
❖ Java Applications
❖ Java Applets
❖ Java Servlets
❖ Java ServerPages (JSPs)
❖ Enterprise JavaBeans (EJBs).
➢ All of these different executables are able to use a JDBC driver to access a database, and
take advantage of the stored data.
➢ JDBC provides the same capabilities as ODBC, allowing Java programs to contain
database-independent code.
Pre-Requisite
➢ Before moving further, you need to have a good understanding of the following two
subjects −
❖ Core JAVA Programming
❖ SQL or MySQL Database
JDBC Architecture
➢ The JDBC API supports both two-tier and three-tier processing models for database
access but in general, JDBC Architecture consists of two layers −
➢ JDBC API: This provides the application-to-JDBC Manager connection.
➢ JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.
➢ The JDBC API uses a driver manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases.
➢ The JDBC driver manager ensures that the correct driver is used to access each data
source.
➢ The driver manager is capable of supporting multiple concurrent drivers connected to
multiple heterogeneous databases.
➢ Following is the architectural diagram, which shows the location of the driver
manager with respect to the JDBC drivers and the Java application −
Common JDBC Components
➢ The JDBC API provides the following interfaces and classes −
➢ DriverManager:
❖ This class manages a list of database drivers. Matches connection requests from
the java application with the proper database driver using communication sub
protocol.
❖ The first driver that recognizes a certain subprotocol under JDBC will be used to
establish a database Connection.
➢ Driver:
❖ This interface handles the communications with the database server. You will
interact directly with Driver objects very rarely.
❖ Instead, you use DriverManager objects, which manages objects of this type. It
also abstracts the details associated with working with Driver objects.
➢ Connection:
❖ This interface with all methods for contacting a database. The connection object
represents communication context, i.e., all communication with database is
through connection object only.
➢ Statement:
❖ You use objects created from this interface to submit the SQL statements to the
database.
❖ Some derived interfaces accept parameters in addition to executing stored
procedures.
➢ ResultSet:
❖ These objects hold data retrieved from a database after you execute an SQL query
using Statement objects.
❖ It acts as an iterator to allow you to move through its data.
➢ SQLException:
❖ This class handles any errors that occur in a database application.
The JDBC 4.0 Packages
➢ The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the latest
JDBC version at the time of writing this tutorial.
➢ It offers the main classes for interacting with your data sources.
➢ The new features in these packages include changes in the following areas −
❖ Automatic database driver loading.
❖ Exception handling improvements.
❖ Enhanced BLOB/CLOB functionality.
❖ Connection and statement interface enhancements.
❖ National character set support.
❖ SQL ROWID access.
❖ SQL 2003 XML data type support.
❖ Annotations.
3. Explain the detail about the step to make a connection to the database.
Approach I - Class.forName()
➢ The most common approach to register a driver is to use Java's Class.forName() method,
to dynamically load the driver's class file into memory, which automatically registers it.
➢ This method is preferable because it allows you to make the driver registration
configurable and portable.
The following example uses Class.forName( ) to register the Oracle driver −
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
➢ You can use getInstance() method to work around noncompliant JVMs, but then you'll
have to code for two extra Exceptions as follows −
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
catch(IllegalAccessException ex) {
System.out.println("Error: access problem while loading!");
System.exit(2);
catch(InstantiationException ex) {
System.out.println("Error: unable to instantiate driver!");
System.exit(3);
}
Approach II - DriverManager.registerDriver()
➢ The second approach you can use to register a driver, is to use the static
DriverManager.registerDriver() method.
➢ You should use the registerDriver() method if you are using a non-JDK compliant JVM,
such as the one provided by Microsoft.
➢ The following example uses registerDriver() to register the Oracle driver −
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
Database URL Formulation
➢ After you've loaded the driver, you can establish a connection using the
DriverManager.getConnection() method.
➢ For easy reference, let me list the three overloaded DriverManager.getConnection()
methods −
❖ getConnection(String url)
❖ getConnection(String url, Properties prop)
❖ getConnection(String url, String user, String password)
➢ Here each form requires a database URL. A database URL is an address that points to
your database.
➢ Formulating a database URL is where most of the problems associated with establishing
a connection occurs.
➢ All the highlighted part in URL format is static and you need to change only the
remaining part as per your database setup.
4. Discuss in detail about object.
JDBC - Statements
➢ Once a connection is obtained we can interact with the database.
➢ The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the
methods and properties that enable you to send SQL or PL/SQL commands and receive
data from your database.
➢ They also define methods that help bridge data type differences between Java and SQL
data types used in a database.
➢ The following table provides a summary of each interface's purpose to decide on the
interface to use.
Interfaces Recommended Use
Use the for general-purpose access to your database. Useful when
Statement you are using static SQL statements at runtime. The Statement
interface cannot accept parameters.
Use the when you plan to use the SQL statements many times. The
PreparedStatement
PreparedStatement interface accepts input parameters at runtime.
Use the when you want to access the database stored procedures. The
CallableStatement
CallableStatement interface can also accept runtime input parameters.
A simple Server Program in Java The steps for creating a simple server program are:
1. Open the Server Socket:
ServerSocket server = new ServerSocket( PORT );
2. Wait for the Client Request:
Socket client = server.accept();
A simple Client Program in Java The steps for creating a simple client program are:
1. Create a Socket Object:
Socket client = new Socket(server, port_id);
2. Create I/O streams for communicating with the server.
is = new DataInputStream(client.getInputStream());
os = new DataOutputStream(client.getOutputStream());
3. Perform I/O or communication with the server:
Receive data from the server: String line = is.readLine();
Send data to the server: os.writeBytes(“Hello\n”);
4. Close the socket when done:
client.close();
void send(DatagramPacket p)
Sends a datagram packet from this socket.
void receive(DatagramPacket p)
Receives a datagram packet from this socket.
➢ A simple UDP server program that waits for client’s requests and then accepts the
message (datagram) and sends back the same message is given below. Of course, an
extended server program can manipulate client’s messages/request and send a new
message as a response.
Part B
1. What is an Applet? Explain the life cycle of an Applet with one suitable example?
➢ An applet is a Java program that runs in a web browser. An applet can be a fully
functional java application because it has the entire Java API at its disposal.
➢ There are certain differences between Applet and Java Stand alone Application that are
described below:
• An applet is a Java class that extends the java.applet.Applet class.
• A main() method is not invoked on an applet, and an applet class will not define
main().
• Applets are designed to be embedded within an HTML page.
• When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
• A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
•The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
• Applets have strict security rules that are enforced by the Web browser. The security
of an applet is often referred to as sandbox security, comparing the applet to a child
playing in a sandbox with various rules that must be followed.
• Other classes that the applet needs can be downloaded in a single Java Archive (JAR)
file.
Life Cycle of an Applet:
Init() start()
Applet Initialized Applet Running
stop()
Code of MyFirstApplet.java
import java.applet.*;
import java.awt.*;
public class HelloWorldApplet extends Applet
{
public void paint (Graphics g)
{
g.drawString ("Hello World", 25, 50);
}
}
Invoking an Applet:
➢ An applet may be invoked by embedding directives in an HTML file and viewing the file
through an applet viewer or Java-enabled browser.
➢ The <applet> tag is the basis for embedding an applet in an HTML file. Below is an example
that invokes the "Hello, World" applet:
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code="HelloWorldApplet.class" width="320" height="120">
</applet>
<hr>
</html>
Output:
Method – 1: Open the HTML file in java Enabled web browser
Method – 2: Use Appletviewer Tool
2. How will you add images to an applet and how to play audio in applet? Explain with an
example.
➢ An applet can display images of the format GIF, JPEG,
BMP and others.
➢ To display an image within the applet, you use the
drawImage() method found in the java.awt.Graphics class.
4. Explain the architecture of Servlet in detail with a sample Servlet program. (APR/MAY
2011)
Servlet Architecture overview:
• The combination of HTML JavaScript and DOM is sometimes referred to as Dynamic
HTML (DHTML)
• Web pages that include scripting are often called dynamic pages
• A simple HTML document without scripting known as static document
Web server response can be static or dynamic
• Static: When browser has requested an HTML document
• HTML document is retrieved from the file system and returned to the client
• Web server not responsible for generating content of response
• Find and send the content
• Dynamic: HTML document is generated by a program in response to an HTTP request
Eg: Visiting a search engine website
• Java servlets are one technology for producing dynamic server responses
• Servlet is a Java class instantiated by the server to produce a dynamic response
• A particular method is called on this instance when server receives HTTP request
• Code in the servlet method can obtain information about the request and produce
information to be included in the response
• It is done by calling methods on parameter objects passed to the method
• When the servlet returns control to the server , it creates a response from the information
dynamically generated by servlet
Web Server-Servlet Interaction
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String u=request.getParameter("user");
String p=request.getParameter("pass");
System.out.println("USER IS"+u);
System.out.println("PASS IS"+p);
if(u.equals("User1")&&p.equals("pass"))
{
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>WELCOME :" + u + "</h1>");
/*out.println("<h1>PASSWORD IS " + p + "</h1>");*/
out.println("</body>");
out.println("</html>");
}
else
{
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>" + u + " is not a valid user</h1>");
out.println("</body>");
out.println("</html>");
} } }
5. What is a session? Explain how client state is maintained using session and also explain
about session tracking and session management using an example. (NOV/DEC 2011)
Sessions
• A session refers to the entire interaction between a client and a server from the time of
the client’s first request, which generally begins the session, to the time the session is
terminated.
• The session could be terminated by the client’s request, or the server could automatically
close it after a certain period of time.
• Without session management, each time a client makes a request to a server, it’s a brand
new user with a brand new request from the server’s point of view.
.
Server knows that all of these requests are from the same client. The set of requests is known as
a session
INDEX.JSP:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="FirstSession" method="post">
<input type="submit" value="Welcome to Online Purchase"/>
</form>
</body>
</html>
FirstSession.java
public class FirstSession extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
HttpSession session = request.getSession();
String id=session.getId();
System.out.println(id);
String ses_name=(String) session.getAttribute("ses_attr");
System.out.println("Session_name:"+ses_name);
if(session.isNew() || ses_name == null)
{
printSignInForm(out,"Greeting",id);
/*For URL Rewriting(Cookies Turned Off)
printSignInForm(out,response.encodeURL("Greeting"),id);
*/
}
else
{
welcomeBackPage(out,ses_name,id);
}
} finally {
out.close();
}
}
public void printSignInForm(PrintWriter out, String action,String sess_id)
{
out.println("<Form method='post' action="+action+">");
out.println("Session Id:" + sess_id);
out.println("Please Sign in :");
out.println("<input type=text name=signIn>");
out.println("<br><input type=submit name=signin value=SignIn>");
}
private void welcomeBackPage(PrintWriter out,String signIn,String sess_id)
{
out.println("Session Id:" + sess_id);
out.println("Hey you're <h3>" +signIn+ " </h3>Welcome back!!!");
}
}
Greeting.java
public class Greeting extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String user = request.getParameter("signIn");
HttpSession session = request.getSession();
String id=session.getId();
if(user != null)
{
printThanks(out,user,id);
session.setAttribute("ses_attr",user);
}
}
finally
{
out.close();
}
}
private void printThanks(PrintWriter out,String signIn,String sess_id)
{
out.println("Session Id:" + sess_id);
out.println("Thanks for signing in, <h3> "+signIn+ " </h3>");
out.println("<br> Please <a href=FirstSession>visit again !</a>");
/*For URL Rewriting(Cookies Turned Off)
out.println("<br> Please <a href=" +
response.encodeURL("FirstSession") +">visit again !</a>");
*/
}
}
HttpSession interface:
METHODS
Method Description
public HttpSession getSession() Will cause one session to be created.
public HttpSession getSession(boolean) true = will cause one to be created;
false = will return null (no session)
public Object getAttribute(String name) Returns the object bound with the specified name
in this session, or null if no object is bound under
the name.
public void setAttribute(String name, Object Binds an object to this session, using the name
value) specified.
public void removeAttribute(String name) Removes the object bound with the specified
name from this session.
Session termination:
• By default, each session expires if a server-determined length of time elapses between a
session’s HTTP requests
– Server destroys the corresponding session object
• Servlet code can:
– Terminate a session by calling invalidate() method on session object
– Set the expiration time-out duration (secs) by calling setMaxInactiveInterval(int)
➢ Servlets run on the web server platform as part of the same process as the web server itself.
➢ The web server is responsible for initializing, invoking, and destroying each servlet instance.
➢ A web server communicates with a servlet through a simple interface, javax.servlet.Servlet.
➢ This interface consists of three main methods:
✓ init()
✓ service()
✓ destroy()
Servlet API life cycle methods:
Servlet API life cycle methods
– init(): called when servlet is instantiated; must return before any other methods
will be called
– service(): method called directly by server when an HTTP request is received;
default service() method calls doGet() (or related methods covered later)
– destroy(): called when server shuts down
XML Usage:
A short list of XML usage says it all:
➢ XML can work behind the scene to simplify the creation of HTML documents for large web
sites.
➢ XML can be used to exchange the information between organizations and systems.
➢ XML can be used for offloading and reloading of databases.
➢ XML can be used to store and arrange the data, which can customize your data handling needs.
➢ XML can easily be merged with style sheets to create almost any desired output.
➢ Virtually, any type of data can be expressed as an XML document.
XML Declaration:
The XML document can optionally have an XML declaration. It is written as below:
<?xml version="1.0" encoding="UTF-8"?>
Where version is the XML version and encoding specifies the character encoding used in the document.
Syntax Rules for XML declaration
▪ The XML declaration is case sensitive and must begin with "<?xml>" where "xml" is written in
lower-case.
▪ If document contains XML declaration, then it strictly needs to be the first statement of the XML
document.
▪ The XML declaration strictly needs be the first statement in the XML document.
▪ An HTTP protocol can override the value of encoding that you put in the XML declaration.
➢ Run wscompile
▪ Wscompile –gen –keep –d classes –s src config.xml
▪ Wscompile tool creates a class implementing the interface
▪ Interface is shared between webservice server and clients via the wsdl document.
▪ On server side the class implementing the interface is written
▪ On client side the interface is automatically generated by wscompile tool
▪ Structs will be represented as JavaBeans classes, regardless of how they are defined on the
server
▪ Bean obtaining and calling proxy object:
▪ JSP document convert.jspx calls on javaBeans class to perform currency conversion and
displays result in HTML table
▪ Document is placed in ConverterClient directory
4. With a simple example illustrate the steps to create a java web service. (NOV/DEC 2012)
▪ Run jar and wsdeploy to create a Web Archive (WAR) file converter.war
• Name must match urlPatternBase value
▪ jaxrpc-ri.xml: Defines the various end points for referencing a Web service.
▪ wscompile: The wscompile tool generates stubs, and WSDL files used in JAX-RPC clients and
services. The tool reads as input a configuration file and either a WSDL file or an RMI interface
that defines the service.
▪ wsdeploy: Reads a WAR file (something like Jar file) and the jaxrpc-ri.xml file and then
generates another WAR file that is ready for deployment
▪ Write service endpoint interface
• May need to write additional classes representing data structures
▪ Write class implementing the interface
▪ Compile classes
▪ Create configuration files and run JWSDP tools to create web service
▪ Deploy web service to Tomcat
▪ Just copy converter.war to Tomcat webapps directory
• May need to use Manager app to deploy
• Enter converter.war in “WAR or Directory URL” text box
▪ Testing success:
• Visit http://localhost:8080/converter/currency