You are on page 1of 161

LIST OF EXPERIMENTS

(A) HTML & JAVA SCRIPT


1. Create a HTML page that uses the tags like head, title, body etc.
2. Create a HTML page that uses frames and different presentation formats, colors.
3. Create a HTML page with a table consisting of a header, body and footer.
4. Create a HTML page with a form containing various controls.
5. Create a style sheet to set the background color, position and dimensions of a HTML element.
6. Create a simple XML file that contains student data.
7. Write JavaScript code using arithmetic operators.
8. Write JavaScript code to implement sorting.
9. Write JavaScript code that uses recursion.
10. Write JavaScript code that displays date in various formats.
(B) JAVA
1. Write programs using Java built-in functions using all data types.
2. Write programs using conditional statements and loop statements.
3. Write a program to read data from keyboard.
4. Write a program to create class and objects.
5. Write programs using constructors.
6. Write a program to illustrate usage of command line arguments.
7. Write programs using concept of overloading methods.
8. Exercise on inheritance.
9. Write a program using the concept of method overriding.
10. Exercise on importing packages.
11. Exercise on interfaces.
12. Exercise on exception handling.
13. Exercise on multithreading and thread priorities.
14. Exercise on applets.

WEB
PROGRAMMING

Experiment 1: Create a HTML page that uses the tags like head, title, body etc.
Aim: To create a HTML web page demonstrating usage of <head>, <title>, <body>, and some more basic
tags for text markups.
Illustration:
HTML is the building block for web pages. The acronym HTML stands for Hyper Text Markup Language.
Hyper refers to the ability to link to various elements and go to them when the user decides to resource them.
Markup refers to the things we do to make things appear different; bolding text for instance. HTML codes
instruct web browsers such as Internet Explorer, Firefox, Opera and Safari how to display or present content
without displaying the code. Content may include elements such as text, images, audio, video and other
multimedia files

An HTML file is a text file containing small markup tags


The markup tags tell the Web browser how to display the page
An HTML file must have an htm or html file extension

Coding Syntax
HTML formats all the information presented in your web browser with tags. Tags are always enclosed
in the angled brackets < >. In order for them to work, they must be "spelled" correctly.
Examples: <font> <b> <br> <p>
Tags tell the browser when to start formatting information with specific effects and when to stop them.
The effects are stopped by using the same tag with a forward slash before the tag.
Examples:

<b>

This

is

the

text

we

want

to

make

bold.</b>

<center> This is the text which we want to center </center>


Some tags do not require closing versions. These tags are for items which can only occur once. Such as a
line break, an image, a sound file, etc.
Examples:<br>
<img src=picture.jpg:>
Tags often have a more complex structure which incorporates several elements.
Example: <img width =200 height=200 src=picture.jpg>
In this case, the image needed to be resized to 200x200 pixels. In general, images should be resized in a
graphics program. This will be discussed in greater detail in the images section.
Tags must also be "nested" correctly. When a tag is nested inside another it must be ended or closed
before the original tag is closed.
Example: <tag a>The quick brown fox jumps over the <tag b>lazy dog</tag b></tag a>
Although you may see examples where all coding is done in capital letters, this is not necessary. In fact,
the standard recommended by the W3C (World Wide Web Consortium) for HTML 4 is lower case.

Document Structure
Every HTML document has the following basic structure. It starts and stops with the <html> </html>
code to tell the web browser accessing it that it is indeed an HTML page.
Specific details can be embedded in the head
section which are made use of by search
engines, etc but are hidden to the viewer.
Information for display is included in the body
section.
General Layout
We understand what a paragraph is, a heading is, a blockquote, etc and where and when these should be
used. When they are not used, people find reading and viewing content difficult and are more apt to seek
out another website even if the content is excellent on the one created without proper formatting.
Without HTML codes, all text will display in the web browser in a continuous line filling in the screen
from top to bottom.
Paragraphs/Line Breaks
The paragraph code <p> </p> should appear on either side of the text you wish to appear as a
paragraph. A visual space is automatically inserted in between consecutive paragraphs.
If you desire that no visual space appear, you should use a line break <br> OR </br>. This is one of
those codes which is not required to have an opening and closing. You can use one or the other.
Paragraphs can be aligned left, centre and right. Note that you should use the American spelling
of center for this to work.
<p align="center"> </p>
<p align="right"> </p>
<p align="left"> </p>
Headings
Headings are used in html for the exact same reason they are used in print text. HTML has 6 levels of
Headings built into the code. These are used to create a consistent look for all headings.
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>

Horizontal Rules
Horizontal Rules are fairly obsolete in this day and age; however, their concept is sound when it comes
to general page layout. A horizontal rule is in effect a line to help delineate the space on the page or to
section off a document.
<hr>
Note that the horizontal rule tag is one that stands on it's own and does not require a closing tag.
You can change the alignment, width, height(size) and shading of an <hr>.
Example: <hr align="left" width="300" size="10" noshade>
Lists
In HTML there is very little you can do without tables to precisely place any information on the page.
HTML lists aid the programmer in defining steps or items on their own.
There are three types of lists available:

Ordered Lists

Unordered Lists

Definition Lists

The opening and closing tags for the entire list are <ol></ol>, <ul></ul> or <dl></dl>.
Each list item only has an opening tag which is <li>, unless using a definition list where you would use
<dt> and <dd>.
An ordered list automatically inserts numbers sequentially for each item listed.

Unordered lists follow the same type of format; however, the items in the list are in no order of
importance. Unordered lists make use of round bullets before each item listed.

Definition lists are slightly more complicated to create; however, they do have the benefit of
consistent formatting. Definition lists consist of a term and an interleaved and indented definition.

Text Effects
Text can be adjusted to accomplish many different looks. Remember, this is what the markup portion
of HTML stands for.
Simple Effects
Text can be changed in many ways similar to what you can accomplish in word processor. For example
you can change:

The font itself can be changed from the default font type.
The colour
The font size
It can be italicized
It can be bolded
It can be underlined
It can be struck through
Or a combination of these things can occur.

The code is inserted directly before and after the text you wish to change the look of. This is
extremely important to remember!
This is extremely <bold> important </bold> to remember!
You can underline text.
You can <u>underline</u> text.
You can italicize text.
You can <em>italicize</em> text.
You can change the colour of text.
You can change the <font color=#990033>colour</font> of text.
And of course you can apply a combination of all of the above.
And of course you can apply a <b><em><u>combination</u></em></b> of all of the above.

