Java Lab Manual

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 69

STATE BOARD OF TECHNICAL EDUCATION, HYDERABAD

JAVA PROGRAMMING

Lab Manual for the Academic Year 2015-16

VI -DCME

NAME______________________________________________
PIN _____________________YEAR___________________

PRATAP POLYTECHNIC
(Sponsored by Pratap Educational Society(Regd.) chirala-523155)
(Approved by State Govt. & AICTE New Delhi.)
Papayapalem(P.O), Perala(S.O), Ramapuram Village.CHIRALA-523157

CERTIFICATE
Certified that this is a bonafied Record of
Practical Work done
in this Laboratory by
Mr./Miss._______________________
_____________________________________________
In the course in PRATAP POLYTECHNIC,CHIRALA
during the year 2015-2016.

Number of
Experiments

Lab in-charge
Head of the Department

GUIDELINES TO STUDENTS:
1

Equipment in the lab for the use of student community. Students need to maintain a
proper decorum in the computer lab. Students must use the equipment with care. Any
damage is caused is punishable.

Students are required to carry their observation / programs book with completed
exercises while entering the lab.

Students are supposed to occupy the machines allotted to them and are not supposed to
talk or make noise in the lab. The allocation is put up on the lab notice board.

Lab can be used in free time / lunch hours by the students who need to use the systems
should take prior permission from the lab in-charge.

Lab records need to be submitted on or before date of submission.

Students are not supposed to use pen drives/memory cards

INDEX
SNO NAME OF THE EXPERIMENT
1

PAGENO

DATE

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

SNO NAME OF THE EXPERIMENT


22

PAGENO

DATE

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

Java History:
Java is a general-purpose; object oriented programming language developed by
Sun Microsystems of USA in 1991. Originally called oak by James Gosling, one of the
inventors if the language. This goal had a strong impact on the development team to make the
language simple, portable, highly reliable and powerful language.
Java also adds some new features. While C++ is a superset of C. Java is neither a
superset nor a subset of C or C++.

C++
C

Java

Data Types
-------------------------------------------------------------------------------Objectives
Having read this section you should be able to:
declare (name) a local variable as being one of C's five data types
initialise local variables
perform simple arithmetic using local variables
-------------------------------------------------------------------------------There are five basic data types associated with variables:
int - integer: a whole number.
float - floating point value: ie a number with a fractional part.
double - a double-precision floating point value.
char - a single character.
void - valueless special purpose type which we will examine closely in later sections.
One of the confusing things about the C language is that the range of values and the amount of
storage that each of these types takes is not defined. This is because in each case the 'natural'
choice is made for each type of machine. You can call variables what you like, although it helps
if you give them sensible names that give you a hint of what they're being used for - names like
sum, total, average and so on. If you are translating a formula then use variable names that
reflect the elements used in the formula. For example, 2pr (that should read as "2 pi r" but that

depends upon how your browser has been set-up) would give local variables names of pi and r.
Remember, C programmers tend to prefer short names!
Note: all C's variables must begin with a letter or a "_" (underscore) character.
DATA TYPES IN JAVA

Primitive
(intrinsic)

Non-Primitive
(Derived)

Numeric

Integer

Class

Non-Numeric

Floating-point

Character

Arrays

Boolean

Interface
Integer

Byte

Short

Int

Floating point

Long
Float

Double

--------------------------------------------------------------------------------

Integer Number Variables


The first type of variable we need to know about is of class type int - short for integer. An int
variable can store a value in the range -32768 to +32767. You can think of it as a largish
positive or negative whole number: no fractional part is allowed. To declare an int you use the
instruction:
int variable name;
For example:
int a;
declares that you want to create an int variable called a.
To assign a value to our integer variable we would use the following C statement:

a=10;
The C programming language uses the "=" character for assignment. A statement of the form
a=10; should be interpreted as take the numerical value 10 and store it in a memory location
associated with the integer variable a. The "=" character should not be seen as an equality
otherwise writing statements of the form:
a=a+10;
will get mathematicians blowing fuses! This statement should be interpreted as take the current
value stored in a memory location associated with the integer variable a; add the numerical
value 10 to it and then replace this value in the memory location associated with a.
--------------------------------------------------------------------------------

Decimal Number Variables


As described above, an integer variable has no fractional part. Integer variables tend to be used
for counting, whereas real numbers are used in arithmetic. C uses one of two keywords to
declare a variable that is to be associated with a decimal number: float and double. They are
each offer a different level of precision as outlined below.
float
A float, or floating point, number has about seven digits of precision and a range of about 1.E36 to 1.E+36. A float takes four bytes to store.
double
A double, or double precision, number has about 13 digits of precision and a range of about 1.E303 to 1.E+303. A double takes eight bytes to store.
For example:
float total;
double sum;
To assign a numerical value to our floating point and double precision variables we would use
the following C statement:
total=0.0;
sum=12.50;
--------------------------------------------------------------------------------

Character Variables
C only has a concept of numbers and characters. It very often comes as a surprise to some
programmers who learnt a beginner's language such as BASIC that C has no understanding of
strings but a string is only an array of characters and C does have a concept of arrays which we
shall be meeting later in this course.
To declare a variable of type character we use the keyword char. - A single character stored in
one byte.
For example:
char c;
To assign, or store, a character value in a char data type is easy - a character variable is just a
symbol enclosed by single quotes. For example, if c is a char variable you can store the letter A
in it using the following C statement:
c='A'
Notice that you can only store a single character in a char variable. Later we will be discussing
using character strings, which has a very real potential for confusion because a string constant is

written between double quotes. But for the moment remember that a char variable is 'A' and not
"A".

Assignment Statement
Once you've declared a variable you can use it, but not until it has been declared - attempts to
use a variable that has not been defined will cause a compiler error. Using a variable means
storing something in it. You can store a value in a variable using:
name = value;
For example:
a=10;
stores the value 10 in the int variable a. What could be simpler? Not much, but it isn't actually
very useful! Who wants to store a known value like 10 in a variable so you can use it later? It is
10, always was 10 and always will be 10. What makes variables useful is that you can use them
to store the result of some arithmetic.
Consider four very simple mathematical operations: add, subtract, multiply and divide. Let us
see how C would use these operations on two float variables a and b.
add
a+b
subtract
a-b
multiply
a*b
divide
a/b
Note that we have used the following characters from C's character set:
+ for add
- for subtract
* for multiply
/ for divide
BE CAREFUL WITH ARITHMETIC!!! What is the answer to this simple calculation?
a=10/3
The answer depends upon how a was declared. If it was declared as type int the answer will be
3; if a is of type float then the answer will be 3.333. It is left as an exercise to the reader to find
out the answer for a of type char.
Two points to note from the above calculation:
C ignores fractions when doing integer division!
when doing float calculations integers will be converted into float. We will see later how C
handles type conversions.
--------------------------------------------------------------------------------

Arithmetic Ordering
Whilst we are dealing with arithmetic we want to remind you about something that everyone
learns at junior school but then we forget it. Consider the following calculation:
a=10.0 + 2.0 * 5.0 - 6.0 / 2.0
What is the answer? If you think its 27 go to the bottom of the class! Perhaps you got that
answer by following each instruction as if it was being typed into a calculator. A computer
doesn't work like that and it has its own set of rules when performing an arithmetic calculation.
All mathematical operations form a hierarchy which is shown here. In the above calculation the
multiplication and division parts will be evaluated first and then the addition and subtraction
parts. This gives an answer of 17.
Note: To avoid confusion use brackets. The following are two different calculations:
a=10.0 + (2.0 * 5.0) - (6.0 / 2.0)

