Java Lab Manual
Java Lab Manual
Java Lab Manual
JAVA PROGRAMMING
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.
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
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
--------------------------------------------------------------------------------
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.
--------------------------------------------------------------------------------
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)
Java Source
Code
Javadoc
HTML
files
Javac
Java Class
File
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.
10
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.
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
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.
16
Begin
(load Applet)
Born
initialization
Start()
Stop()
Running
Display
Idle
Start()
stopped
Paint()
Destroy()
Destroyed
Dead
Exit of Browser
17
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
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
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. 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
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
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
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
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
4. OUTPUT:
Enter positive value:
10
1
2
3
5
7
28
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
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
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
4. OUTPUT:
You are in superclass
You are in subclass
38
39
4. OUTPUT:
Dog barks
Dog has got 4 legs
dog moves on four legs on land
Dog weights 24.58 kgs
40
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
43
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.
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
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
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
4. OUTPUT:
40
-20
300
0
53
54
4. OUTPUT
*/
55
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
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
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
65
4. OUTPUT
66
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