Fonts
Fonts are drawn from the computer they are displayed on. There are a limited number of fonts which
are installed on all Mac and PC machines.
To change from the default font (that is the font that the browser automatically applies when no font is
specified, use "face".
<font face="comic sans ms">This is the comic sans ms font"</font>
It is good idea to specify a secondary font optionalthough the above fonts are most likely
available on a computer, you never are 100% sure that the user did not delete them.
<font face="comic sans ms, verdana, arial"> </font>
In this case the browser know that if comic sans ms is not available on the computer, that it should
look next to the verdana font and then arial if the first two aren't there. If you do not specify a
font, text will display; however, you will have no control over what alternate font the browser uses.
Special Characters
In order to place special characters into a document, HTML requires a special code to "recreate" them.
Special characters are often referred to as "character entities". These are characters which are either
already used within HTML coding and therefore do not display (eg <\>) or they are characters which are
not included in the plain ASCII character set
There are many sources on the internet for character entities as there are many different languages
which make use of different symbols. You can research for specifics; however, the following resource
has a good selection of the most commonly used ones.
Image Effects
Resizing Images
Because we are so used to placing and resizing images in word processed documents using the image
tools and handle bars on the image this approach is often imitated in HTML. Unfortunately,
resizing an image visually does not equate to resizing it physically in HTML.
Even though you are asking the image to be displayed at a specific size, the physical image still resides in
your file structure and the entire image must be downloaded in order to view it. If you resize the image to
the actual display size using a graphics program, the image to be downloaded before the HTML code
presents it, will be much smaller.
When resizing an imagebe sure to keep the image ratio intact. Nothing looks more unprofessional
than an image which has been squashed.
Image Format
It is important that you use the correct image format when preparing images for the web. As this course is
not one on design we will stick to the following simple rule. If the image is cartoonlike or requires
transparency you should use a .gif. If the image is more photo like or has gradients of colour, you should
use a .jpeg.

Inserting Images
The terminology "inserting" an image is somewhat problematic. In reality you are telling the
webpage to display an image saved in your website at a specific location on the page. It should be thought
of as "displaying" an image instead.
Use the "img src" tag.
<img src="cow.jpg>
Depending on where it is saved in your file structure, the "path" to the image may look slightly different.
Further explanation is available in the File Management portion of this resource.
<img src="../images/animals/cow.jpg>
Note that images do NOT have a closing tag.
The Alt Tag
<img src="cow.jpg" alt="cow">
This will pop up the word cow when the mouse is hovered over the cow displayed on the web page.
Where this is useful is for those who turn images off in their browsers (there are still a lot of people using
dial up!) or for those who have vision problems and make use of text readers to interpret their webpages
for them.
The width and height tags
<img src="htmltemplate/graphics/photo2.png" width="200" height="133">

You can use these to change the size of the image being displayed on your webpage; however,
although it resizes the image VISUALLY it does not resize the physical image. Use it to visually
decide the size you will change your image to using a graphics program.

The numbers are in pixels

If you wish to resize the image according to the display size of the window, you can use percentages.
<img src="htmltemplate/graphics/photo2.png" width="30%" height="10%">

Alignment
The alignment of the image relative to the text can also be controlled using the align attribute.
<img src="cow.jpg" align="middle">
You can align "middle", "top", "bottom", "left", "right", "texttop", "absmiddle", "baseline", and
"absbottom".
What is frustrating is that only one line of text will be aligned in this way. Any text that wraps to the next
line will appear below the image. 2 solutions are available in the tables section and in the .css section.

Borders and Spacing


You can add a solid border to an image.
<img src="cow.jpg border="3">
To add space around the image use the hspace and vspace attributes.
<img src="cow.jpg" hspace="5" vspace="5">
Page Defaults
There are several attributes that you can set up for the entire page in order that you don't need to type
code over and over.
You can change the background colour of an entire page:
<body bgcolor="#000024">
OR You can tile an image filling the background.
<body background="../graphics/bgtile.gif">
The other item you can affect throughout the page is the "default" colour for text.
All text (non linked) <body text="000234">
Linked Text

<body link="239344">

Visited Links

<body vlink="234884">

Active Links

<body alink="223344">

Adding the "Hyper"


The Hyper in Hypertext basically means the ability to link from one page or element to another.
Linking Text
Page Links
<a href=http://www.edu.pe.ca> Page Link</a>
By page link this means you can link to any document viewable on the Internet or by the individual who
may have software on their computer that will read a specific file type. For example, you may link to a
.pdf, another .htm page quite easily. You may also link to a .wpd (word perfect file), a .ppt (powerpoint
file) and it will open as long as the individual has a viewer or the program installed on their computer.
The page link can be a direct or relative link (see next section).
Target Your Links
A system of specifying where you would like your window to open is somewhat obsolete. It made
more sense when it was the norm to use Frames to design a webpage.

However, the one target that is still useful is "_blank". This will open the link in a new window.
<a href=http://www.edu.pe.ca target="_blank"> Page Link</a>
Email Links
<a href=mailto:> Email Link</a>
This type of link will start up the individual's email program on their computer and address an email to
that address.
Anchors
<a name=name> Anchor</a> This is the anchor
<a href=#name> Link to Anchor</a> This is the link to the anchor.
This type of link creates spots in longer pages where the link can "jump" to.
Relative or Direct?
Creating links to other resources is a fairly simple process; however, it is beneficial to know when to use
DIRECT links vs INDIRECT links.
Direct links are links which specifically spell out a location.
For example: <a href="http://www.edu.com/wsb/westindex.htm"></a> specifically tells your computer to
look on the internet for that specific address. If you are linking to that page from outside of that site (say
for example, High Education wanted to link to the WSB website), they would use this specific link.
If, on the other hand, it was the WSB webmaster linking to this page, he or she would use relative links. It is
important to keep your code as clean and limited as possible. In the end, if you create proper relative linking,
you will be able to move your pages within your web structure without breaking any links because they are
all relative.
So the following coding should be used
Code Explanation
- no code returns you to a page located
within the same folder

Example
<a href="contacts.htm></a>

- the / returns the link to the root of the


webpage and then into the folder indicated
/

..

<a href="/materials/forms/forms.htm></a>
- continue for each folder
- means to go back one folder (for each
instance of ../) and then look for the file
located within

<a
href="../courses/cmp521/index.htm></a>
<img
src="/graphics/logo.png>
<img src="../../2008/courseindex.htm></a>

What that would look like from a page within the wsb webpage would be
<a href="index.htm"></a>

Linking Images
Images may also be used as links.
Just as with text, you will insert the linking tags on either side of the image.
<a href="http://www.edu.com/> <img src="../graphics/doeicon.gif" alt="PEI Department of
Education"></a>
There are several considerations for linking using images. If you are using an icon as part of your
navigation, ensure you include the alt text information so that individuals using a text reader don't miss
out on that info.
If you are linking to a web page not in your website, consider having that link "open in a new window"
(use the target attribute and select "_blank" -- it is important you include the underscore)
<a href="http://www.edu.com/> <img src="../graphics/doeicon.gif" alt="PEI Department of Education"
target="_blank"></a>
Image Maps
Image maps used to be used to provide a graphical interface by indicating points on the image which
would be "hot spots".
Embedding Other Media
You can include media such as audio and video within your webpage. It is important to remember that
the user needs to have the "player" for that media installed in their web browser to view or hear the
media. These are often called plug-ins.
In addition, the question remains...do you want to "force" the viewer to have to download the media OR
do you want to provide them with a choice. Not everyone has high speed internet and there are
accessibility issues to consider. However, for our purposes, we will be looking at embedding as opposed
to providing a link to the resource.
If you wish to embed media you have created, it needs to be saved within the file structure of your
webpage.
Audio
Use the embed code.
<embed src="audio/podcast32.mp3" autostart="false" loop"false" height="40" width="100">
Video
Video also uses the embed tag AND the same attributes. Ensure that you do not use the hidden attribute
as it will hide the video and control bar.
Ensure as well, that the height and width of the video is exactly the same size as the video is meant to be
displayed.

PROGRAM 1

<!-- A Program to illustrate body and pre tags -->


<html>
<head>
<title> body and pre tag </title>
</head>
<body text="red" bgcolor="yellow" background="Desert.jpg"> This is an Illustration of
body tag with its properties
<pre>
This text uses
pre tag and preserves
nextline and spaces
</pre>
This text doesnt uses
pre tag so doesnt preserves nextline and
spaces.. everything will be printed in the same
line
</body>
</html>
OUTPUT

PROGRAM 2
<!-- A Program to illustrate text Font tag -->
<html>
<title>
Font tag Example
</title>
<body>
<font face="arial" size="1" color="blue"> WELCOME </font><br>
<font size="2" color="cyan">
<font size="3" color="red">
<font size="4" color="yellow">

WELCOME
WELCOME
WELCOME

</font>
</font>
</font>

<br>
<br>
<br>

<font size="5" color="green">

WELCOME

</font>

<br>

<font size="6" color="brown">

WELCOME

</font>

<br>

<font size="7" color="pink">


<font size="20" color="gray">

WELCOME
WELCOME

</font>
</font>

<br>
<br>

</body>
</html>
OUTPUT

PROGRAM 3
<!-- A Program to illustrate comment,h1.h6, and div tag -->
<html>
<head>
<title> Illustrating comment, h1...h6 and div tags </title>
</head>
<body>
<!-- THIS IS A COMMENT LINE -->
<div style="color:#00ff00">
<h1 align="center"> This is h1 tag text with center aligned </h1>
<h2 align="left"> This is h2 tag text with left aligned </h2>
<h3 align="right">This is h3 tag text with right aligned </h3>
</div>
<h4> This is h4 tag text without alignment</h4>
<h5> This is h5 tag Text without alignment </h5>
<h6> This is h6 tag text without alignment </h6>
</body>
</html>
OUTPUT

PROGRAM 4
<!-- A Program to illustrate text formatting tags -->
<html>
<head>
<title> Text Tags </title>
</head>
<body>
<center>
<h1 align="center">To illustrate text formatting tags </h1>
<hr color="red">
<P> <marquee behavior="alternate"> This is an alternate Marquee text
</marquee>
<p> This is <i> italized </i> </p>
<p> This is <u> underlined </u> </p>
<p> This is <b> bold </b> </p>
<p> This is <em> emphasized </em> </p>
<p>This is <Strong> Strong Text </strong> </p>
<p> This is <s> striked text </s> </p>
<p> This is <code> computer code </code> </p>
<p> This is <sup> superscript </sup> code </p>
<p> This is <sub> subscript </sub> code </p>
<p> This is <big> big text
</big> </p>
<p> This is <small> small text </small> </p>
</center>
</body>
</html>

OUTPUT

PROGRAM 5
<!-- A Program to illustrate Order List tag -->
<html>
<head>
<title> Order List tag </title>
</head>
<body>
<h3 align="center" style="color:red">To illustrate ORDER list tags</h3>
<hr COLOR="RED">
<h4>Numbered list:</h4>
<ol>
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ol>
<h4>Uppercase Letters list:</h4>
<ol type="A">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ol>
<h4>Lowercase letters list:</h4>
<ol type="a">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ol>
<h4>Roman numbers list:</h4>
<ol type="I">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ol>
<h4>Lowercase Roman numbers list:</h4>
<ol type="i">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ol>
</body></html>

OUTPUT

PROGRAM 6
<!-- A Program to illustrate Unorder List tag -->
<html>
<title> Unorder List </title>
</head>
<body>
<h3 align="center"> To illustrate unorder list tags </h3>
<hr color="red">
<h4>Disc bullets list:</h4>
<ul type="disc">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ul>
<h4>Circle bullets list:</h4>
<ul type="circle">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ul>
<h4>Square bullets list:</h4>
<ul type="square">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ul>
</body>
</html>

OUTPUT

PROGRAM 7
<!-- A Program to illustrate Nested and Definition tag -->
<html>
<head>
<title> Nested and Definition List <title>
</head>
<body>
<h3 align="center"> To illustrate Nested and Definition List Tags </h3>
<hr color="red">
<h4> An ordered nested List: </h4>
<ol>
<li> Coffee </li>
<li> Tea
<ol type= "a">
<li> Black tea </li>
<li> Green tea </li>
<ol type= "i" >
<li> China </li>
<li> Africa </li>
</ol>
</ol>
<li> Milk </li>
</ol>
<h4> A Definition List: </h4>
<dl>
<dt> Bangalore </dt>
<dd>
-Capital City of Karnataka
</dd>
<dt> Mumbai</dt>
<dd>
-Capital city of Maharashtra
</dd>
</dl>
</body>
</html>
OUTPUT

PROGRAM 8
<!-- A Program to illustrate Img tag -->
<html>
<head>
<title> Image Tag </title>
</head>
<body>
<h3 align="center" style="color:red"> To illustrate image tags</h3> <hr>
<p>
<img src="flower.bmp" align="right" height="100" width="100"/> This image is
right aligned with the text
</p> <br><br><br><br><hr>
<p>
<img src="flower.bmp"
align="left" height="100" width="100"/> This
image is left aligned with the text
</p> <br><br><br><br><hr>
This image is center aligned with the text.
<img src="flower.bmp"
align="middle" height="100" width="100"/>
<br><br><br><br><hr>
This image is bottom aligned with the text.
<img src="flower.bmp" align="bottom" height="100" width="100"/>
<br><br><br><br><hr>
This image is top aligned with the text.
<img src="flower.bmp" align="top" height="100" width="100"/>
</body>
</html>
OUTPUT

PROGRAM 9
<!-- A Program to illustrate Hyper Link tag (Anchor tag) -->
<html>
<head>
<title> Link Tag </title>
</head>
<title>
<body>
Home.html
<h3 align="center" style="color:red">To illustrate link Tags</h3> <hr>
Text as a link/hyperlink to another page : <a href="page1.html "> Click here!!!</a>
<hr>
Image as a link/hyperlink :<a href="page1.html">
<img src="flower.bmp" width="32" height="32" align="bottom"/></a>
<hr>
<p>
<a href="#C8">See also Chapter 8 ( link within a page )</a>
</p>
<h2>Chapter 1</h2>
<p>This chapter explains Pointers</p>
<h2>Chapter 2</h2>
<p>This chapter explains variables</p>
<h2>Chapter 3</h2>
<p>This chapter explains operator</p>
<h2>Chapter 4</a></h2>
<p>This chapter explains structure</p>
<h2>Chapter 5</h2>
<p>This chapter explains arrays</p>
<h2>Chapter 6</h2>
<p>This chapter explains linked list</p>
<h2>Chapter 7</h2>
<p>This chapter explains expressions</p>
<h2><a name="C8">Chapter 8</h2>
<p>This chapter explains Binary Trees</p>
<h2>Chapter 9</h2>
<p>This chapter explains Unordered trees</p>
<h2>Chapter 10</h2>
<p>This chapter explains Statements</p>
<h2>Chapter 11</h2>
<p>This chapter explains searching</p>
<h2>Chapter 12</h2>
<p>This chapter explains sorting</p>
<h2>Chapter 13</h2>
<p>This chapter explains Binary sort</p>
<h2>Chapter 14</h2>
<p>This chapter explains merge sort</p>
<h2>Chapter 15</h2>

<p>This chapter explains heap sort</p>


</body>
</html>
OUTPUT

After Clicking On Click Me or the Flower image the output is

After Clicking on the See also Chapter 8(link within a page) the output is

Experiment 2: Create a HTML page that uses frames and different presentation formats, colors.
Aim: To create a HTML web page demonstrating splitting a webpage layout into multiple
sections called as frames and usage of presentation and color formats.
Illustration:
With frames, you can display more than one Web page in the same browser window. Each
HTML document is called a frame, and each frame is independent of the others. The
disadvantages of using frames are:
The web developer must keep track of more HTML documents
It is difficult to print the entire page
The Frameset Tag
The <frameset> tag defines how to divide the window into frames
Each frameset defines a set of rows or columns
The values of the rows/columns indicate the amount of screen area each row/column
will occupy
The Frame Tag
The <frame> tag defines what HTML document to put into each frame
In the example below we have a frameset with two columns. The first column is set to 25% of
the width of the browser window. The second column is set to 75% of the width of the browser
window. The HTML document "frame_a.htm" is put into the first column, and the HTML
document "frame_b.htm" is put into the second column:
<frameset cols="25%,75%">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
</frameset>
Basic Notes - Useful Tips
If a frame has visible borders, the user can resize it by dragging the border. To prevent a user
from doing this, you can add noresize="noresize" to the <frame> tag. Add the <noframes> tag
for browsers that do not support frames.
Frame Tags
Tag

Description

<frameset>

Defines a set of frames

<frame>

Defines a sub window (a frame)

<noframes>

Defines a noframe section for browsers that do not handle frames

<iframe>

Defines an inline sub window (frame)

1
0

PROGRAM 10
<!-- A Program to illustrate Frame tag -->
mainframe.html
<html>
<head>
<title> Frame tag </title>
</head>
<head>
<frameset cols="20,60">
<frame src="f1.html">
<frame src="f2.html" name="main">
</frameset>
</frameset>
</head>
</html>
f1.html
f2.html
<html>
<html>
<head>
<head>
<title>f1.html</title>
<title> f2.html </title>
</head>
</head>
<body>
<body>
<h3> States of Telangana </h3>
<h1> Click on any state to get a Welcome
<a href=hyderabad.html target=main>
message </h1>
Hyderabad<br></a>
</body></html>
<a href=secunderabad.html
target=main>Secunderabad<br></a>
</body></html>
hyderabad.html
<html>
<head>
<title> Hyderabad.html </title>
</head>
<body bgcolor=green>
<h1> Welcome to Hyderabad </h1>
</body>
</html>
secunderabad.html
<html>
<head>
<title> Secunderabad.html </title>
</head>
<body bgcolor=red>
<h1> Welcome to Secunderabad </h1>
</body>
</html>

1
0

OUTPUT

1
0

Experiment 3: Create a HTML page with a table consisting of a header, body and footer.
Aim: To create a HTML web page demonstrating creating rows and columns based table and
work around its attribute usage.
Illustration:
Tables are defined with the <table> tag. A table is divided into rows (with the <tr> tag), and
each row is divided into data cells (with the <td> tag). The letters td stands for "table data,
which is the content of a data cell. A data cell can contain text, images, lists, paragraphs, forms,
horizontal rules, tables, etc.

How it looks in a browser:


row 1, cell 1

row 1, cell 2

row 2, cell 1

row 2, cell 2

Tables and the Border Attribute


If you do not specify a border attribute the table will be displayed without any borders.
Sometimes this can be useful, but most of the time, you want the borders to show.
To display a table with borders, you will have to use the border attribute:
<table border="1">
<tr>
<td>Row 1, cell 1</td>
<td>Row 1, cell 2</td>
</tr>
</table>

1
0

Headings in a Table
Headings in a table are defined with the <th> tag.

How it looks in a browser:


Heading

Another Heading

row 1, cell 1

row 1, cell 2

row 2, cell 1

row 2, cell 2

Empty Cells in a Table


Table cells with no content are not displayed very well in most browsers.

How it looks in a browser:


row 1, cell 1

row 1, cell 2

row 2, cell 1
Note that the borders around the empty table cell are missing. To avoid this, add a non-breaking
space (&nbsp;) to empty data cells, to make the borders visible:

1
0

How it looks in a browser:


row 1, cell 1

row 1, cell 2

row 2, cell 1
Table Tags
Tag
<table>
<th>
<tr>
<td>
<caption>
<colgroup>
<col>
<thead>
<tbody>
<tfoot>

Description
Defines a table
Defines a table header
Defines a table row
Defines a table cell
Defines a table caption
Defines groups of table columns
Defines the attribute values for one or more columns in a table
Defines a table head
Defines a table body
Defines a table footer

1
0

Experiment 4: Create a HTML page with a form containing various controls.


Aim: To create a HTML web page demonstrating forms and work around its various control tags
and their attribute usage.
Illustration:
A form is an area that can contain form elements.
Form elements are elements that allow the user to enter information (like text fields, textarea
fields, drop-down menus, radio buttons, checkboxes, etc.) in a form.
A form is defined with the <form> tag.

Input
The most used form tag is the <input> tag. The type of input is specified with the type attribute.
The most commonly used input types are explained below.
Text Fields
Text fields are used when you want the user to type letters, numbers, etc. in a form.
<form>
First name:
<input type="text" name="firstname">
<br>
Last name:
<input type="text" name="lastname">
</form>
How it looks in a browser:
First name:
Last name:
Note that the form itself is not visible. Also note that in most browsers, the width of the text field
is 20 characters by default.
Radio Buttons
Radio Buttons are used when you want the user to select one of a limited number of choices.

1
0

<form>
<input type="radio" name="sex" value="male"> Male
<br>
<input type="radio" name="sex" value="female"> Female
</form>
How it looks in a browser:
Male
Female
Note that only one option can be chosen.
Checkboxes
Checkboxes are used when you want the user to select one or more options of a limited number
of choices.

How it looks in a browser:


I have a bike
I have a car
The Form's Action Attribute and the Submit Button
When the user clicks on the "Submit" button, the content of the form is sent to another file. The
form's action attribute defines the name of the file to send the content to. The file defined in the
action attribute usually does something with the received input.
<form name="input" action="html_form_action.asp"
method="get">
Username:
<input type="text" name="user">
<input type="submit" value="Submit">
</form>
How it looks in a browser:
Username:

Submit

1
0

If you type some characters in the text field above, and click the "Submit" button, you will send
your input to a page called "html_form_action.asp". That page will show you the received input.
Form Tags
Tag

Description

<form>

Defines a form for user input

<input>

Defines an input field

<textarea>

Defines a text-area (a multi-line text input control)

<label>

Defines a label to a control

<fieldset>

Defines a fieldset

<legend>

Defines a caption for a fieldset

<select>

Defines a selectable list (a drop-down box)

<optgroup>

Defines an option group

<option>

Defines an option in the drop-down box

<button>

Defines a push button

<isindex>

Deprecated. Use <input> instead

1
0

PROGRAM 11
<!-- A Program to illustrate Form tag -->
<html>
<head>
<title> form tag </title>
</head>
<body>
<center>
<h3 align="center">To illustrate form based tags</h3> <hr color="red">
<form action="">
<p>This is a text box to enter any text.<input type="text" >
<p>This is a text box to enter password.<input type="password" >
<p>This is a text area to enter large text<textarea> </textarea>
<p>This is a button.<input type="button" Value="Click" >
<p><b><u>Radio Options</u></b><br>
<input type="radio" name="y" checked> yes
<input type="radio" name="n" checked> no </p>
<p><b><u>Checkbox Options</u></b><br>
Sunday<input type="checkbox" checked >
Monday<input type="checkbox" >
Tuesday<input type="checkbox" >
</p>
<p><b><u>Menu driven options </u></b>
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select></p>
</form>
</center>
</body>
</html>

1
0

OUTPUT

1
0

Experiment 5: Create a style sheet to set the background color, position and dimensions of a
HTML element.
Aim: To create a HTML web page demonstrating usage of Cascading Style Sheets to markup
text and background of a HTML document and modify the position and dimensions of text.
Illustration:
CSS is an acronym which stands for Cascading Style Sheets. A style may be applied to an
existing HTML tag or can be used to create the equivalent of one. This is called a style.
Why use CSS?

an alternative to programs which use templates


give a consistent look and feel to page elements
more control over layout
should decrease page load time
one file will change the look of your entire website
Applying CSS
There are three ways in which to apply css code to an HTML doc:
1. Inline
2. Internal
3. External

Inline
The style is used with a single instance of an HTML tag. In reality, it would make much more
sense to use HTML to change only one specific tag.
<html>
<head>
<title>Inline Style Page Example</title>
</head>
<body style="background-color:#99FFCC;">
<p>This is an example where the background colour of this particular webpage would
be light blue</p>
</body>
</html>

1
0

Internal
Styles are defined in the head section of an HTML document. These styles only affect the
instances included in the particular page. It is more common for people to use External style
sheets.
<html>
<head>
<title>Internal Style Page Example</title>
<style type="text/css">
body{background-color:#99FFCC;}
</style>
</head>
<body>
<p>This is an example where the background colour of this particular webpage would
be light blue</p>
</body>
</html>

External
Styles are defined in a separate document called a "style sheet". This sheet may be referenced
from many HTML documents. As such, each time the styles are changed within the sheet the
"look" is reflected in HTML pages referencing the sheet.
<html>
<head>
<title>External Style Page Example</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<p>This is an example where the background colour of this particular webpage would
be light blue</p>
</body>
</html>

Cascading
Different style sheets will overwrite (cascade) similar styles:

inline overwrites internal

internal overwrites external

external overwrites browser default

1
0

Coding Syntax

Examples:
p {text-align:center; color=green;}
- more than one delcaration may be referred to in a selector
- each declaration must be seaprated by a semi-colon (;) h1, h2, h3 {color:red;}
- you can apply the same property and value to vaious selectors as in the example above
Selectors
There are three types of selectors:
tag selectors
ID selectors
Class selectors
Tag Selectors
Tag selectors are those which change already in existence HTML tags.
p{
background-color: red;
}
Class Selectors
Class selectors are essentially a way in which to style an element which you name. For example,
you might wish to create a type of text box for news stories on a webpage to be reused many
times, or a way in which to wrap text around an image. The point is that a class selector can be
used many times.
#leftcontainer{
background:url(images/template/shadow_left.gif) repeat-y right top; width:419px;
float:left; color:#585858;
font:11px Tahoma, serif; height: 466px;
overflow: auto;
}
1
0

ID Selectors
An ID selector is exactly like a class selector except that it can only be used ONCE in a page.
Using Selectors
To use selectors which are different from the HTML Tags, you will need to add these in in a
similar way to HTML tags. To do this you use SPAN and the term class or id depending on what
kind of selector it is.
<span class="header">Elementary School</span>
<span id="specialparagraph">Upcoming Dates:</span>
If your selector is already an HTML tag, you would simply use it as you already have.
<p>Ipsum Lorem</p>
Properties
There are many different properties and values that can be applied to selectors.
Text
There are many ways in which to change the value of properties that relate to text.

1
0

Background
In the HTML section, backgrounds were applied to two items...the entire page or to a cell in a
table. The Background of any css selector can be changed in css.

1
0

Block

1
0

Box
Box properties are extremely useful in css. This area is what allows you to specifically decide
how to parcel each item on the page. Later on, when we look at combining this with positioning
you will see how placing boxes precisely on a page will allow you to accomplish not only what
you were able to in HTML with tables, but you can go further with this in that you can layer
boxes amongst other things.

1
0

Border

List

1
0

Positioning
The position property defines where an element will be placed on a page, either in relation to the
upper left hand corner of the screen or through it's placement within the code.

1
0

1
0

PROGRAM 12
<!-- A Program to illustrate span tag -->
<html>
<head>
<title> span tag </title>
<style type="text/css">
span.blue{ color:lightskyblue; font-weight:bold;} span.green{
color:darkolivegreen; font-weight:bold;}
</style>
</head>
<body>
<p align="center">
<font size=10>
my mother has <span class="blue"> light blue </span> eyes and my
father has <span class="green"> dark green </span> eyes.
</font>
</p>
</body>
</html>
OUTPUT

1
0

PROGRAM 13
<!-- A Program to illustrate CSS (cascading style sheet) -->
<html>
<head>
<title> css demo </title>
<style type="text/css">
body { background-color:red;}
h1 { color:orange; text-align:center;}
p { font-family: "Times new roman ";

font-size: 20px;}

</style>
</head>
<body>
<h1> CSS EXAMPLE </h1>
<p> This is a paragraph </p>
</body>
</html>
OUTPUT

1
0

PROGRAM 14
<!-- A Program to illustrate Embedded Multimedia -->
<html>
<head>
<title> embedding multimedia </title>
</head>
<body>
<center>
<h1> Here is a video embedded on this webpage </h1>
<br>
<object data="Wildlife.wmv" type="video/msvideo" height=200 width=200
hspace=200 vspace=200>
</object>
</center>
</body>
</html>
OUTPUT

1
0

Experiment 6: Create a simple XML file that contains student data.


Aim: To demonstrate usage of XML to define a structured documentation representing student
details.
Illustration:
A markup language is a mechanism to identify structures in a document. XML (Extensible
Markup language) is a markup language for documents containing structured information. As a
meta-language, XML is about to describe data and its structure; while HTML is about to display
the data.
XML is not to replace HTML, but compliment it by allowing writers to create and format their
own document markups. For HTML, The tags used to mark up HTML documents and the
structure of HTML documents are predefined. For XML, there is no predefined tag set, so there
is no any preconceived semantics. Writers are provided a facility to define tags and the structural
relationships. That is the extensible feature of XML.
To be valid, XML documents should be well-formed. That means XML documents follow some
strict rules.
For example, every opening tag in XML documents must have a matching closing tag. While in
HTML, pairing is optional for some of the tags, and only the opening tag is required.
1. Closing Tags
An element in XML must have a closing tag.
<firstname>James</firstname>
2. Overlapping Elements
An element must be nested properly by closing all child elements before closing the parent
elements.
<student>
<firstname>James</firstname>
<lastname>Smith</lastname>
</student>
It would be incorrectly nested if the student element was closed before forename element.
3. Single Root Element
An XML document only can have a single root element. All other elements should be within this
root element.

1
0

<mec>
<student>
<firstname>James</firstname>
<lastname>Smith</lastname>
</student>
</mec>
As above, mec is the root element, and student is its descendant.
4. Case Sensitive
XML is case sensitive, and care should be taken to ensure that Opening and closing tags are in
the same case. An element name of "MEC" is not the same as "mec".
5. Quoted Attribute Values
In XML, attributes must be specified a value, and the values must be in quotes, regardless of the
data type. Single and double quotes are both acceptable.
Correct: <input type="checkbox" checked="checked"/>
Wrong: <input type="checkbox" checked>
6. Naming Conventions
In XML, since there is no any pre-defined tag, there are no reserved words needed to be avoided
when naming elements. The following are some simple rules when naming an element.
a. Elements must start with a character or an underscore but not a number or
punctuation. After the first character, numbers, hyphens and periods are allowed.
b. Names must not contain spaces.
c. A colon is reserved for namespaces

1
0

PROGRAM 15

1. Create a XML file


Use XML to create a student record database for the
student information management.
So the structure of the student record can be presented as:
<?xml version = "1.0"?>
<!--student1.xml-->
<students>
<student>
<name>
<firstname> James </firstname>
<lastname> Smith </lastname>
</name>
<address>
<street> 101 South Street</street>
<city> Halifax </city>
<email> james@dal.ca </email>
<phone> 4940001 </phone>
</address>
</student>
<student>
<name>
<firstname> Tom </firstname>
<lastname> White </lastname>
</name>
<address>
<street> 202 Victoria Road </street>
<city> Dartmouth </city>
<email> tom@dal.ca</email>
<phone> 4940002 </phone>
</address>
</student>
</students>

Save the above code as Student.xml, and open the file through a browser.

1
0

2. Create a DTD file for the XML file


A DTD (Document Type Definition) is a set of rules that defines what tags appear in a XML
document, how and where these tags appear, what the relationship the tags have with each other.
Be brief, a DTD defines the legal elements and their structure in an XML document.
When an XML document is processed, it is compared within the DTD to be sure the structure is
valid and all tags are used in the proper manner. Independent developers can agree to use a
common DTD for exchanging XML data, which makes data be shared easily.
We create the students.dtd file as below:
<?xml version = "1.0"?>
<!--students.dtd-a document type definition for the students.xml-->
<!ELEMENT students (student+)>
<!ELEMENT student (name,address)>
<!ELEMENT name (firstname,lastname)>
<!ELEMENT firstname (#PCDATA)>
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT address (street,city,email,phone)>
<!ELEMENT street (#PCDATA)>
<!ELEMENT city (#PCDATA)>
<!ELEMENT email (#PCDATA)>
<!ELEMENT lastname (#PCDATA)>
To use the DTD file, we must add this code into the XML file.
<!DOCTYPE students SYSTEM "students.dtd">

1
0

So the changed Student2.xml will be as follows:


<?xml version = "1.0"?>
<!-- students2.xml for the DTD -->
<!DOCTYPE students SYSTEM "students.dtd">
<students>
<student>
<name>
<firstname> James </firstname>
<lastname> Smith </lastname>
</name>
<address>
<street> 101 South Street</street>
<city> Halifax </city>
<email> james@dal.ca </email>
<phone> 4940001 </phone>
</address>
</student>
<student>
<name>
<firstname> Tom </firstname>
<lastname> White </lastname>
</name>
<address>
<street> 202 Victoria Road </street>
<city> Dartmouth </city>
<email> tom@dal.ca</email>
<phone> 4940002 </phone>
</address>
</student>
</students>

1
0

3. Display the XML file in HTML by CSS and XSLT


Display the XML file in HTML by CSS and XSLT
Browsers are not particularly good at formatting XML. It is true that most of the time XML will
be used to define data instead of displaying it. But for viewing, we have to format the XML
data. CSS and XSL could be used to do this.
CSS
CSS (Cascading Style Sheets) is a markup language with the purpose of styling online
content. It is used extensively for formatting standard HTML pages and also used to
format XML documents. CSS can define how XML tags are displayed, allowing them
to be presented in different ways.
<!--students.css- a style sheet for the students.xml document-->
student{display: block; margin-top: 15px; color: blue;}
name{display: block; margin-left:40px;margin-top: 30pt;color:red}
firstname{font-size: 28pt;}
lastname{font-size: 28pt;}
address{display: block; margin-left:40px;color:green}
street{display: block;font-size: 18pt;}
city{display: block;font-size: 18pt;}
email{display: block;font-size: 18pt;color:blue}
phone{display: block;font-size: 18pt;}
To use the CSS file, the XML must add the following sentence:
<?xml-stylesheet type="text/css" href= "students.css"?>

1
0

So the complete Student3.xml will be:


<?xml version = "1.0"?>
<!-- students3.xml for the CSS -->
<?xml-stylesheet type="text/css" href= "students.css"?>
<students>
<student>
<name>
<firstname> James </firstname>
<lastname> Smith </lastname>
</name>
<address>
<street> 101 South
Street</street>
<city> Halifax </city>
<email> james@dal.ca </email>
<phone> 4940001 </phone>
</address>
</student>
<student>
<name>
<firstname> Tom </firstname>
<lastname> White </lastname>
</name>
<address>
<street> 202 Victoria Road
</street>
<city> Dartmouth </city>
<email> tom@dal.ca</email>
<phone> 4940002 </phone>
</address>
</student>
</students>

1
0

XSLT
XSL (eXstensible Stylesheet Language) is XSL (eXstensible Stylesheet
Language) is a new language developed to format XML documents. With
the appearance of XML, in many cases the original data, not the HTML
representation of it, will be exchanged. This gives the users a richer
data-set to work with and data transformations are necessary. To
perform these transformations, XSL could be used. XSLT is used to
format a XML file into a HTML document. It maps the XML elements to
XSL templates. So XSLT provides a powerful presentation for XML.
<?xml version ="1.0"?>
<!--students.xsl-->
<xsl:stylesheet version = "1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/TR/xhtml1/strict">
<xsl:template match = "/">
<h2> Student Record </h2>
<xsl:for-each select="students/student">
<br/>
<span style="font-weight:bold;color:red"> FirstName: </span>
<xsl:value-of select="name/firstname" />
<span style="font-weight:bold;color:red"> LastName: </span>
<xsl:value-of select="name/lastname" /> <br/>
<span style="font-weight:bold;color:green"> Street: </span>
<xsl:value-of select="address/street" /> <br/>
<span style="font-weight:bold;color:green"> City: </span>
<xsl:value-of select="address/city" /> <br/>
<span style="font-weight:bold;color:blue"> Email: </span>
<xsl:value-of select="address/email" /> <br/>
<span style="font-weight:bold;color:green"> Phone: </span>
<xsl:value-of select="address/phone" /> <br/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
To use the XSLT file, we must add the following sentence into XML file.
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?>

1
0

The complete file students4.xml is :


<?xml version = "1.0"?>
<!--student4.xml for XSLT-->
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?>
<students>
<student>
<name>
<firstname> James </firstname>
<lastname> Smith </lastname>
</name>
<address>
<street> 101 South Street</street>
<city> Halifax </city>
<email> james@dal.ca </email>
<phone> 4940001 </phone>
</address>
</student>
<student>
<name>
<firstname> Tom </firstname>
<lastname> White </lastname>
</name>
<address>
<street> 202 Victoria Road </street>
<city> Dartmouth </city>
<email> tom@dal.ca</email>
<phone> 4940002 </phone>
</address>
</student>
</students>

1
0

PROGRAM 16
<html>
<head>
<title>Arithmetic operations</title>
</head>
<script type="text/javascript">
function Addition()
{
x=parseFloat(calc.value1.value);
y=parseFloat(calc.value2.value);
z=(x+y);
alert("The Addition result is"+z);
calc.value3.value=z
}
function Subtraction()
{
var x,y,z;
x=calc.value1.value;
y=calc.value2.value;
z=x-y;
alert("The subtraction result is "+z);
calc.value3.value=z
}
function Multiplication()
{
var x,y,z;
x=calc.value1.value;
y=calc.value2.value;
z=x*y;
alert("The Multiplication result is "+z);
calc.value3.value=z
}
function Division()
{
var x,y,z;
x=calc.value1.value;
y=calc.value2.value;
z=x/y;
alert("The subtraction result is "+z);
calc.value3.value=z
}

1
0

</script>
</head>
<body>
<form name="calc">
<h1>Online Calculator</h1>
Enter first Numeric Value : <input type="number" id="value1"> </br>
Enter Second Numeric Value : <input type="number" id="value2"> </br>
</br>
Result of the Arithmetic operation is : <output type="number" id="value3">
</output></br>
<input type="button" Value="Addition" onClick=Addition()> </br>
<input type="button" Value="Subtraction" onClick=Subtraction()></br>
<input type="button" Value="Multiplication" onClick=Multiplication()></br>
<input type="button" Value="Division" onClick=Division()></br>
</form>
</body>
</html>

1
0

PROGRAM 17
<!DOCTYPE html>
<html>
<body>

<p>Click the button to sort the array in descending order.</p>


<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;

function myFunction() {
points.sort(function(a, b){return b-a});
document.getElementById("demo").innerHTML = points;
}
</script>

</body>
</html>

1
0

PROGRAM 18
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Calculate the factorial of a number.</title>
<script type="text/javascript">
function factorial(x)
{
if (x === 0)
{
return 1;
}
return x * factorial(x-1);
}
console.log(factorial(5)); // Writes it to the
browsers console.
document.write (factorial(5)); //Writes it to the HTML document
// displayed in browser.
</script>
</head>
<body>
</body>
</html>

1
0

PROGRAM 19
<!DOCTYPE html>
<html>
<head>
<title>Write a JavaScript program to get the current date.
</title>
<script type="text/javascript">
var today = new Date();
var dd = today.getDate();
//The value returned by getMonth is an integer
between 0 and 11, referring 0 to //January, 1 to
February, and so on.
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
if(dd<10)
{
dd='0'+dd;
}
if(mm<10)
{
mm='0'+mm;
}
today = mm+'-'+dd+'-'+yyyy;
console.log(today);
document.write (today+<br>);
today = mm+'/'+dd+'/'+yyyy;
console.log(today);
document.write (today+<br>);
today = dd+'-'+mm+'-'+yyyy;
console.log(today);
document.write (today+<br>);
today = dd+'/'+mm+'/'+yyyy;
console.log(today);
document.write (today +<br>);
</script>
</head>
<body>

</body>

</html>

1
0

JAVA
PROGRAMMING

1
0

Experiment 1: Write programs using Java built-in functions using all data types.
Aim: To demonstrate usage of Java built-in functions for various data types supported by Java.
Illustration:
A data type is a set of values and a set of operations defined on them. For example, we are
familiar with numbers and with operations defined on them such as addition and multiplication.
There are eight different built-in types of data in Java, mostly different kinds of numbers.

int
a =
b =
c =

a, b, c;
1234;
99;
a + b;

String a, b, c;
a = "Hello,";
b = " Bob";
c = a + b;

Library methods and APIs.


Many programming tasks involve using Java library methods in addition to the built-in
operators. An application programming interface is a table summarizing the methods in a
library.

Printing strings to the terminal window.

Converting strings to primitive types.

1
0

Mathematical functions.

You can call a method by typing its name followed by arguments, enclosed in parentheses and separated
by commas. Here are some examples:

We often find ourselves converting data from one type to another using one of the following
approaches.
Type conversion.
We often find ourselves converting data from one type to another using one of the
following approaches.

Explicit type conversion. Call methods such as Math.round(), Integer.parseInt(),


andDouble.parseDouble().

Automatic type conversion. For primitive numeric types, the system automatically
performs type conversion when we use a value whose type has a larger range of values
than expected.

1
0

Explicit casts. Java also has some built-in type conversion methods for primitive types
that you can use when you are aware that you might lose information, but you have to
make your intention using something called a cast.

Automatic conversions for strings. The built-in type String obeys special rules. One of
these special rules is that you can easily convert any type of data to a String by using
the + operator.

1
0

Program 20
A. Byte
1.
2.
3.
4.
5.

Byte data type is a 8 -bit signed two's complement integer


Minimum value is : -128 ( -2^7)
Maximum value is : 127 (inclusive)(2^7 -1)
Default value is : 0
Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four
times smaller than an int

Syntax :
byte Variable_Name = Value;
Example (DataType_Byte.java) :
public class DataType_Byte {
byte a = 50;
byte b = (byte) -80;

void add() {

byte c = (byte) (a + b);

System.out.println("The Byte Value is : " + c);


}
}

class MainClass {

public static void main(String args[]) {

DataType_Byte obj = new DataType_Byte();

obj.add();
}
}
Sample Output

The Byte Value is : -30

1
0

B. Short
1.
2.
3.
4.
5.

Short data type is a 16 -bit signed two's complement integer


Minimum value is : -32,768 (-2^15)
Maximum value is : 32,767(inclusive) (2^15 -1)
Default value is : 0
Short data type can also be used to save memory as byte data type. A short is 2 times smaller than
an int

Syntax :
short Variable_Name = Value;
Example (DataType_Short.java) :
public class DataType_Short {

short a = 1000;
short b = -1500;

void add() {

short c = (short) (a + b);

System.out.println("The Short Value is : " + c);


}
}

class MainClass {

public static void main(String args[]) {

DataType_Short obj = new DataType_Short();

obj.add();
}
}
Sample Output

The Short Value is : -500

1
0

C. Int
1.
2.
3.
4.
5.

Int data type is a 32 -bit signed two's complement integer


Minimum value is : -2,147,483,648.( -2^31)
Maximum value is : 2,147,483,647(inclusive).(2^31 -1)
Default value is : 0
Int is generally used as the default data type for i ntegral values unless there is a concern about
memory

Syntax :
int Variable_Name = Value;
Example (DataType_Int.java) :
public class DataType_Int {

int a = 15000;
int b = -20000;

void add() {

int c = a + b;

System.out.println("The int Value is : " + c);


}
}

class MainClass {

public static void main(String args[]) {

DataType_Int obj = new DataType_Int();

obj.add();
}
}
Sample Output

The int Value is : -5000

1
0

D. Long
1.
2.
3.
4.
5.

Long data type is a 64 -bit signed two's complement integer


Minimum value is : -9,223,372,036,854,775,808.( -2^63)
Maximum value is : 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
Default value is : 0L
This type is used when a wider range than int is needed

Syntax :
long Variable_Name = Value_L;
Example (DataType_Long.java) :
public class DataType_Long {

long a = 1000L;
long b = -2000L;

void add() {

long c = a + b;

System.out.println("The Long Value is : " + c);


}
}

class MainClass {

public static void main(String args[]) {

DataType_Long obj = new DataType_Long();

obj.add();
}
}
Sample Output

The Long Value is : -1000

1
0

E. Float
1.
2.
3.
4.

Float data type is a single -precision 32 -bit IEEE 754 floating point
Default value is : 0.0f
Float data type is never used for precise values such as currency
Float is mainly used to save memory in large arrays of floating point numbers

Syntax :
float Variable_Name = (float) Value;
Example (DataType_Float.java) :
public class DataType_Float {

float a = (float) 10.56;


float b = (float) -23.57;

void add() {

float c = a + b;

System.out.println("The Float Vaue is : " + c);


}
}

class MainClass {

public static void main(String args[]) {

DataType_Float obj = new DataType_Float();

obj.add();
}
}
Sample Output

The Float Vaue is : -13.009999

1
0

F. Double
1.
2.
3.
4.

double data type is a double -precision 64 -bit IEEE 754 floating point
Default value is : 0.0d
Double data type should never be used for precise values such as currency
This data type is generally used as the default data type for decimal values. generally the default
choice

Syntax :
double Variable_Name = Value;
Example (DataType_Double.java) :
public class DataType_Double {

double a = 123.456;
double b = -45.894;

void add() {

double c = a + b;
System.out.println("The Double Value is : " + c);
}

class MainClass {

public static void main(String args[]) {

DataType_Double obj = new DataType_Double();

obj.add();
}
}
Sample Output

The Double Value is : 77.56200000000001

1
0

G. Boolean
1.
2.
3.
4.

boolean data type represents one bit of information


There are only two possible values : true and false
This data type is used for simple flags that track true/false conditions
Default value is : false

Syntax :
boolean Variable_Name = Value (true/false);
Example (DataType_Boolean.java) :
public class DataType_Boolean {

boolean a = true;

void check() {

if(a == true) {
a = false;
System.out.println("The Boolean Value is : " + a);
}
}
}

class MainClass {
public static void main(String args[]) {
DataType_Boolean obj = new DataType_Boolean();

obj.check();
}
}
Sample Output

The Boolean Value is : false

1
0

H. Char
1.
2.
3.
4.

char data type is a single 16 -bit Unicode character


Minimum value is : '\u0000' (or 0)
Maximum value is : '\uffff' (or 65,535 inclusive)
Char data type is used to store any character

Syntax :
char Variable_Name = Value;
Example (DataType_Char.java) :
public class DataType_Char {

char a = 'J';
char b = 'A';
char c = 'V';
char d = 'A';

void join() {

System.out.println("The Characters Value is : " + a+b+c+d);


}
}

class MainClass {

public static void main(String args[]) {

DataType_Char obj = new DataType_Char();

obj.join();
}
}
Sample Output

The Characters Value is : JAVA

1
0

Program 21
A. Syntax
if(condition) {
// Statement if the condition is true..
}
if(condition) {
// Statement-1 if the condition is true..
}else {
// Statement-2 if the condition is false..
}
if(condition-1) {
// Statement-1 if the condition-1 is true..
}else if(condition-2) {
// Statement-2 if the condition-2 is true..
}else {
// Statement-3 if both conditions are false..
}
if(condition-1) {
// Statement-1 if the condition-1 is true..
}else if(condition-2) {
// Statement-2 if the condition-2 is true..
}else if(condition-3) {
// Statement-3 if the condition-3 is true..
}
if(condition-1) {
// Statement-1 if condition-1 is true..}
if(condition-2) {
// Statement-2 if condition-2 is true..}
if(condition-3) {
// Statement-3 if condition-3 is true..}

1
0

B. if statement
If_Ex1.java
public class If_Ex1 {

int a = 10;
int b = 8;
int c;

void add() {

c = a + b;
}

void check() {

if (c >= a) {

System.out.println("The Addition is : " + c);


}
}
}

class MainClass {

public static void main(String args[]) {

If_Ex1 obj = new If_Ex1();


obj.add();
obj.check();
}
}
Sample Output

The Addition is : 18

1
0

C. if...else statement

If_Ex2.java
public class If_Ex2 {

boolean ans = true;

void check() {

if(ans == false) {

System.out.println("The Answer is false");


}
else {

System.out.println("The Answer is true");


}
}
}

class MainClass {

public static void main(String args[]) {

If_Ex2 obj = new If_Ex2();


obj.check();
}
}
Sample Output

The Answer is true

1
0

D. if..elseif...else statement

If_Ex3.java
public class If_Ex3 {

int a = 11;
int b = 20;
int c = 18;

void check() {

if(a>b && a>c) {

System.out.println("A is Greater !!!");


}
else if(b>a && b>c) {

System.out.println("B is Greater !!!");


}
else {

System.out.println("C is Greater !!!");


}
}
}
class MainClass {
public static void main(String args[]) {

If_Ex3 obj = new If_Ex3();


obj.check();
}
}
Sample Output

B is Greater !!!

1
0

E. if...elseif...elseif statement
If_Ex5.java
public class If_Ex5 {

int a = 3;

void check() {

if(a == 1) {
System.out.print("'A' is : 1");
}else if(a == 2) {
System.out.print("'A' is : 2");
}else if(a == 3) {
System.out.print("'A' is : 3");
}
}
}

class MainClass {

public static void main(String args[]) {

If_Ex5 obj = new If_Ex5();


obj.check();
}
}
Sample Output

'A' is : 3

1
0

F. if...if...if statement

If_Ex4.java
public class If_Ex4 {

int a = 11;
int b = 20;
int c = 18;

void check() {

if(a>b && a>c) {

System.out.println("A is Greater !!!");


}
if(b>a && b>c) {

System.out.println("B is Greater !!!");


}
if(c>a && c>b) {

System.out.println("C is Greater !!!");


}
}
}

class MainClass {
public static void main(String args[]) {
If_Ex4 obj = new If_Ex4();
obj.check();
}
}
Sample Output

B is Greater !!!

1
0

A. Syntax
for loop
for(initialize; condition; increment) {
// Statement Loop..
}
foreach loop
for(type varName : iterableObj) {
// Get Iterable Object's Individual Value..
}

B. for loop (int Values) in Java


For_Ex1.java
public class For_Ex1 {
void display(int n) {
for(int i=1; i<=n; i++) {
System.out.println("for - i : " + i);
}
}
}
class MainClass {
public static void main(String[] args) {
For_Ex1 obj = new For_Ex1();
obj.display(5);
}
}
Sample Output
for - i : 1
for - i : 2
for - i : 3
for - i : 4
for - i : 5

1
0

C. for loop (float Values) in Java


For_Ex5.java
public class For_Ex5 {
void display() {
for(float i=(float) 0.0; i<=0.5; i = (float) (i + 0.1)) {
System.out.println("for - Float Value : " + i);
}
}
}
class MainClass {
public static void main(String args[]) {
For_Ex5 obj = new For_Ex5();
obj.display();
}
}
Sample Output

for - Float Value : 0.0


for - Float Value : 0.1
for - Float Value : 0.2
for - Float Value : 0.3
for - Float Value : 0.4
for - Float Value : 0.5

1
0

D. foreach loop in Java


For_Ex2.java
public class For_Ex2 {
int[] value = {10, 20, 30, 40, 50, 60};
void display() {
for(int i : value) {
System.out.println("foreach i = i * 100;

i : " + i);

// No defect on value..

}
}
}
class MainClass {
public static void main(String args[]) {
For_Ex2 obj = new For_Ex2();
obj.display();
}
}

Sample Output

foreach -

i : 10

foreach -

i : 20

foreach -

i : 30

foreach -

i : 40

foreach -

i : 50

foreach -

i : 60

1
0

E. foreach (enum Values) loop in Java


For_Ex3.java
public class For_Ex3 {
enum days {Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday, Sunday};
void display() {
for(days day : days.values()) {
System.out.println("Enum Value : " + day);
}
}
}
class MainClass {
public static void main(String args[]) {
For_Ex3 obj = new For_Ex3();
obj.display();
}
}
Sample Output

Enum Value : Monday


Enum Value : Tuesday
Enum Value : Wednesday
Enum Value : Thursday
Enum Value : Friday
Enum Value : Saturday
Enum Value : Sunday

1
0

F. foreach (ArrayList<Double>) loop in Java


For_Ex4.java
import java.util.ArrayList;
public class For_Ex4 {
ArrayList<Double> list = new ArrayList<Double>();
double sum = 0.0;
void add() {
list.add(111.120);
list.add(102.658);
list.add(653.123);
}
void display() {
for(double i : list)
sum = sum + i;
System.out.println("The Sum of ArrayList Value is : " + sum);
}
}
class MainClass {
public static void main(String args[]) {
For_Ex4 obj = new For_Ex4();
obj.add();
obj.display();
}
}
Sample Output

The Sum of ArrayList Value is : 866.9010000000001

1
0

A. Syntax
While
while(condition) {
// Statement if the condition is true..
}
Do While
do {
// Do Statement at least once and then check condition..
} while(condition);

B. While Loop in Java


While_Ex1.java
public class While_Ex1 {
int i = 1;
void check(int n) {
while(i<n) {
System.out.println("While - i : " + i);
i++;
}
}
}

class MainClass {
public static void main(String args[]) {
While_Ex1 obj = new While_Ex1();
obj.check(4);
}
}
Sample Output
While - i : 1
While - i : 2
While - i : 3

1
0

C. Do While Loop in Java


DoWhile_Ex1.java
public class DoWhile_Ex1 {
int i = 1;
void check(int n) {
do {
System.out.println("Do While - i : " + i);
i++;
} while(i<n);
}
}

class MainClass {
public static void main(String args[]) {
DoWhile_Ex1 obj = new DoWhile_Ex1();
obj.check(4);
}
}
Sample Output

Do While - i : 1
Do While - i : 2
Do While - i : 3

1
0

D. While & Do-While Differentiation


While_Ex2.java
public class While_Ex2 {
int i = 1;
void check1(int n) {
while(i < n) {
System.out.println("While - i : " + i);
}
}
void check2(int n) {
do {
System.out.println("Do While - i : " + i);
} while(i < n);
}
}
class MainClass {
public static void main(String args[]) {
While_Ex2 obj = new While_Ex2();
obj.check1(1);
obj.check2(1);
}
}
Sample Output

Do While - i : 1

1
0

A. Syntax
Switch Statement
switch(caseValue) {
case caseValue1 :
// Statement-1 if caseValue1 = caseValue
break;
case caseValue2 :
// Statement-2 if caseValue2 = caseValue
break;
case caseValue3 :
// Statement-3 if caseValue3 = caseValue
break;
default :
// Statement-4 if caseValue is not available..
}

B. Switch Statement (int) in Java


Switch_Ex1.java
public class Switch_Ex1 {
void display(int n) {
switch(n) {
case 1 :
System.out.println("Switch Case : 1");
break;
case 2 :
System.out.println("Switch Case : 2");
break;
case 3 :
System.out.println("Switch Case : 3");
break;
default :
System.out.println("Switch Case : Default");
}
}

1
0

class MainClass {

public static void main(String args[]) {

Switch_Ex1 obj = new Switch_Ex1();


obj.display(2);
obj.display(10);
}
}
Sample Output

Switch Case : 2
Switch Case : Default

C. Switch Statement (char) in Java


Switch_Ex2.java
public class Switch_Ex2 {

void display(char name) {

switch(name) {

case 'A':
System.out.println("Switch Case : A");
break;
case 'B' :
System.out.println("Switch Case : B");
break;
case 'C' :
System.out.println("Switch Case : C");
break;
default :

1
0

System.out.println("Switch Case : Default");


}
}
}

class MainClass {

public static void main(String args[]) {

Switch_Ex2 obj = new Switch_Ex2();


obj.display('B');
obj.display('A');
obj.display('Y');

}
}
Sample Output

Switch Case : B
Switch Case : A
Switch Case : Default

D. Switch Statement (enum) in Java

Switch_Ex3.java
public class Switch_Ex3 {

enum friends {Boobalan, Vinoth, Mani, Rahul, Kumaresan};

void display() {

for(friends guys : friends.values()) {

switch(guys) {

1
0

case Boobalan :
System.out.println("Boobalan");
break;
case Vinoth :
System.out.println("Vinoth");
break;
case Mani :
System.out.println("Mani");
break;
case Rahul :
System.out.println("Rahul");
break;
case Kumaresan :
System.out.println("Kumaresan");
break;
default :
System.out.println("Friends");
}
}
}
}

class MainClass {

public static void main(String args[]) {

Switch_Ex3 obj = new Switch_Ex3();


obj.display();
}
}
Sample Output
Boobalan
Vinoth
Mani
Rahul
Kumaresan

1
0

Program 21
A. Generate Fibonacci Series upto N times in Java

Fibonacci_Ex1.java
import java.util.Scanner;

public class Fibonacci_Ex1 {

public static void main(String args[]) {

Scanner scan = new Scanner(System.in);

System.out.println("Enter 'N' value

: ");

int n = Integer.parseInt(scan.nextLine());

int a = -1;
int b = 1;
int c = 0;

System.out.println("The Fibonacci Series are : ");

for(int i=1; i<=n; i++) {

c = a + b;
int temp = a;
a = b;
b = c;
System.out.println(c);
}
}
}
Sample Output
Enter 'N' value

10

1
0

The Fibonacci Series are :


0
1
1
2
3
5
8
13
21
34

B. Factorial using Recursion in Java


Factorial_Ex1.java
import java.util.Scanner;
public class Factorial_Ex1 {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);

System.out.println("Enter the number : ");


int n = Integer.parseInt(scan.nextLine());
int factorial = fact(n);
System.out.println("The Factorial is : " + factorial);
}
private static int fact(int x) {
if (x > 1)
x = x * fact(x-1);
return x;
}
}

Sample Output
Enter the number :
8

1
0

C. Palindrome - String Value in Java

Palindrome_Ex1.java
import java.util.Scanner;

public class Palindrome_Ex1 {

void check(String name) {

char[] c1 = new char[name.length()];


String rev = "";

for(int i=0; i<name.length(); i++) {

c1[i] = name.charAt((name.length()-1) - i);


rev = rev + c1[i];
}

if(name.equals(rev)) {
System.out.println(name + " is Palindrome");
}
else {
System.out.println(name + " is not Palindrome");
}
}
}

class MainClass {

public static void main(String args[]) {

Palindrome_Ex2 obj = new Palindrome_Ex2();

Scanner scan = new Scanner(System.in);

System.out.println("Enetr the String :");


String name = scan.nextLine();

1
0

obj.check(name);
}
}
Sample Output

Enetr the String :


mom
mom is Palindrome
Enetr the String :
Mom
Mom is not Palindrome

D. Palindrome - Integer Value in Java


Palindrome_Ex2.java
import java.util.Scanner;
public class Palindrome_Ex2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the Number : ");
int num= Integer.parseInt(scan.nextLine());

int n = num;
int rev=0;

for (int i=0; i<=num; i++) {

1
0

int r = num % 10;


num = num / 10;
rev = (rev * 10) + r;
i = 0;
}

if(n == rev){
System.out.println(n + " is Palindrome");
}
else{
System.out.println(n + " is not Palindrome");
}
}
}

Sample Output

Enter the Number :


1234321
1234321 is Palindrome
Enter the Number :
123
123 is not Palindrome

1
0

E. Palindrome - Float Value in Java

Palindrome_Ex3.java
import java.util.Scanner;

public class Palindrome_Ex3 {

float number;

void getVal() {

System.out.println("Enter the number : ");


Scanner scan = new Scanner(System.in);

number = Float.parseFloat(scan.nextLine());
}

void divide() {

float temp = number;


String st = String.valueOf(temp);

String str[] = st.split("\\.");

int before = Integer.parseInt(str[0]);


int after = Integer.parseInt(str[1]);

String str1 = String.valueOf(revere(before));


String str2 = String.valueOf(revere(after));

if(str1.equals(str[0]) && str2.equals(str[1]))


System.out.println(number + " is a Palindrome");
else
System.out.println(number + " is not a Palindrome");
}

private int revere(int value) {

1
0

int mod;
int sum = 0;

while(value != 0) {

mod = value % 10;


sum = sum * 10 + mod;
value = value / 10;
}

return sum;
}
}

class MainClass {

public static void main(String args[]) {

Palindrome_Ex3 obj = new Palindrome_Ex3();

obj.getVal();
obj.divide();
}
}
Sample Output

Enter the number :


121.363
121.363 is a Palindrome
Enter the number :
121.369
121.369 is not a Palindrome

1
0

F. Check Given number is Odd or Even in Java


OddEven_Ex1.java
import java.util.Scanner;
public class OddEven_Ex1 {
Scanner scan;
int num;
void getVal() {
scan = new Scanner(System.in);
System.out.println("Check Odd or Even");
System.out.println("\nEnter the number : ");
num = Integer.parseInt(scan.nextLine());
}
void check() {
if((num % 2) == 0)
System.out.println(num + " is Even number");

else
System.out.println(num + " is Odd number");
}
}
class MainClass {
public static void main(String args[]) {
OddEven_Ex1 obj = new OddEven_Ex1();
obj.getVal();
obj.check();
}
}
Sample Output
Check Odd or Even
Enter the number :
111
111 is Odd number
Check Odd or Even
Enter the number :
120
120 is Even number

1
0

G. Find Odd numbers between two numbers in Java


OddEven_Ex2.java
import java.util.Scanner;

public class OddEven_Ex2 {

Scanner scan;
int start, end;

void getVal() {

scan = new Scanner(System.in);


System.out.println("Find Odd numbers between two numbers");

System.out.println("\nEnter the Starting value : ");


start = Integer.parseInt(scan.nextLine());

System.out.println("Enter the End value : ");


end = Integer.parseInt(scan.nextLine());
}

void check() {

System.out.println();

for(int i=start; i<=end; i++) {

if((i % 2) != 0)
System.out.println(i + " is Odd number");
}
}
}

class MainClass {

public static void main(String args[]) {

1
0

OddEven_Ex2 obj = new OddEven_Ex2();

obj.getVal();
obj.check();
}
}
Sample Output

Find Odd numbers between two numbers

Enter the Starting value :


25
Enter the End value :
38

25 is Odd number
27 is Odd number
29 is Odd number
31 is Odd number
33 is Odd number
35 is Odd number
37 is Odd number

H. Check given year is Leap year or not in Java

Leap_Ex1.java

import java.util.Scanner;

public class Leap_Ex1 {

int year;
Scanner scan;

void check() {

1
0

System.out.println("Check leap year or not");

System.out.println("\nEnter the year : ");


scan = new Scanner(System.in);

year = Integer.parseInt(scan.nextLine());

if(year%400 == 0 || year%4 == 0)
System.out.println(year + " is a leap year");

else
System.out.println(year + " is not a leap year");
}
}

class MainClass {

public static void main(String str[]) {

Leap_Ex1 obj = new Leap_Ex1();

obj.check();
}
}
Sample Output
Check leap year or not

Enter the year :


1994
1994 is not a leap year
Check leap year or not

Enter the year :


2012
2012 is a leap year

1
0

H. Int Value Swap in Java

Swap_Ex1.java
import java.util.Scanner;

public class Swap_Ex1 {

int a, b, temp;
Scanner scan;

void getVal() {

scan = new Scanner(System.in);


System.out.println("Integer Swapping method\n");

System.out.println("Enter first value 'a' : ");


a = Integer.parseInt(scan.nextLine());

System.out.println("Enter second value 'b' : ");


b = Integer.parseInt(scan.nextLine());
}

void swap() {

System.out.println("\nBefore Swapping\na : " + a + " & b : " + b);

temp = a;
a = b;
b = temp;

System.out.println("\nAfter Swapping\na : " + a + " & b : " + b);


}
}

class MainClass {

public static void main(String args[]) {

1
0

Swap_Ex1 obj = new Swap_Ex1();

obj.getVal();
obj.swap();
}
}
Sample Output

Integer Swapping method

Enter first value 'a' :


10
Enter second value 'b' :
20

Before Swapping
a : 10 & b : 20

After Swapping
a : 20 & b : 10

I. Float Value Swap in Java

Swap_Ex2.java
import java.util.Scanner;

public class Swap_Ex2 {

float a, b, temp;
Scanner scan;

void getVal() {

1
0

scan = new Scanner(System.in);


System.out.println("Integer Swapping method\n");

System.out.println("Enter first value 'a' : ");


a = Float.parseFloat(scan.nextLine());

System.out.println("Enter second value 'b' : ");


b = Float.parseFloat(scan.nextLine());
}

void swap() {

System.out.println("\nBefore Swapping\na : " + a + " & b : " + b);

temp = a;
a = b;
b = temp;

System.out.println("\nAfter Swapping\na : " + a + " & b : " + b);


}
}

class MainClass {

public static void main(String args[]) {

Swap_Ex2 obj = new Swap_Ex2();

obj.getVal();
obj.swap();
}
}
Sample Output

Integer Swapping method

1
0

Enter first value 'a' :


10.50
Enter second value 'b' :
20.60

Before Swapping
a : 10.5 & b : 20.6

After Swapping
a : 20.6 & b : 10.5

J. String Value Swap in Java


Swap_Ex3.java
import java.util.Scanner;

public class Swap_Ex3 {

String a, b, temp;
Scanner scan;

void getVal() {

scan = new Scanner(System.in);


System.out.println("Integer Swapping method\n");

System.out.println("Enter first value 'a' : ");


a = scan.nextLine();

System.out.println("Enter second value 'b' : ");


b = scan.nextLine();
}

void swap() {

System.out.println("\nBefore Swapping\na : " + a + " & b : " + b);

1
0

temp = a;
a = b;
b = temp;

System.out.println("\nAfter Swapping\na : " + a + " & b : " + b);


}
}

class MainClass {

public static void main(String args[]) {

Swap_Ex3 obj = new Swap_Ex3();

obj.getVal();
obj.swap();
}
}
Sample Output

Integer Swapping method

Enter first value 'a' :


XYZ
Enter second value 'b' :
ABC

Before Swapping
a : XYZ & b : ABC

After Swapping
a : ABC & b : XYZ

1
0

K. Swap method without using third variable

Swap_Ex4.java
import java.util.Scanner;

public class Swap_Ex4 {

int a, b, temp;
Scanner scan;

void getVal() {

scan = new Scanner(System.in);


System.out.println("Integer Swapping method\n");

System.out.println("Enter first value 'a' : ");


a = Integer.parseInt(scan.nextLine());

System.out.println("Enter second value 'b' : ");


b = Integer.parseInt(scan.nextLine());
}

void swap() {

1
0

System.out.println("\nBefore Swapping\na : " + a + " & b : " + b);

a = a + b;
b = a - b;
a = a - b;

System.out.println("\nAfter Swapping\na : " + a + " & b : " + b);


}
}

class MainClass {

public static void main(String args[]) {

Swap_Ex4 obj = new Swap_Ex4();

obj.getVal();
obj.swap();
}
}

Sample Output

Integer Swapping method

Enter first value 'a' :

1
0

11
Enter second value 'b' :
20

Before Swapping
a : 11 & b : 20

After Swapping
a : 20 & b : 11

L. Count digits of Given number in Java

CSP_Ex1.java
import java.util.Scanner;

public class CSP_Ex1 {

Scanner scan;
int num;

void getVal() {

scan = new Scanner(System.in);

System.out.println("Count the digits of given Number");

System.out.println("\nEnter the number");


num = Integer.parseInt(scan.nextLine());
}

void display() {

int temp = num;


int count = 0;

while(temp != 0) {

1
0

temp = temp / 10;


count ++;
}

System.out.println("The Digit Count is : " + count);


}
}

class MainClass {

public static void main(String args[]){

CSP_Ex1 obj = new CSP_Ex1();

obj.getVal();
obj.display();
}
}
Sample Output

Count the digits of given Number

Enter the number


589461256
The Digit Count is : 9

M. Sum digits of Given number in Java

CSP_Ex2.java
import java.util.Scanner;

public class CSP_Ex2 {

1
0

Scanner scan;
int num;

void getVal() {

scan = new Scanner(System.in);

System.out.println("Sum the digits of given Number");

System.out.println("\nEnter the number");


num = Integer.parseInt(scan.nextLine());
}

void display() {

int temp = num;


int sum = 0;
int mod = 0;

while(temp != 0) {

mod = temp % 10;


sum = sum + mod;
temp = temp / 10;
}

System.out.println("The Digit Count is : " + sum);


}
}

class MainClass {

public static void main(String args[]){

CSP_Ex2 obj = new CSP_Ex2();

obj.getVal();

1
0

obj.display();
}
}
Sample Output

Sum the digits of given Number

Enter the number


123456
The Digit Count is : 21

O. Power of Given number in Java


CSP_Ex3.java
import java.util.Scanner;

public class CSP_Ex3 {

Scanner scan;
int num, power;

void getVal() {

scan = new Scanner(System.in);

System.out.println("Power of given Number");

System.out.println("\nEnter the number");


num = Integer.parseInt(scan.nextLine());

System.out.println("Power of :");
power = Integer.parseInt(scan.nextLine());
}

void display() {

1
0

int sum = 0;

sum = (int) Math.pow(num, power);

System.out.println("The Digit Count is : " + sum);


}
}

class MainClass {

public static void main(String args[]){

CSP_Ex3 obj = new CSP_Ex3();

obj.getVal();
obj.display();
}
}
Sample Output

Power of given Number

Enter the number


25
Power of :
2
The Digit Count is : 625

1
0

P. Round the value of Given number in Java


CSP_Ex4.java
import java.util.Scanner;
public class CSP_Ex4 {

Scanner scan;
float num;

void getVal() {

scan = new Scanner(System.in);

System.out.println("Round of given Number");

System.out.println("\nEnter the number");


num = Float.parseFloat(scan.nextLine());
}

void display() {

float round = 0;

round = Math.round(num);

1
0

System.out.println("The Digit Count is : " + round);


}
}

class MainClass {

public static void main(String args[]){

CSP_Ex4 obj = new CSP_Ex4();

obj.getVal();
obj.display();
}
}

Sample Output

Round of given Number

Enter the number


11.49
The Digit Count is : 11.0
Round of given Number

Enter the number


11.50
The Digit Count is : 12.0

1
0

Program 22
A. Syntax for a Class in Java

ClassName.java
public class ClassName {

// Declare Variables and Method

public ClassName() {

// Initialise values to Variables


}

public void functionName() {

// Write Code Inside Method


}
}

class MainClassName {

public static void main(String args[]) {

/*
*
* Create Object to ClassName class
*
* Access Variables and Methods inside ClassName class
*
*/
}
}

1
0

B. Create a Class in Java

Class_Example_1.java
public class Class_Example_1 {
int a;
float b;
String str;
public Class_Example_1()
{
a = 10;
b = (float) 15.26;
str = "Java";
}
public void display()
{
System.out.println("The Integer Value is : "+a);
System.out.println("The Float Value is : "+b);
System.out.println("The String Value is : "+str);
}
}

class mainClass {
public static void main (String args[])
{
Class_Example_1 obj = new Class_Example_1();
obj.display();
}
}
Sample Output

The Integer Value is : 10


The Float Value is : 15.26
The String Value is : Java

1
0

C. Create More Classes in Java

Class_Example_2.java
public class Class_Example_2 {

void display1() {

System.out.println("This is Class - 1");


}
}

class Class2 {

void display2() {

System.out.println("This is Class - 2");


}
}

class Class3 {

void display3() {

System.out.println("This is Class - 3");


}
}

class MainClass {

public static void main(String[] args) {

Class_Example_2 obj1 = new Class_Example_2();


Class2 obj2 = new Class2();
Class3 obj3 = new Class3();

obj1.display1();
obj2.display2();

1
0

obj3.display3();
}
}
Sample Output

This is Class - 1
This is Class - 2
This is Class - 3

D. Create Nested Classes in Java


Class_Ex4.java
public class Class_Ex4 {

int a, b, c;

Class_Ex4() {

a = 10;
b = 20;
}

class InnerClass {

InnerClass() {

c = a +b;
}

void display() {

System.out.println("The Addition is : " + c);


}
}

1
0

void display() {

System.out.println("'A' is : " + a);


System.out.println("'B' is : " + b);
}
}

class MainClass {

public static void main(String args[]) {

Class_Ex4 obj1 = new Class_Ex4();


Class_Ex4.InnerClass obj2 = obj1.new InnerClass();

obj1.display();
obj2.display();
}
}
Sample Output

'A' is : 10
'B' is : 20
The Addition is : 30

A. Syntax for an Object in Java

ClassName.java
public class ClassName {

// Initialise Variables

public ClassName() {

// Write Code Inside Constructor


}

1
0

class MainClassName {

public static void main(String args[]) {

ClassName ObjectName = new ClassName();


}
}

B. Create an Object for a Class in Java

Object_Ex1.java
public class Object_Ex1 {

int a = 10;
int b = 20;
int c;

public Object_Ex1() {

c = a + b;
System.out.println("The Addition is : "+c);
}
}

class MainClass {

public static void main(String args[]) {

Object_Ex1 obj = new Object_Ex1();


}
}

1
0

Sample Output

The Addition is : 30

C. Accessing Variables using Object in Java

Objext_Ex2.java
public class Objext_Ex2 {
int a = 10;
float b = (float)56.23;
String str = "Java";
}

class MainClass {

public static void main(String args[]) {

Objext_Ex2 ObjectName = new Objext_Ex2();

System.out.println("The Integer Value is : "+ ObjectName.a);


System.out.println("The Float Value is : "+ ObjectName.b);
System.out.println("The String Value is : "+ ObjectName.str);
}
}
Sample Output

The Integer Value is : 10


The Float Value is : 56.23
The String Value is : Java

1
0

D. Accessing Methods using Object in Java

Objext_Ex3.java
public class Object_Ex3 {

int a;
float b;
String str;

public Object_Ex3() {

a = 100;
b = (float)10.20;
str = "Open Source";
}

public void Method() {

System.out.println("The Integer Value is : "+ a);


System.out.println("The Float Value is : "+b);
System.out.println("The String Value is : "+str);
}
}

class MainClass {
public static void main(String args[]) {
Object_Ex3 ObjectName = new Object_Ex3();
ObjectName.Method();
}
}
Sample Output

The Integer Value is : 100


The Float Value is : 10.2
The String Value is : Open Sourc

1
0

Program 23
A. Syntax
Constructor
class ClassName {

ClassName() {

// Statement..
}
}

class MainClass {

public static void main(String args[]) {

ClassName objName = new ClassName();


// We don't want to call the Constructor..
// It will automatically call when we create object for that class..
}
}

B. Contructor Creation in Java


Constructor_Ex1.java
public class Constructor_Ex1 {

int a, b, c;

Constructor_Ex1() {

System.out.println("Constructor - Simple Example");

a = 11;

1
0

b = 20;
c = a + b;
}

void display() {
System.out.println("The Addition is : " + c);
}
}

class MainClass {

public static void main(String args[]) {


Constructor_Ex1 obj = new Constructor_Ex1();
obj.display();
}
}
Sample Output
Constructor - Simple Example
The Addition is : 31

C. Constructor Overloading in Java


Constructor_Ex2.java
public class Constructor_Ex2 {

Constructor_Ex2() {

System.out.println("Constructor Overloading Example");


}

Constructor_Ex2(int x) {

System.out.println("Constructor int - " + x);


}
Constructor_Ex2(float x) {

1
0

System.out.println("Constructor float - " + x);


}

Constructor_Ex2(char x) {
System.out.println("Constructor char - " + x);
}
}

class MainClass {

public static void main(String args[]) {

Constructor_Ex2 obj1 = new Constructor_Ex2();


Constructor_Ex2 obj2 = new Constructor_Ex2(111);
Constructor_Ex2 obj3 = new Constructor_Ex2((float) 11.20);
Constructor_Ex2 obj4 = new Constructor_Ex2('B');
}
}
Sample Output
Constructor Overloading Example
Constructor int - 111
Constructor float - 11.2
Constructor char - B

D. Create More Constructors for More Classes


Constructor_Ex3.java
public class Constructor_Ex3 {
Constructor_Ex3() {
System.out.println("More Classes and More Constructors");
}
}

1
0

class SubClass1 {
SubClass1() {
System.out.println("SubClass - 1");
}
}
class SubClass2 {
SubClass2() {
System.out.println("SubClass - 2");
}
}

class MainClass {
public static void main(String args[]) {
Constructor_Ex3 obj1 = new Constructor_Ex3();
SubClass1 obj2 = new SubClass1();
SubClass2 obj3 = new SubClass2();
}
}

Sample Output

More Classes and More Constructors


SubClass - 1
SubClass - 2

1
0

Program 24
class A{
public static void main(String args[]){
System.out.println("Enter some message at time of execution of Program: \t eg:
java A txt msg");

for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
Sample Output
Enter some message at time of execution of Program:

eg: java A txt msg

sonoo
jaiswal
1
3
abc

1
0

Program 25
A. Same Length Attributes Method Overloading
Poly_Ex1.java
public class Poly_Ex1 {
int a;
float b;
String str;

Poly_Ex1() {
a = 11;
b = (float)11.11;
str = "Method ";
}

void display(int x) {
a = a+x;
System.out.println("The Integer Value is : "+ a);
}

void display(float y) {
b = b+y;
System.out.println("The Float Value is : "+ b);
}

void display(String z) {
str = str.concat(z);
System.out.println("The String Value is : "+ str);
}
}

class MainClass {

public static void main(String args[]) {

Poly_Ex1 obj = new Poly_Ex1();

1
0

obj.display(100);
obj.display((float)23.56);
obj.display("Overloading !!!");
}
}
Sample Output

The Integer Value is : 111


The Float Value is : 34.67
The String Value is : Method Overloading !!!

B. Different Length Attributes Method Overloading


Poly_Ex2.java
public class Poly_Ex2 {

void display() {

System.out.println("Welcome");
}

void display(int x, int y) {

int a = x + y;
System.out.println("int, int Combination : "+a);
}

void display(int x, float y) {

float a = x + y;
System.out.println("int, float Combination : "+a);
}

void display(String x, String y) {

1
0

String a = x.concat(y);
System.out.println("string, string Combination : "+a);
}
}

class MainClass {

public static void main(String args[]) {

Poly_Ex2 obj = new Poly_Ex2();

obj.display();
obj.display(10, 20);
obj.display(20, (float)50.45);
obj.display("Method ", "Overloading !!!");
}
}
Sample Output

Welcome
int, int Combination : 30
int, float Combination : 70.45
string, string Combination : Method Overloading !!!

C. Same Length Attributes Constructor Overloading

Poly_Ex3.java
public class Poly_Ex3 {

Poly_Ex3(String x) {

System.out.println(x);
}

1
0

Poly_Ex3(int x) {

System.out.println("Int Value : "+x);


}

Poly_Ex3(float x) {

System.out.println("Float Value : "+x);


}
}

class MainClass {

public static void main(String args[]) {

Poly_Ex3 obj1 = new Poly_Ex3("Constructor Overloading !!!");


Poly_Ex3 obj2 = new Poly_Ex3(11);
Poly_Ex3 obj3 = new Poly_Ex3((float)32.65);
}
}
Sample Output

Constructor Overloading !!!


Int Value : 11
Float Value : 32.65

D. Different Length Attributes Constructor Overloading


Poly_Ex4.java
public class Poly_Ex4 {
Poly_Ex4() {
System.out.println("Welcome !!!");
}
Poly_Ex4(String x, String y) {

1
0

x = x.concat(y);
System.out.println(x);
}
Poly_Ex4(int x, int y) {
x = x+y;
System.out.println("int, int Combination : "+x);
}
Poly_Ex4(int x, float y) {
y = x+y;
System.out.println("int, float Combination : "+y);
}
}
class MainClass {
public static void main(String args[]) {
Poly_Ex4 obj1 = new Poly_Ex4();
Poly_Ex4 obj2 = new Poly_Ex4("Constructor ", "Overloading");
Poly_Ex4 obj3 = new Poly_Ex4(5,10);
Poly_Ex4 obj4 = new Poly_Ex4(23,(float) 56.23);
}
}

Sample Output

Welcome !!!
Constructor Overloading
int, int Combination : 15
int, float Combination : 79.229996

1
0

Program 26
A. Core packages in J2SE 6

java.lang

basic language functionality and fundamental types

java.util

collection data structure classes

java.io

file operations

java.math

multiprecision arithmetics

java.nio -

the New I/O framework for Java

java.net -

networking operations, sockets, DNS lookups, ...

java.security

java.sql -

Java Database Connectivity (JDBC) to access databases

java.awt -

basic hierarchy of packages for native GUI components

javax.swing
components

hierarchy of packages for platform-independent rich GUI

java.applet

classes for creating an applet

key generation, encryption and decryption

B. Pre defined Packages - Call a Class within the File itself in Java
Package_Ex1.java
package TopLevelPackage.SubPackage.java;

// The below packages are J2SE pre defined packages..


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class Package_Ex1 {


Scanner scan;
InputStreamReader isr;
int num;
String name;

1
0

void getVal() {
System.out.println("Java Pre defined Packages " +
"- Call a Class within the File itself");
System.out.println("\nEnter a number :");
scan = new Scanner(System.in);
num = scan.nextInt();

System.out.println("\nEnter a String :");


BufferedReader br = new BufferedReader
(new InputStreamReader(System.in));
try {
name = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
}
}

class MainClass {
public static void main(String args[]) {
Package_Ex1 obj = new Package_Ex1();
obj.getVal();
}
}
Sample Output
Java Pre defined Packages - Call a Class within the File itself
Enter a number :
111
Enter a String :
XYZ

1
0

C. User defined Package - Call a Class within the Package in Java


Package_Ex2.java
package TopLevelPackage.SubPackage.java;
import java.util.Scanner;
public class Package_Ex2 {
public int a, b, c;
Scanner scan;
public void getVal() {
System.out.println("Java User defined Package " +
"- Call a Class within the Package");
scan = new Scanner(System.in);
System.out.println("\nEnter value of 'a' :");
a = Integer.parseInt(scan.nextLine());

System.out.println("Enter value of 'b' :");


b = Integer.parseInt(scan.nextLine());
}
public void add() {
c = a + b;
}
public void display() {
System.out.println("\nThe Sum is : " + c);
}
}
MainClass.java
package TopLevelPackage.SubPackage.java;
public class MainClass {
public static void main(String args[]) {
Package_Ex2 obj = new Package_Ex2();
obj.getVal();
obj.add();
obj.display();
}
}

1
0

Sample Output
Java User defined Package - Call a Class within the Package
Enter value of 'a' :
11
Enter value of 'b' :
20
The Sum is : 31

D. User defined Package - Call another Package Class in Java


Package_Ex3.java
package TopLevelPackage.SubPackage.java;
import java.util.Scanner;
public class Package_Ex3 {
public int a, b, c;
Scanner scan;
public void getVal() {
System.out.println("Java User defined Package " +
"- Call another Package's Class");
scan = new Scanner(System.in);
System.out.println("\nEnter value of 'a' :");
a = Integer.parseInt(scan.nextLine());
System.out.println("Enter value of 'b' :");
b = Integer.parseInt(scan.nextLine());
}
public void add() {
c = a + b;
}
public void display() {
System.out.println("\nThe Sum is : " + c);
}

1
0

MainClass.java
package TopLevelPackage.scz.java;

import TopLevelPackage.SubPackage.java.Package_Ex3;
public class MainClass {
public static void main(String args[]) {
Package_Ex3 obj = new Package_Ex3();
obj.getVal();
obj.add();
obj.display();
}
}

Sample Output

Java User defined Package - Call another Package's Class

Enter value of 'a' :


113
Enter value of 'b' :
148

The Sum is : 261

1
0

Program 27
A. Single Inheritance in Java
Inherit_Single.java
public class Inherit_Single {
protected String str;
Inherit_Single() {
str = "Java ";
}
}

class SubClass extends Inherit_Single {


SubClass() {
str = str.concat("World !!!");
}
void display()
{
System.out.println(str);
}
}

class MainClass {
public static void main (String args[]){
SubClass obj = new SubClass();
obj.display();
}
}
Sample Output

Java World !!!

1
0

B. Multi-level Inheritance in Java


Inherit_Multilevel.java
public class Inherit_Multilevel {

protected String str;

Inherit_Multilevel() {

str = "J";
}
}

class SubClass1 extends Inherit_Multilevel {

SubClass1() {

str = str.concat("A");
}
}

class SubClass2 extends SubClass1 {

SubClass2() {

str = str.concat("V");
}
}

class SubClass3 extends SubClass2 {

SubClass3() {

str = str.concat("A");
}

void display() {

1
0

System.out.println(str);
}
}

class MainClass {

public static void main(String args[]) {

SubClass3 obj = new SubClass3();

obj.display();
}
}
Sample Output

JAVA

1
0

C. Multiple Inheritance in Java

Inherit_Multiple.java
public interface Inherit_Multiple {

String str1 = "This ";


}

interface Interface2 {

String str2 = "is ";


}

interface Interface3 {

String str3 = "Java ";


}

interface Interface4 {

String str4 = "World !!!";


}

class SubClass implements Inherit_Multiple, Interface2, Interface3, Interface4 {

String str;

SubClass() {

str = str1.concat(str2).concat(str3).concat(str4);
}

void display() {

System.out.println(str);
}
}

1
0

class MainClass {

public static void main(String args[]) {

SubClass obj = new SubClass();

obj.display();
}
}
Sample Output

This is Java World !!!

1
0

Program 28
A. Simple Exception in Java

Try..Catch
try {

// Protected Mode..
} catch (error) {

// Error Catching Mode..


}
Exception_Ex1.java
public class Exception_Ex1 {

public static void main(String args[]) {

int[] array = {1, 2};

try {

System.out.println("The 10th value of Array is : " +


array[10]);
}

1
0

catch (Exception e) {

System.out.println("The Error : " + e);


}
}
}
Sample Output

The Error : java.lang.ArrayIndexOutOfBoundsException: 10

B. Multi Catch in Java

Try..Catch..Catch..Catch..
try {

// Protected Mode..
} catch (error-1) {

// Error Catching Mode - 1 ..


} catch (error-2) {

// Error Catching Mode - 2 ..


} catch (error-3) {

// Error Catching Mode - 3 ..


}
Exception_Ex2.java
public class Exception_Ex2 {

public static void main (String args[]) {

1
0

int array[] = {20,10,30};


int num1 = 15, num2 = 0;
int sum = 0;

try
{
sum = num1 / num2;
System.out.println("The result is : " + sum);

for(int i =0; i <10; i++)


{
System.out.println("The value of array are"
+array[i]);
}

}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Error 1 : " + e);
}

catch (ArithmeticException e)
{
System.out.println ("Error 2 : " + e);
}
}
}
Sample Output

Error 2 : java.lang.ArithmeticException: / by zero


Change it into try block as below :
try
{

for(int i =0; i <10; i++)


{

1
0

System.out.println("The value of array are" +array[i]);


}

sum = num1 / num2;


System.out.println("The result is : " + sum);

}
Sample Output

The value of array are20


The value of array are10
The value of array are30
Error 1 : java.lang.ArrayIndexOutOfBoundsException: 3

C. Create your Own Exception in Java

OwnException.java
public class OwnException extends Exception {

public OwnException(int msg) {

super(String.valueOf(msg));
}

public OwnException(float msg) {

super(String.valueOf(msg));
}

public OwnException(char msg) {

super(String.valueOf(msg));
}

1
0

public OwnException(String msg) {

super(msg);
}
}

class MainClass {

public static void intFn() throws OwnException {

System.out.println("Throwing OwnException from intFn()");


throw new OwnException(10);
}

public static void floatFn() throws OwnException {

System.out.println("Throwing OwnException from floatFn()");


throw new OwnException((float) 111.111);
}

public static void charFn() throws OwnException {

System.out.println("Throwing OwnException from charFn()");


throw new OwnException('A');
}

public static void StringFn() throws OwnException {

System.out.println("Throwing OwnException from StringFn()");


throw new OwnException("Java World..");
}

public static void main(String[] args) {

try {
intFn();
}
catch (OwnException e) {

1
0

e.printStackTrace();
}

try {
floatFn();
}
catch (OwnException e) {
e.printStackTrace();
}

try {
charFn();
}
catch (OwnException e) {
e.printStackTrace();
}

try {
StringFn();
}
catch (OwnException e) {
e.printStackTrace();
}
}
}
Sample Output

Throwing OwnException from intFn()


Throwing OwnException from floatFn()
Throwing OwnException from charFn()
Throwing OwnException from StringFn()
OwnException: 10
at MainClass.intFn(OwnException.java:30)
at MainClass.main(OwnException.java:54)
OwnException: 111.111
at MainClass.floatFn(OwnException.java:36)
at MainClass.main(OwnException.java:61)

1
0

OwnException: A
at MainClass.charFn(OwnException.java:42)
at MainClass.main(OwnException.java:68)
OwnException: Java World..
at MainClass.StringFn(OwnException.java:48)
at MainClass.main(OwnException.java:75)

D. Finally Block in Java

FinallyMethod.java
public class FinallyMethod {

public static void main(String args[]) {

try {

System.out.println("The Value :");

for(int i=1; i<=3; i++) {

System.out.println(i);
}
}
catch(Exception e) {
e.printStackTrace();

1
0

}
finally {
System.out.println("The finally block always executes..");
}
}
}

Sample Output

The Value :
1
2
3
The finally block always executes..

1
0

Program 29
A. Create a Simple Thread in Java

Thread_Ex1.java
public class Thread_Ex1 extends Thread{

String text = null;

Thread_Ex1(String str) {

text = str;
start();
}

public void run() {

System.out.println(text);
}
}

class MainClass {

public static void main(String args[]) {

new Thread_Ex1("Thread Activity Started..");


}
}
Sample Output

Thread Activity Started..

B. Create a Runnable Thread in Java

1
0

Thread_Ex2.java
public class Thread_Ex2 implements Runnable{

String text = null;


Thread thread;

Thread_Ex2(String str) {

text = str;
thread = new Thread(this);
thread.start();
}

public void run() {

System.out.println(text);
}
}

class MainClass {

public static void main(String args[]) {

new Thread_Ex2("Thread Activity Started..");


}
}
Sample Output

Thread Activity Started..

C. join() & isAlive() using Thread in Java

1
0

Thread_Ex3.java
public class Thread_Ex3 extends Thread{

String text = null;


int count;

Thread_Ex3(String str) {

super(str);
count = 0;
start();
}

public void run() {

while(count < 3) {

System.out.println(getName() + " - count : " + count);


count ++;

try {

Thread.sleep(250);
}
catch (InterruptedException e) {

e.printStackTrace();
}
}
}
}

class MainClass {

public static void main(String args[]) {

Thread_Ex3 obj1 = new Thread_Ex3("Thread A");

1
0

Thread_Ex3 obj2 = new Thread_Ex3("Thread B");

try {

obj1.join();

if (!obj1.isAlive())
System.out.println("Thread A not alive.");

obj2.join();

if (!obj2.isAlive())
System.out.println("Thread B not alive.");
} catch (Exception e) { }

System.out.println("Exit from Main Thread.");


}
}
Sample Output

Thread A - count : 0
Thread B - count : 0
Thread A - count : 1
Thread B - count : 1
Thread A - count : 2
Thread B - count : 2
Thread A not alive.
Thread B not alive.
Exit from Main Thread.

D. Call sleep() using Thread in Java

Thread_Ex4.java

1
0

import java.util.Date;

public class Thread_Ex4 {

int wait = 0;

Date dt;

void ThreadActivity() {

dt = new Date();
System.out.println("Before Threading");
System.out.println(dt.getHours() + " : "
+ dt.getMinutes() + " : "
+ dt.getSeconds());

try {
while(wait <= 100) {
Thread.sleep(100);
wait ++;
}
}
catch (Exception e) {

1
0

System.out.println("Error : " + e.toString());


}
finally {

dt = new Date();
System.out.println("\nAfter Threading");
System.out.println(dt.getHours() + " : "
+ dt.getMinutes() + " : "
+ dt.getSeconds());
}
}
}
class MainClass {
public static void main(String args[]) {
Thread_Ex4 obj = new Thread_Ex4();
obj.ThreadActivity();
}
}

Sample Output

Before Threading
14 : 33 : 12

After Threading
14 : 33 : 22

1
0

Program 30
A. Basic Java Applet
BasicAppletExample.java
/*
Basic Java Applet Example
This Java example shows how to create a basic applet using Java Applet class.
*/
import java.applet.Applet;
import java.awt.Graphics;
/*
<applet code = "BasicAppletExample" width = 200 height = 200>
</applet>
*/
public class BasicAppletExample extends Applet{
public void paint(Graphics g){
//write text using drawString method of Graphics class
g.drawString("This is my First Applet",20,100);
}
}

B. Set Status Message in Applet Window


SetStatusMessageExample.java
/*
Set Status Message in Applet Window Example
This java example shows how to set a status message of an applet window
using showStatus method of an Applet class.
*/

/*
<applet code="SetStatusMessageExample" width=200 height=200>
</applet>
*/

1
0

import java.applet.Applet;
import java.awt.Graphics;

public class SetStatusMessageExample extends Applet{


public void paint(Graphics g){
/*
* Show status message in an Applet window using
* void showStatus(String msg) method of an applet class.
*/
//this will be displayed inside an applet
g.drawString("Show Status Example", 50, 50);
//this will be displayed in a status bar of an applet window
showStatus("This is a status message of an applet window");
}
}

1
0

You might also like