a=(10.0 + 2.0) * (5.0 - 6.0) / 2.0


You can freely mix int, float and double variables in expressions. In nearly all cases the lower
precision values are converted to the highest precision values used in the expression. For
example, the expression f*i, where f is a float and i is an int, is evaluated by converting the int
to a float and then multiplying. The final result is, of course, a float but this may be assigned to
another data type and the conversion will be made automatically. If you assign to a lower
precision type then the value is truncated and not rounded. In other words, in nearly all cases
you can ignore the problems of converting between types.

Process of building and running java application programs:


Text Editor

Java Source
Code

Javadoc

HTML
files

Javac

Java Class
File

Java (only file name)

Javah

Header
Files

Jdb (database)

Java
progra
m
Output
The way these tools are applied to build and run application programs is create a program. We
need create a source code file using a text editor. The source code is then compiled using the
java compiler javac and executed using the java interpreter java. The java debugger jdb is used
to find errors. A complied java program can be converted into a source code.

ARRAYS, STRINGS AND STRINGBUFFERS


Arrays are used to stroe large number data of same data types. which are grouped together and
called by a common name.These are called elements of the array. Arrays can store both
primitive data types and objects.but they must be of same type.These elements are stored in
contiguous memory locations. Arrays are ordered in the sense that each element is indexed.
starting from 0 and can be retreived based on the indexed value.Arrays in java unlike in C are
objects, and are of fixed size.
STRINGS
A String is a series of characters enclosed in double quotes and is treated as a single unit.Unlike
c/c++ string in java is an object from class string.A string in java does not terminate with a null
character(\o).A string may be assigned in declaration to a string reference.The declaration String
age="old"; initializes a String reference age to refer to the anonymous string object "old".
String Concatenation
String can be concatenated with + operator.
String concatenation using string references
public class StringConcatenation {
public static void main(String args[]){
String first_name="Nagesh";
String last_name="Rao";
String sir_name = "Sure";
String concat1=sir_name+first_name+last_name;
String concat2= sir_name+"'+first_name+""+last_name;
System.out.println(concat1);
System.out.println(concat1);
System.out.println(concat2);
}
}
OUTPUT:
SureNegeshRao
Sure Negesh Rao
The length(size) of a string can be found with the string method length().Two string can be
compared with equals() method, if both strings are same, the method returns a boolean value of
true and if not false. In equals() method the case ( upper or lower) of the letters will be taken
into consideration and if case is not a matter, th method equalsIgnoreCase() may be used. The
operator. == is used to compare two objects references to see if they refer the same instance.
using equals(), equalsIgnoreCase() and to see the differece between the usage of equals and()
and ==
public class StringComparision{
public static void main(String args[]) {
String s1 = "java"
String s2 = "java"
String s3 = "java"
String s4 = s1;
System.out.println("Length of the string s1= "+s1.lenght());
System.out.println("s1(java)equals s2(java):"+ s1.equals(s2));
System.out.println("s1(java) equalsIgnoreCaseS2(java):+s1.equalsignoreCase(s2));
System.out.println("s1(java) == s2(java):" + s1==s2);

10

System.out.println("s2(java) == s3(java):" +s2== s3);


System.out.println("s1(java)==s4(java):" + s1==s4);
}
}
OUTPUT:
Length of the String s1 =4
s1(java) equals s2(java): false
s1(java)equalsignorecases2(java):true
s1(java)==s2(java):false
s2(java)==s3(java): false
s1(java)== s4(java): false
The method compareTo() can also be used to compare two string but comparision is done
lexographically(that is letter by letter in a dictionary order(). Method compareTo() returns 0 if
both strings are equal, a negative number if the string that invokes compareTo is less than the
string that is passed an an argument and a positive number if the string that invokes compareTo
is greater than the string that is passed as an argument.A part of a string can be copied with the
method substring() method.
STRINGBUFFERS Class:
Once a String object is created, its contents can never be changed. That is to say Strings are
immutable and if tried to change a nbew reference is created.This can be overcome by using the
objects of class StringBuffer. With StringBuffer strings can be manipulated dynamically. String
objects are constant strings and StringBuffer objects are modifiable strings.
Program on finding the length and capacity of a StringBuffer object.
Public class LengthCapacity {
Public static void main(String args[]){
StringBuffer sb1 = new StringBuffer();
StringBuffer sb2 = new StringBuffer(ObjectOne);
System.out.println(Length of sb1 = +sb.lenth());
System.out.println(Length of sb2 = sb2.lenght());
System.out.println(Capacity of sb1 = sb1.capacity());
System.out.println(Capacity of sb2 = sb2.capacity());
}
}
OUTPUT
Length of sb1 = 0
Length of sb2 = 9
Capacity of sb1 = 16
Capacity of sb2 = 25

11

MULTITHREADING
Multithreading allows two parts of the same program to run concurrently. This article discusses
how to pull off this performance-improving feat in Java. It is excerpted from chapter 10 of the
book Java Demystified, written by Jim Keogh (McGraw-Hill/Osborne, 2004; ISBN:
0072254548
Multitasking is performing two or more tasks at the same time. Nearly all operating systems are
capable of multitasking by using one of two multitasking techniques: process-based
multitasking and thread-based multitasking.
Process-based multitasking is running two programs concurrently. Programmers refer to a
program as a process. Therefore, you could say that process-based multitasking is programbased multitasking.
Thread-based multitasking is having a program perform two tasks at the same time. For
example, a word processing program can check the spelling of words in a document while you
write the document. This is thread-based multitasking.
A good way to remember the difference between process-based multitasking and thread-based
multitasking is to think of process-based as working with multiple programs and thread-based
as working with parts of one program.
Main thread
______________
______________
___________

Thread A
_________
_________
_________
_________

Thread B
_________
_________
_________
_________

Thread C
_________
_________
_________
_________

The objective of multitasking is to utilize the idle time of the CPU. Think of the CPU as the
engine of your car. Your engine keeps running regardless of whether the car is moving. Your
objective is to keep your car moving as much as possible so you can get the most miles from a
gallon of gas. An idling engine wastes gas.
The same concept applies to the CPU in your computer. You want your CPU cycles to be
processing instructions and data rather than waiting for something to process. A CPU cycle is
somewhat similar to your engine running.
It may be hard to believe, but the CPU idles more than it processes in many desktop computers.
Lets say that you are using a word processor to write a document. For the most part, the CPU is
idle until you enter a character from the keyboard or move the mouse. Multitasking is designed

12

to use the fraction of a second between strokes to process instructions from either another
program or from a different part of the same program.
Making efficient use of the CPU may not be too critical for applications running on a desktop
computer because most of us rarely need to run concurrent programs or run parts of the same
program at the same time. However, programs that run in a networked environment, such as
those that process transactions from many computers, need to make a CPUs idle time
productive.

LIFE CYCLE OF A THREAD:


New born state:
We created a thread object, the thread is born and is said to be in newborn
state. The thread is not yet scheduled for running.
Schedule it for running using start() method.
Kill it using stop() method.

Runnable state:
The runnable state means that the thread is ready for execution and is
waiting for the availability of the processor. That is, the thread has joined the queue of
threads that are waiting for execution. If all threads have equal priority, then they are given
time slots for execution in round robin, first-come, first-serve manner.
If we want a thread to relinquish control to another thread of equal priority before its turn
comes, we can do so by using the yield() method.

New thread

Newborn
stop
start

Active
Thread

stop

Running

Runnable

Dead
Killed Thread

yield

Suspend
sleep wait

Idle Thread
(not Runnable)

Resume
notify

stop

Blocked

Running state:
Running means that the processor has given its time to the thread for its
execution. The thread runs until it relinquishes control on its own or it is preempted by a higher
priority thread.
Suspend () method:

13

A suspended thread can be revived by using the resume () method. This


approach is useful when we want to suspend a thread for some time due to certain reason, but
do not want to kill it.
Sleep() method:
We can put a thread to sleep for a specified time period using the method sleep
(time) where time is in milliseconds. This means that the thread is out of the queue during this
time period.the thread re-enters the runnable state as soon as this time period is elapsed.
Notify () method:
It has been told to wait until some event occurs. This is done using the
wait () method. The thread can be scheduled to run again using the notify () method.

Blocked state:
A thread is said to be blocked when it is prevented from entering into the
runnable state and subsequently the running state. This happens when the thread is suspended,
sleeping , or waiting in order to satisfy certain requirements. A blocked thread is considered
not runnable but not dead and therefore fully qualified to run again.
Dead state:
Every thread has a life cycle. A running thread ends its life when is has
completed executing its run() method. We can kill it by sending the stop message to it at any
state thus causing a premature death to it. A thread can be killed as soon it is born, or while it is
running, or even when it is in not runnable (blocked) condition.

EXCEPTION HANDLING
Exceptions :
Exceptions are part of the inheritance hierarchy and are derived from the Throwable
class.That is an exception is an instance of the
Throwable class.
Error: This class describes internal errors,such as out of disk space etc.The user can only be
informed about such errors and so objects of these cannot be thrown.
Exceptions Two classes shown above are derived from this class
Run Time Exception Exceptions that inherit from this class include
a bad cast.
out of bound array access
a null pointer acess.
These problems arise out of wrong programming logic and must be corrected by the
programmer himself. Some of these exceptions are
Arithmetic Exception
NullPointer Exception
ClassCast Exception
ArrayIndexOutBounds Exception.
Other exceptions :These include exceptions for multithreading, malformed URL,reading past
end of file etc.
Some of the subclasses:
IOException

14

AWTException
ClassNotFoundException
IllegalAcessException
Throwing Exceptions
A method tha returns a value can also be made to throw an exception.
What is exception handling?
An exception signifies an illegal, invalid or unexcected, issue during program execution. Since
exceptions are always assumed to be anticipated., you need to provide appropriate exception
handling
What are the keywords that are frequently used in exception handling?
The important keywords of exception handling are try and catch and they are not methods, but
generally termed as try block and catch block and in these blocks we write the handling code.
As usual each block contains statements delimeted by braces ({}).The statements that are
suspected to raise the exceptions ae written in try block and the statements to handle the
situation when the try block statements raises an exception are written in catch block(like
catch(ArithmeticException ae)
Example:
Public class Arrayindex{
Public static void main(String args[]) {
Int marks[]={10,20,30,40,50}
Try{
System.out.println(marks[10]);
}
Catch(ArrayIndexOutOfBoundsException ai) {
System.out.println(Hello! Exceptions is caught by me +ai);
}
Finally {
System.out.println(This executes irrespective of raising of an exception);
}
System.out.println(marks[4]=+marks[4]);
}
}
Multiple catch Blocks
In some cases a method may have to catch different types of exceptions. Java supports multiple
catch blocks, that is a single try block can contain any number of catch blocks. A precation to be
observed is each block must specify a different type of exception.
Public class MultipleCatch {
Public static void main(String args[]) {
Int a=8, b=0, c, d, marks[]={10,20,30,40,50};
Try
C= a/b;
System.out.println(a/b = +c);
d=marks[10];
System.out.println(marks[10]=+d);
}
Catch(ArrayIndexOutBoundException aie){
System.out.println(Exception caught by me is +aie);

15

}
Catch(ArithmeticException e) {
Syetem.out.println(Excepion caught by me is +e);
}
Catch(Exception e) {
System.out.pritnln(From Exception :+e);
}
}
}

APPLETS
An applet is a program written in the Java programming language that can be included in an
HTML page, much in the same way an image is included in a page. When you use a Java
technology-enabled browser to view a page that contains an applet, the applet's code is
transferred to your system and executed by the browser's Java Virtual Machine (JVM). For
information and examples on how to include an applet in an HTML page, refer to this
description of the <APPLET> tag.
Java Plug-in software enables enterprise customers to direct applets or beans written in the Java
programming language on their intranet web pages to run using Sun's Java Runtime
Environment (JRE), instead of the browser's default. This enables an enterprise to deploy
applets that take full advantage of the latest capabilites and features of the Java platform and be
assured that they will run reliably and consistently.

APPLET LIFE CYCLE:


Initialization state:
Applet enters the initialization state when it is first loaded. This is
achieved by calling the init() method of Applet class.
Create objects needed by the applet.
Set up initial values.
Load images or fonts.
Set up colors.
Running state:
Applet enters the running state when the system calls the start() method
of Applet class. This occurs automatically after the applet is initialized. Starting can also occur
if the applet is already in stopped (idle) state.
Idle or Stopped State:
An applet becomes idle when it is stopped from running. Stopping occurs
automatically when we leave the page containing the currently running applet. We can calling
the stop () method explicitly.
Dead State:
An applet is said to be dead when it is removed from memory. This
occurs automatically by invoking the destroy() method when we quit the browser.
Display State:
Applet moves to the display state whenever it has to perform some output
operation on the screen. This happens immediately after the applet enters into the running state.

16

Begin
(load Applet)

Born

initialization

Start()
Stop()
Running

Display

Idle
Start()

stopped

Paint()
Destroy()

Destroyed

Dead

Exit of Browser

Applet state transition diagram

17

1. Experiment no .1 : Write a Program to find Simple Interest.


1. AIM:
Write a java program to find the simple interest.
2. Algorithm:
1.
2.
3.
4.
5.
6.

Start the program.


Declare the variables and assume values
InterestTopay=principle*time*rate/100;
print the values.
End of class and main method.
stop the program.

3. PROGRAM:
import java.io.*;
import java.lang.*;
class Simpleinterest
{
public static void main(String args[])
{
int principle=25000;
float rate = 12.5f;
double interestToPay,time = 2.75;
interestToPay=principle*time*rate/100;
System.out.println("Principle amount is Rs."+principle+ "interest=Rs."+interestToPay);
System.out.println ("Total amount to pay to clear the loan = Rs."+(principle+interestToPay));
}
}
4. OUTPUT:
Principle amount is Rs.25000 interest = Rs.8593.75
Total amount to pay to clear the loan = Rs.33593.75

18

2. Experiment no .2 : Program To Find The Arthematic Operations


1. AIM:
Write a java program to find the given numbers of arithmetic operations.
2. Algorithm:
1. Start the program.
2. Declare the variables a and b.
3. Read a string with inputstreamReader(System.in).
4. convert the string into Integer.parseInt(stdin.readLine());
5. Given variables addition, subtraction, multiplication, division.
6. End of class and main method.
7. stop the program.
3. PROGRAM:
import java.io.*;
class arthematic
{
public static void main(String s[]) throws IOException
{
int a,b,add,sub,mul,div;
DataInputStream stdin=new DataInputStream(System.in);
System.out.println("Enter First Number:");
a=Integer.parseInt(stdin.readLine());
System.out.println("Enter Second Number:");
b=Integer.parseInt(stdin.readLine());
add=a+b;
sub=a-b;
mul=a*b;
div=a/b;
System.out.println("Addition of a and b = "+add);
System.out.println("Subtraction of a and b = "+sub);
System.out.println("Multiplication of a and b = "+mul);
System.out.println("Division of a and b = "+div);
}
}

4. OUTPUT:
Enter first number: 5
Enter second number: 3
Addition of a and b = 8
Subtraction of a and b=2
Multiplication of a and b=15
Division of a and b=1.0

19

3. Experiment no .3 : Program To Find The Single Digit Number


1. AIM:
Write a java program to find the given single digit number using switch case.
2. Algorithm:
1. Start the program.
2. Read a string with inputstreamReader(System.in).
3. convert the string into Integer.parseInt(stdin.readLine());
4. By using switch case ( multi way decision statement) when a match is found,
that case is executed.
5. Default it is a break statement exit the switch statement.
6. Stop the program.
4. PROGRAM:
import java.io.*;
class digit
{
public static void main(String s[]) throws IOException
{
int n;
DataInputStream stdin=new DataInputStream(System.in);
System.out.println("Enter Any positive single digit number :");
n=Integer.parseInt(stdin.readLine());
switch(n)
{
case 0:
System.out.println("Zero");
break;
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
case 4:
System.out.println("Four");
break;
case 5:
System.out.println("Five");
break;
case 6:
System.out.println("Six");
break;
case 7:

20

System.out.println("Seven");
break;
case 8:
System.out.println("Eight");
break;
case 9:
System.out.println("Nine");
break;
default:
System.out.println("Invalid Number");
break;
}
}
}

4. OUTPUT:
Enter any positive single digit number: 6
Six
Enter any positive single digit number: 5
Five

21

4. Experiment no .4 : Program To Find The Factorial Of A Number


1. AIM:
Write a java program to find the given factorial numbers.
2. Algorithm:
1. Start the program. Import the packages.
2. Read a string with inputstreamReader(System.in).
3. convert the string into Integer.parseInt(stdin.readLine());
4. By using for loop rotating the integer value.
5. Repeat enter the value until end of loop.
6. End of class and main method.
7. stop the program.
3. PROGRAM:
import java.io.*;
//importing io package
import java.lang.*;
//importing lang package
class Factorial
{
public static void main(String args[]) throws IOException
{
int i,n,f=1;
System.out.println("Enter the numbert you want to calculate the factorial");
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
n=Integer.parseInt(stdin.readLine());
for(i=1;i<=n;i++)
{
f=f*i;
}
System.out.println("The factorial of " + n + " is " + f);
}
//End of main
}
//End of class Factorial

4. OUTPUT
Enter the number for which you want the factorial 4
The factorial of 4 is 24
Enter the number for which you want the factorial 3
The factorial of 3 is 6
Enter the number for which you want the factorial 6
The factorial of 6 is 120

22

5. Experiment no. 5: Program to check whether the first number is a multiple


of second number.
1. AIM:
To check whether the first number is a multiple of second number.
2. Algorithm:
1. Start the program, import the packages.
2. Create a class and variables with data types.
3. Read a string with inputstreamReader(System.in).
4. convert the string into Integer.parseInt(stdin.readLine());
5. By using ifelse loop rotating the string.
6. Print the concatenation of arrays.
7. Stop the program.
3. PROGRAM:
import java.io.*;
//Importing io package
class Multiple
{
public static void main(String args[]) throws IOException
{
int m,n;
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the first number" );
m=Integer.parseInt(stdin.readLine());
System.out.println("Enter the second number ");
n=Integer.parseInt(stdin.readLine());
if ( m%n==0)
{
System.out.println("The first number is the multiple of second number" );
}
else
{
System.out.println("The first number is not the multiple of second number" );
}
}
//End of main
}
//End of class Multiple

4. OUTPUT
Enter the first number 10
Enter the second number 5
The first number is the multiple of second number
Enter the first number 2
Enter the second number 3
The first number is not the multiple of second number

23

6. Experiment no. 6: Program to check the given array is sorting order


1. AIM:
Write a java program to check given numbers in a sorting order.
2. Algorithm:
1.
2.
3.
4.
5.
6.
7.

Start the program.


Create a class and variables with data types.
Read a string with DatainputstreamReader(System.in).
convert the string into Integer.parseInt(stdin.readLine());
By using for loop rotating the array.
Print the concatenation of arrays.
Stop the program.

3. PROGRAM:
import java.io.*;
class sorting
{
public static void main(String s[]) throws IOException
{
int a[]=new int[10];
int i,j;
DataInputStream stdin=new DataInputStream(System.in);
System.out.println("Enter 10 Elements into Array");
for(i=0;i<10;i++)
a[i]=Integer.parseInt(stdin.readLine());
for(i=0;i<9;i++)
for(j=0;j<9-i;j++)
{
if (a[j+1]<a[j])
{
int temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
System.out.println("Required Order is ");
for(i=0;i<10;i++)
System.out.println(a[i]);
}
}

4. OUTPUT:
Enter 10 elements into Array:10 9 8 7 6 5 4 3 2 1
Required order is:1 2 3 4 5 6 7 8 9 10

24

7. Experiment no. 7: Program To generate the ARMSTRONG number


1. AIM:
Write a java program to generate the Armstrong number.
2. Algorithm:
1. Start the program.
2. Read a string with DatainputstreamReader(System.in).
3. convert the string into Integer.parseInt(stdin.readLine());
4. sum=sum+r*r*r formula.
5. Using if else statement.
6. Stop the program.
3. PROGRAM:
import java.io.*;
class armstrong
{
public static void main(String s[]) throws IOException
{
int n,r,temp,sum;
DataInputStream stdin=new DataInputStream(System.in);
System.out.println("Enter any Positive Integer Number :");
n=Integer.parseInt(stdin.readLine());
temp=n;
sum=0;
while(temp>0)
{
r=temp % 10;
sum=sum+r*r*r;
temp=temp/10;
}
if (n==sum)
System.out.println("Given Number is Armstrong Number");
else
System.out.println("Given Number is not Armstrong Number");
}
}

4. OUTPUT:
Enter any positive Integer number: 153
Given number is Armstrong number.
Enter any positive Integer number: 146
Given number is not Armstrong number.

25

8. Experiment no. 8: Program To generate the Quadratic equation


1. AIM:
Write a java program to generate the quadratic equation.
2. Algorithm:
1. Start the program. Import the packages.
2. Create a class and variables with data types.
3. Declaration of the main class.
4. Read a string with inputstreamReader(System.in).
5. convert the string into Integer.parseInt(stdin.readLine());
6. By using if(d==0) Roots are Equalent loop rotating the integer value.
7. if(d>0) Roots are Real otherwise ("Roots are Imaginary");
8. Repeats enter the value until end of loop.
9. End of class and main method.
10. Stop the program.
3. PROGRAM:
import java.io.*;
import java.math.*;
class quadratic
{
public static void main(String s[]) throws IOException
{
int a,b,c,d;
double r1,r2;
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter value of a:");
a=Integer.parseInt(stdin.readLine());
System.out.println("Enter value of b:");
b=Integer.parseInt(stdin.readLine());
System.out.println("Enter value of c:");
c=Integer.parseInt(stdin.readLine());
d=b*b-4*a*c;
if(d==0)
{
System.out.println("Roots are Equalent");
r1=-b/(2*a);
r2=-b/(2*a);
System.out.println("Root1 = "+r1);
System.out.println("Root2 = "+r2);
}
else if (d>0)
{
System.out.println("Roots are Real");
r1=(-b+Math.sqrt(d))/(2*a);
r2=(-b-Math.sqrt(d))/(2*a);
System.out.println("Root1 = "+r1);

26

System.out.println("Root2 = "+r2);
}
else
System.out.println("Roots are Imaginary");
}

4. OUTPUT:
Enter value of a:1
Enter value of b:2
Enter value of c:1
Roots are Equalent
Enter value of a:2
Enter value of b:3
Enter value of c:2
Roots are Imaginary

27

9. Experiment no. 9: Program to Find The Primary Numbers


1. AIM:
Write a java program to find the given primary numbers.
2. Algorithm:
1. Start the program. Import the packages.
2. Read a string with inputstreamReader(System.in).
3. convert the string into Integer.parseInt(stdin.readLine());
4. By using Nested for() loop rotating the integer value.
5. Repeat enters the value until end of loop.
6. End of class and main method.
7. stop the program.
3. PROGRAM:
import java.io.*;
class prime
{
public static void main(String s[]) throws IOException
{
int i,j,c,n;
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Positive value :");
n=Integer.parseInt(stdin.readLine());
for (i=1;i<=n;i++)
{
for(j=1,c=0;j<=i;j++)
{
if (i%j==0)
c=c+1;
}
if(c==2)
System.out.println(i);
}
}
}

4. OUTPUT:
Enter positive value:
10
1
2
3
5
7

28

10. Experiment no. 10: Program to generate the Fibonacci series


1. AIM:
Write a java program to generate the Fibonacci series, given number of n
values.
2. Algorithm:
1. Start the program. Import the packages.
2. Create a class and variables with data types.
3. Declaration of the main class.
4. Read a string with inputstreamReader(System.in).
5. convert the string into Integer.parseInt(stdin.readLine());
6. By using for loop rotating the integer value.
7. Repeats enter the value until end of loop.
8. End of class and main method.
9. Stop the program.
3. PROGRAM:
import java.io.*;
//importing io package
import java.lang.*;
//importing Lang package
class A
{
int a,b,c;
A( int f1,int f2 )
{
a=f1;
b=f2;
}
//End of constructor A
void Feb()
{
c=a+b;
System.out.print("\t" + c);
a=b;
b=c;
}
//End of method Feb
}
//End of class A
class Febinocci
{
public static void main(String args[]) throws IOException
{
int n,f3, i;
A a=new A(0,1);
System.out.println("Enter how many numbers you want in febinoci series");
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
n=Integer.parseInt(stdin.readLine());
System.out.println("The febinocci series is as follows");
System.out.print("\t" + 0);
System.out.print("\t" + 1);

29

for(i=0;i<(n-2);i++)
{
a.Feb();
}
//End of for loop
}
//End of main
//End of class Febinocci

4. OUTPUT
Enter how many numbers you want in febinoci series 3
The febinocci series is as follows 0 1 1
Enter how many numbers you want in febinoci series 6
The febinocci series is as follows 0 1 1 2 3 5
Enter how many numbers you want in febinoci series 10
The febinocci series is as follows 0 1 1 2 3 5 8 13

21

34

30

11. Experiment no. 11: Program to generate the sorting order of array
1. AIM:
Write a java program to generate the sorting order of a given number of n values.
2. Algorithm:
1. Start the program. Import the packages.
2. Create a class and variables with data types.
3. Declaration of the main class.
4. Read a string with inputstreamReader(System.in).
5. convert the string into Integer.parseInt(stdin.readLine());
6. By using for loop rotating the integer value.
7. Swapping the values into a temp=a[i];
8. Repeats enter the value until end of loop.
9. End of class and main method.
10.Stop the program.
3. PROGRAM:
import java.io.*;
class sorting
{
public static void main(String s[]) throws IOException
{
int a[]=new int[20];
int i,j,temp;
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter 10 integers into array");
for(i=0;i<10;i++)
a[i]=Integer.parseInt(stdin.readLine());
for(i=0;i<10-1;i++)
{
for(j=0;j<10-i-1;j++)
{
if (a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.println("Required Order is ");
for(i=0;i<10;i++)
System.out.println(a[i]);
}}

4. OUTPUT:
Enter 10 integers in to array:
9876543210
Required order is: 0 1 2 3 4 5 6 7 8 9

31

12. Experiment no. 12: Program to find product, sum and difference of 2 matices
1. AIM:
Write a java program to find the sum of the matrices, product of the
matrices and differences of matrices, by using two dimensional arrays.
2. Algorithm:
1. Start the program, import the packages.
2. Create a class and variables with two dimensional arrays.
3. Read a string with inputstreamReader(System.in).
4. convert the string into Integer.parseInt(stdin.readLine());
5. By using for loop rotating the two dimensional arrays value.
6. Column is i, rows is j declare in two dimensional matrices.
7. Repeats enter the value until end of loop.
8. Print the concatenation of arrays.
9. Stop the program.
3. PROGRAM:
import java.io.*;
//Importing io package
class Matrix
{
public static void main(String args[])
throws IOException
{
int a[][]=new int[3][3];
int b[][]=new int[3][3];
int s[][]=new int[3][3];
int d[][]=new int[3][3];
int p[][]=new int[3][3];
int i,j;
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the elements of 1st matrix");
for( i=0;i<3;i++)
//Reading the elements of first matrix
{
for(j=0;j<3;j++)
{
a[i][j]=Integer.parseInt(stdin.readLine());
}}
System.out.println("Enter the elements of the 2nd matrix");
for(i=0;i<3;i++)
//Reading the elements of second matrix
{
for(j=0;j<3;j++)
{
b[i][j]=Integer.parseInt(stdin.readLine());
}}
for(i=0;i<3;i++)
//Calculating additon and substraction
{
for(j=0;j<3;j++)
{

32

s[i][j]=a[i][j]+b[i][j];
d[i][j]=a[i][j]-b[i][j];
}}
System.out.println("The sum of the matrices is");
for(i=0;i<3;i++)
//Calculating product
{
for(j=0;j<3;j++)
{
System.out.print(" "+s[i][j]);
}
System.out.println();
}
System.out.println("The productof the matrices is");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
p[i][j]=0;
for(int k=0;k<3;k++)
{
p[i][j]=p[i][j]+a[i][k]*b[k][j];
}
System.out.print(" "+p[i][j]);
}
System.out.println();
}
System.out.println("The difference of the matrices is");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(" "+d[i][j]);
}
System.out.println();
}}}

4. OUTPUT
Enter the elements of 1st matrix 1 2 3 4 1 2 3 4 1
Enter the elements of 2nd matrix 2 3 4 5 6 1 2 3 4
The sum of the matrices is
3 5 7
9 7 3
5 7 5
The productof the matrices is
18 24 18
17 24 25
28 36 20
The difference of the matrices is
-1 -1 -1
-1 -5 1
1 1 -3

33

13. Experiment no. 13: Program To implement abstract keyword


1. AIM:
Write a java program to implement the abstract keyword and method
overriding.
2. Algorithm:
1. Start the program.
2. Create a classes and variables with data types.
3. Assigns the values of rectangle and triangle.
4. Create a object of relevant class, to call the procedure.
5. Given a formula of area.
6. Print the concatenation of string.
7. Stop the program.
3. PROGRAM:
abstract class Figure
{
double dim1,dim2;
Figure(double a,double b)
{
dim1=a;
dim2=b;
}
abstract double area();
}
class Rectangle extends Figure
{
Rectangle(double a,double b)
{
super(a,b);
}
double area()
{
return(dim1*dim2);
}
}
class Triangle extends Figure
{
Triangle(double a,double b)
{
super(a,b);
}
double area()
{
return((dim1*dim2)/2);
}

34

}
class Abstract
{
public static void main(String args[])
{
Rectangle r=new Rectangle(5,5);
double ar=r.area();
Triangle t=new Triangle(5,5);
double at=r.area();
System.out.println("area of rectangle " + ar);
System.out.println("area of triangle " + at );
}
}

4. OUTPUT:
area of rectangle 25
area of triangle 12.5*/

35

14. Experiment no. 14: Program to implement constructor OverLoading


1. AIM:
Write a java program to implement the constructor and overloading method
program.
2. Algorithm:
1. Start the program.
2. Create a class and variables with data types.
3. Declare the methods in same name with different parameters.
4. Create a object to call the procedure.
5. Print the concatenation of values.
6. Stop the program.
3. PROGRAM:
class A
{
int a=2,b=3,c=4;
A(int c1)
{
a=c1;
}
A(int c1,int c2)
{
a=c1;
b=c2;
}
A(int c1,int c2,int c3)
{
a=c1;
b=c2;
c=c3;;
}
void show()
{
System.out.println("The value of a is " + a);
System.out.println("The value of b is " + b);
System.out.println("The value of c is " + c);
}
}
class Consover
{
public static void main(String args[])
{
A a=new A(6);
A a2=new A(7,8);
A a1=new A(9,10,11);
a.show();

36

a1.show();
a2.show();
}
}

4. OUTPUT:
The value of a is 6
The value of a is 7
The value of b is 8
The value of a is 9
The value of b is 10
The value of c is 11

37

15. Experiment no. 15: Program To Implement Dynamic(super class) method


dispatch
1. AIM:
Write a java program to implement the super class and sub class method.
2. Algorithm:
1. Start the program.
2. Create a classes and variables with data types.
3. Create a methods void show ().
4. Create an object of relevant class, to call the procedure.
5. Print the concatenation of string.
6. Stop the program.
3. PROGRAM:
import java.io.*;
import java.lang.*;
class A
{
void show()
{
System.out.println("You are in superclass");
}
}
class B extends A
{
void show()
{
System.out.println("You are in subclass");
}
}
class Dmd
{
public static void main(String args[])
{
A a;
//Creating reference variable
B b=new B();
//creating object for class B
b.show();
a=b;
//Assigning object b to a;
a.show();
}
}

4. OUTPUT:
You are in superclass
You are in subclass

38

16. Experiment no. 16: Declaring and implementing an interface


1. AIM:
Write a java program to implement the Interface command on multiple
class.
2. Algorithm:
1. Start the program.
2. Create a classes and variables with data types.
3. Create a command of interface( ).
4. Create an object of relevant class, to call the procedure.
5. Calculate the formula in a program.
6. Print the concatenation of string.
7. Stop the program.
3. Program:
interface Pet
{
void speak();
void legs(int x);
String move(String how);
double weight(double x);
}
public class interfaceDemo implements Pet{
public void speak(){
System.out.println("Dog braks");
}
public void legs(int x){
System.out.println("Dog has got" +x+"legs");
}
public String move(String how_to_ move){
System.out.println("Dog moves on"+how_to_move+"on land);
return"";
}
public double weight(double x){
return x;
}
public static void main(string args[]){
double wt;
InterfaceDemo id= new InterfaceDemo();
id.speak();
id.legs(4);
id.move("four legs");
wt=id.weight(24.58);
System.out.println("Dog weights" +wt + "kgs");
}
}

39

4. OUTPUT:
Dog barks
Dog has got 4 legs
dog moves on four legs on land
Dog weights 24.58 kgs

40

17. Experiment no. 17: Program To Implement "Inheritance"


1. AIM:
Write a java program to implement the Inheritance program.
2. Algorithm:
1. Start the program, import the packages.
2. Create a class and variables with data types.
3. Declare the methods in different names in Arithmetic operations.
4. Arguments give a throws IOExceptions.
5. Read a string with inputstreamReader(System.in).
6. convert the string into Integer.parseInt(stdin.readLine());
7. Create a object to call the procedure.
8. Print the concatenation of string.
9. Stop the program.
3. PROGRAM:
import java.io.*;
import java.lang.*;
class Add
{
int c;
void add(int a,int b)
{
c=a+b;
System.out.println("Result of adding is "+ c);
}
}
class Sub extends Add
{
void sub(int a,int b)
{
c=a-b;
System.out.println("Result of subtracting is "+ c);
}
}
class Mul extends Sub
{
void mul(int a,int b)
{
c=a*b;
System.out.println("Result of multiplying is "+ c);
}
}
class Inherit
{
public static void main(String args[]) throws IOException

41

{
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter 2 numbers to perform add,sub and mul");
int i=Integer.parseInt(stdin.readLine());
int j=Integer.parseInt(stdin.readLine());
Mul m=new Mul();
m.mul(i,j);
m.add(i,j);
m.sub(i,j);
}
}

4. OUTPUT
Enter 2 numbers to perform add,sub and mul
10 20
Result of multiplying is 300
Result of adding is 30
Result of subtracting is -10
Enter 2 numbers to perform add,sub and mul
5 10
Result of multiplying is 50
Result of adding is 15
Result of subtracting is -5
Enter 2 numbers to perform add,sub and mul
2 1
Result of multiplying is 2
Result of adding is 3
Result of subtracting is 1

42

18. Experiment no. 18: Program to show the Use of This Keyword and
Constructor Overloading
1. AIM:
Write a java program to show the use of This Keyword And Constructor Overloading.

2. Algorithm:
1. Start the program, import the packages.
2. Create a class and variables with data types.
3. Declare the methods in same name with different parameters.
4. Arguments give a throws IoExceptions.
5. Read a string with inputstreamReader(System.in).
6. convert the string into Integer.parseInt(stdin.readLine());
7. Create a object to call the procedure.
8. Print the concatenation of string.
9. Stop the program.
3. PROGRAM:
import java.io.*;
import java.lang.*;
class A
{
int Square( int x )
{

//importing io package
//importing Lang package

int s=x*x;
return(s);
}
//End of constructor Square with int as return type
float Square( float x )
{
float s=x*x;
return(s);
}
//End of constructor Square with float as return type
double Square( double x )
{
double s=x*x;
return(s);
}
//End of constructor Square with double as return type
}
//End of class A
class Methover
{
public static void main(String args[])
{

throws IOException

System.out.println("Enter the integer number you want to calculate square");

43

BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));


int n=Integer.parseInt(stdin.readLine());
System.out.println("Enter the floating point number you want to calculate square");
float m=Float.parseFloat(stdin.readLine());
System.out.println("Enter the double data type number uou want to calculate square");
double p=Double.parseDouble(stdin.readLine());
A a=new A();
int sq1=a.Square(n);
System.out.println("The square of integer number is " + sq1);
A a1=new A();
float sq2=a1.Square(m);
System.out.println("The square of float number is " + sq2);
A a2=new A();
double sq3=a2.Square(p);
System.out.println("The square of double number is " + sq2);
}
}

4. OUTPUT:
Enter the integer number you want to calculate square 5
Enter the floating point number you want to calculate square 2.5
Enter the double data type number uou want to calculate square 3.44
The square of integer number is 25
The square of float number is 6.25
The square of double number is 11.56

44

19. Experiment no. 19: Program to invoke constructors using "Super" Keyword
1. AIM:
Write a java program to Invoke constructors using "Super" Keyword.
2. Algorithm:
1.
2.
3.
4.
5.

Start the program.


Create a class and variables with data types.
Declare the method of void show ();
Print the concatenation of values.
Stop the program.

3. PROGRAM:
class A
{
int a,b,c;
A(int d1,int d2)
//Constructor of class A
{
a=d1;
b=d2;
}
void show()
{
System.out.println("The value of a is " + a);
System.out.println("The value of b is " + b);
}
}
//End of class A
class B extends A
{
B(int d1,int d2,int d3) //Constructor of class B
{
super(d1,d2);
//super calls constructor A
c=d3;
}
void show()
{
System.out.println("The value of a is " + a);
System.out.println("The value of b is " + b);
System.out.println("The value of c is " + c);
}
}
//End of class B
class Super1
{
public static void main(String args[])
{
A a=new A(10,20); //Creating object for class A
a.show();
B b=new B(10,20,30); //Creating object for class B

45

b.show();
}
//End of main
}
//End of class super1

4. OUTPUT:
The value of a is 10
The value of b is 20
The value of a is 10
The value of b is 20
The value of c is 30*/

46

20. Experiment no. 20: Program to show The Separate Window multiplication
1. AIM:
Write a java program to show the separate window of multiplication of
three numbers.
2. Algorithm:
1. Start the program, import the packages.
2. Create a class and variables with data types.
3. Declare the string() values.
4. JOptionPane.showInputDialog command is a window.
5. JOptionPane.showMessageDialog dialog box.
6. Print the windows of out put.
7. Stop the program.
3. PROGRAM:
import java.io.*;
import javax.swing.JOptionPane;
public class Product
{
public static void main( String args[] )
{
int x;
// first number
int y;
// second number
int z;
// third number
int result; // product of numbers
String xVal; // first string input by user
String yVal; // second string input by user
String zVal; // third string input by user
xVal = JOptionPane.showInputDialog( "Enter first integer:" );
yVal = JOptionPane.showInputDialog( "Enter second integer:" );
zVal = JOptionPane.showInputDialog( "Enter third integer:" );
x = Integer.parseInt( xVal );
y = Integer.parseInt( yVal );
z = Integer.parseInt( zVal );
result = x * y * z;
JOptionPane.showMessageDialog( null, "The product is " + result );
System.exit( 0 );
} // end method main
} // end class Product

47

4. OUTPUT:

48

21. Experiment no. 21: Program To show The MULTITHREADING


1. AIM:
Write a java program to show the multithreading using try and catch() methods.
2. Algorithm:
1.
2.
3.
4.
5.
6.
7.

Start the program.


Create a class and variables User Thread ().
Using try catch () methods.
For loop executions.
Print the try statements and catch () statements.
Print the concatenation of string.
Stop the program.

3. PROGRAM:
class UserThread extends Thread
{
UserThread()
{
super("UserThread");
System.out.println("it is a UserThread");
start();
}
public void main()
{
try
{
for(int i=10;i>0;i--)
{
System.out.println("Uservalue"+i);
Thread.sleep(500);
}
}
catch(InterruptedException ie)
{
System.out.println("User thread Exception");
}
System.out.println("User thread completed");
}
}
public class ThreadDemo
{
public static void main(String args[])
{
int i;
UserThread ut=new UserThread();
try
{

49

for(i=1;i==2;i++)
{
System.out.println("main Thread value is" +i);
Thread.sleep(100);
}
}
catch(InterruptedException ie)
{
System.out.println("main thread interreupted");
}
System.out.println("main thread completed");
}
}
4. OUTPUT:
It is UserThread
Main thread completed

50

22. Experiment no. 22: Program to implement Packages


1. AIM:
Write a java program to implement Arithmetic operations the packages.
2. Algorithm:
1. Start the program.
2. Import the Mathc packages.
3. Create a classes and variables with data types.
4. Create an object of relevant class, to call the procedure.
5. Create an object to call the packages.
6. Return arithmetic operations.
7. Print the concatenation of string.
8. Stop the program.
3. PROGRAM:
package Mathc;
public class Arithmetic
{
public int a,b;
public Arithmetic(int p,int q)
{
a=p;
b=q;
}
public int add()
{
return(a+b);
}
public int sub()
{
return(a-b);
}
public int mul()
{
return(a*b);
}
public int div()
{
return(a/b);
}
}

import java.io.*;
import Mypack.*;

51

class Usepack
{
public static void main(String args[]) throws IOException
{
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter 2 numbers to perform add,sub and mul");
int i=Integer.parseInt(stdin.readLine());
int j=Integer.parseInt(stdin.readLine());
Mul m=new Mul();
Addsub a=new Addsub();
a.add(i,j);
m.mul(i,j);
m.add(i,j);
m.sub(i,j);
}
}

4. OUTPUT:
Enter 2 numbers to perform add,sub and mul
10 20
Result of multiplying is 300
Result of adding is 30
Result of subtracting is -10
Enter 2 numbers to perform add,sub and mul
5 10
Result of multiplying is 50
Result of adding is 15
Result of subtracting is -5
Enter 2 numbers to perform add,sub and mul
2 1
Result of multiplying is 2
Result of adding is 3
Result of subtracting is 1

52

23. Experiment no. 23 : Program which imports the package Mathc


1. AIM:
Write a java program to implement Arithmetic operations the packages.
2. Algorithm:
1. Start the program.
2. Import the Mathc packages.
3. Create a classes and variables with data types.
4. Create an object of relevant class, to call the procedure.
5. Create an object to call the packages.
6. Return arithmetic operations.
7. Print the concatenation of string.
8. Stop the program.
3. PROGRAM:
import Mathc.*;
public class PackDemo
{
public static void main(String args[])
{
Arithmetic a=new Arithmetic(10,30);
System.out.println(a.add());
System.out.println(a.sub());
System.out.println(a.mul());
System.out.println(a.div());
}
}

4. OUTPUT:
40
-20
300
0

53

24. Experiment no. 24 : Program to print JAVA IS SIMPLE in different styles


and fonts
1. AIM:
Write a java program to implement the APPLET PACKAGES programs.
2. Algorithm:
1. Start the program.
2. Import the packages of applet,awt.
3. Create a classes public void paint(Graphics g).
4. Assume the values of string, color and font.
5. g.drawString() application of GUI.
6. Printing in the separated Applet viewer window.
7. Stop the program.
3. PROGRAM:
import java.awt.*;
import java.applet.*;
import javax.swing.*;
/*<applet code="JavaDemo" width=350 height=200>
</applet>*/
public class JavaDemo extends JApplet
{
public void paint(Graphics g)
{
Font f1=new Font("TimesNewRoman",Font.BOLD|Font.ITALIC,20);
g.setFont(f1);
String str="JAVA IS SIMPLE";
g.drawString(str,10,20);
Font f2=new Font("Helvetica",Font.BOLD,30);
g.setFont(f2);
g.setColor(Color.RED);
g.drawString(str,10,60);
Font f3=new Font("TimesNewRoman",Font.PLAIN,40);
g.setFont(f3);
g.setColor(Color.GREEN);
g.drawString(str,10,100);
}
}

54

4. OUTPUT

*/

55

25. Experiment no. 25: Program to draw Lines, Rectangles, Rounded


Rectangles, filled Polygons and Ovals
1. AIM:
Write a java program to implement the APPLET PACKAGES, draw Lines,
Rectangles, Rounded Rectangles, filled Polygons programs.
2. Algorithm:
1. Start the program.
2. Import the packages of applet,awt,awt.event.
3. Create a classes: public void paint(Graphics g).
4. Assume the values of string, color and font.
5. g.drawString() application of Graphical User Interface.
6. Printing in the separated Applet viewer window.
7. Stop the program.
3. PROGRAM:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code="ShapeDemo" width=300 height=300>
</applet*/
public class ShapeDemo extends Applet
{
public void paint(Graphics g)
{
setLayout(new FlowLayout());
g.drawLine(10,20,50,20);
g.drawRect(20,30,30,30);
g.setColor(Color.RED);
g.fillRect(20,30,30,30);
g.drawRoundRect(20,70,50,70,15,15);
g.setColor(Color.GREEN);
g.fillRoundRect(20,70,50,70,15,15);
g.drawOval(20,150,50,50);
g.setColor(Color.BLUE);
g.fillOval(20,150,50,50);
}
}

56

4. OUTPUT:

57

26. Experiment no. 26: Program to implement Action Event that performs
Arithmetic Operations
1. AIM:
Write a java program to implement the APPLET PACKAGES, draw event
handlers programs.
2. Algorithm:
1. Start the program.
2. Import the packages of applet, awt, awt.event.
3. Create a classes, methods.
4. Assume the values of string Integer.parseInt.
5. while using if loops rotating values.
6. The event arguments execution.
7. Printing in the separated Applet viewer window.
8. Stop the program.
3. PROGRAM:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EventDemo extends JFrame implements ActionListener
{
public JLabel l1,l2,l3;
public JTextField t1,t2;
public JButton b1,b2,b3;
EventDemo( )
{
Container c = getContentPane( );
c. setLayout(new FlowLayout());
l1=new JLabel("NUM 1");
l2 = new JLabel("NUM 2");
l3 = new JLabel( );
t1 = new JTextField(6);
t2 = new JTextField(6);
b1 = new JButton("ADD");
b2 = new JButton("SUB");
b3 = new JButton("MUL");
c.add(l1);
c.add(t1);
c.add(l2);
c.add(t2);
c.add(b1);
c.add(b2);

58

c.add(b3);
c.add(l3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
setSize(200,200);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
int n1,n2,n3=0;
n1 = Integer.parseInt(t1.getText( ).trim());
n2 = Integer.parseInt(t2.getText( ).trim());
String str = "The result is ";
if(ae.getSource( ) == b1)
n3=n1 + n2;
if(ae.getSource( ) == b2)
n3= n1-n2;
if(ae.getSource( ) == b3)
n3=n1*n2;
l3.setText(str+" " +n3);
}
public static void main(String args[ ] )
{
EventDemo e = new EventDemo( );
}
}

4. OUTPUT

59

27. Experiment no. 27: Program to implement Mouse Listener


(Mouse Events)
1. AIM:
Write a java program to implement the APPLET PACKAGES, draw Mouse
event handler programs.
2. Algorithm:
1. Start the program.
2. Import the packages of applet, awt, awt.event.
3. Create a classes, methods.
4. Mouse moments, mouse Clicked, mouse Pressed, mouse Released, mouse
Entered, mouse Exited, mouse Dragged events args.
5. g.drawString() application of Graphical User Interface.
6. While rotating mouse event args.
7. The mouse event arguments execution.
8. Printing in the separated Applet viewer window.
9. Stop the program.
3. PROGRAM:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code="MouseDemo" width=300 height=300>
</applet>*/
public class MouseDemo extends Applet implements MouseListener,MouseMotionListener
{
int mx=0;
int my=0;
String msg="";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
mx=20;
my=40;
msg="Mouse Clicked";
repaint();
}
public void mousePressed(MouseEvent me)
{
mx=30;
my=60;
msg="Mouse Pressed";
repaint();

60

}
public void mouseReleased(MouseEvent me)
{
mx=30;
my=60;
msg="Mouse Released";
repaint();
}
public void mouseEntered(MouseEvent me)
{
mx=40;
my=80;
msg="Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent me)
{
mx=40;
my=80;
msg="Mouse Exited";
repaint();
}
public void mouseDragged(MouseEvent me)
{
mx=me.getX();
my=me.getY();
showStatus("Currently mouse dragged"+mx+" "+my);
repaint();
}
public void mouseMoved(MouseEvent me)
{
mx=me.getX();
my=me.getY();
showStatus("Currently mouse is at"+mx+" "+my);
repaint();
}
public void paint(Graphics g)
{
g.drawString("Handling Mouse Events",30,20);
g.drawString(msg,60,40);
}
}

61

4. OUTPUT

62

28. Experiment no. 28: Program to implement KeyListener (Key Events)


1. AIM:
Write a java program to implement the APPLET PACKAGES, draw Key
event Listeners programs.
2. Algorithm:
1. Start the program.
2. Import the packages of applet, awt, awt.event.
3. Create a classes, methods.
4. Key moments, key Clicked, key Pressed, key Released, key Entered, key
Exited, key Dragged events args.
5. g.drawString() application of Graphical User Interface.
6. while rotating key event args.
7. Printing in the separated Applet viewer window.
8. Stop the program.
3. PROGRAM:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code="KeyDemo" width=300 height=300>
</applet>*/
public class KeyDemo extends Applet implements KeyListener
{
String msg="";
int x=10;
int y=20;
public void init()
{
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent ke)
{
showStatus("key pressed");
int key=ke.getKeyCode();
switch(key)
{
case KeyEvent.VK_UP:msg=msg+"<up>";
break;
case KeyEvent.VK_SHIFT:msg=msg+"<shift>";
break;
case KeyEvent.VK_F1:msg+="<F1>";
break;

63

}
repaint();
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Released");
}
public void keyTyped(KeyEvent ke)
{
char ch=ke.getKeyChar();
msg=msg+ch;
showStatus("Key Typed");
}
public void paint(Graphics g)
{
g.drawString(msg,40,40);
}
}

4. OUTPUT

64

29. Experiment no. 29: Program to implement BorderLayout


1. AIM:
Write a java program to implement the APPLET PACKAGES, Create
Border layout of window.
2. Algorithm:
1. Start the program.
2. Import the packages of applet, awt, awt.event.
3. Create classes and methods.
4. Declare the Border Layout directions.
5. Application of Graphical User Interface.
6. Printing in the separated Applet viewer window.
7. Stop the program.
3. PROGRAM:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code = "BorderDemo" width=300 height=300>
</applet> */
public class BorderDemo extends Applet
{
public void init( )
{
setLayout(new BorderLayout( ));
add(new Button("CSE students"),BorderLayout.NORTH);
add(new Label("studying well"),BorderLayout.SOUTH);
add(new Button("right"),BorderLayout.EAST);
add(new Button("left"),BorderLayout.WEST);
String msg = "This is the Demo for BorderLayout"+"done by Cse-1 students";
add(new TextArea(msg),BorderLayout.CENTER);
}
}

65

4. OUTPUT

66

30. Experiment no. 30: Program to implement Radio Listener


1. AIM:
Write a java program to implement the APPLET PACKAGES, Create
Radio buttons in a window.
2. Algorithm:
1. Start the program.
2. Import the packages of applet, awt, awt.event.
3. Create classes, methods.
4. Declare the Radio buttons and give values.
5. Application of Graphical User Interface.
6. Printing in the separated Applet viewer window.
7. Stop the program.
3. PROGRAM:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RadDemo extends JFrame implements ActionListener
{
public JLabel l1;
public JRadioButton r1,r2,r3;
RadDemo()
{
Container c = getContentPane( );
c.setLayout(new FlowLayout( ));
l1=new JLabel();
r1 = new JRadioButton("CSE");
r2 = new JRadioButton("ECE");
r3 = new JRadioButton("EEE");
ButtonGroup bg = new ButtonGroup( );
bg.add(r1);
bg.add(r2);
bg.add(r3);
c.add(r1);
c.add(r2);
c.add(r3);
c.add(l1);
r1.addActionListener(this);
r2.addActionListener(this);
r3.addActionListener(this);
setSize(200,200);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand()=="CSE")

67

{
l1.setText("You selected CSE");
}
if(ae.getActionCommand()=="ECE")
{
l1.setText("You selected ECE");
}
if(ae.getActionCommand()=="EEE")
{
l1.setText("You selected EEE");
}
}
public static void main(String args[])
{
RadDemo rd=new RadDemo();
}
}

4. OUTPUT

68

You might also like