SlideShare a Scribd company logo
1 of 83
Download to read offline
Department of Information Technology
OOPS THROUGH JAVA
Lab Manual for the Academic Year 2007-2008
II B. Tech
Guru Nanak Engineering
College
Ibrahimpatnam, R R District – 501 506 (A. P.)
In-charge HOD
Principal
Prepared by: Approved &
Reviewed by:
Issued by: w.e.f Date:
D. RAMA RAO
G. PRABHAKAR RAJU
Guru Nanak Engineering College
Ibrahimpatnam, R R District – 501 506 (A. P.)
Department of Information Technology
Lab Manual for the Academic Year 2007-08
(In accordance with JNTU syllabus)
SUBJECT : JAVA LAB
SUBJECT CODE : CS (05338)
SEMESTER : II - II
STREAM : Information Technology
INSTRUCTOR : D. RAMA RAO
: G. PRABHAKAR RAJU
PROGRAMMERS : 1) G. SRINIVASULU
2) M.B. NEELAKANTESHWARA REDDY
2
Head IT
3
Guru Nanak Engineering College
Ibrahimpatnam, R R District – 501 506 (A. P.)
Department of Information Technology
Lab Manual for the Academic Year 2007-08
(In accordance with JNTU syllabus)
Suggestions from Principal:
Enhancement if any:
Comments:
4
S.No Contents Page No
1 Lab Objective 4
2 Introduction About Lab 5
3 Guidelines to Students 6
4
List of Lab Exercises
4.1 Syllabus Programs (JNTU)
4.2 Additional and Advanced
Programs
7-8
5 Description about Oops Concepts 9-17
6 Solutions for Programs 18-59
7
Solutions for Additional
Programs
60-80
8 References 81
5
Lab Objective
1) Introduction to object oriented programming concepts- java as an object
oriented programming language. Introduction to java application and applets-
control structures-methods-arrays.
2) Object based and object oriented programming creating packages-using
overloaded constructors-static class variables-data abstraction and information
hiding-relation between super class objects and subclass objects composition
verses inheritance-polymorphism- dynamic method binding abstract super
classes and concrete super classes –inheriting interface-use of inner classes and
wrapper classes-String to kenizer and String Suffer classes.
3) Role of object oriented programming in designing GUI –Graphs and
Java20overview of swing- event handling, adapter classes and layout managers.
Advance GUI components- JPopup Menus- JDesktopPane- advance layout
managers.
4) Exception handling and multithreading in object oriented programming- When
exception handling should be used-java exception handling – exceptions and
inheritance-multithreading in java-thread synchronization-daemon threads
Runnable interface- Files and streams in java.
5) Network and Database handling through object oriented programming –using
JOSC –processing queries-overview of servlet –introduction to networking –
establishing a simple server and a client – introduction to RMI – implementing
the remote interface.
6
INTRODUCTION ABOUT LAB
There are 66 systems ( Compaq Presario ) installed in this Lab.
Their configurations are as follows :
Processor : AMD Athelon ™ 1.67 GHz
RAM : 256 MB
Hard Disk : 40 GB
Mouse : Optical Mouse
Network Interface card : Present
Software
1 All systems are configured in DUAL BOOT mode i.e, Students can boot from
Windows XP or Linux as per their lab requirement.
This is very useful for students because they are familiar with different
Operating Systems so that they can execute their programs in different
programming environments.
2 Each student has a separate login for database access
Oracle 9i client version is installed in all systems. On the server, account for each
student has been created.
This is very useful because students can save their work ( scenarios’,
pl/sql programs, data related projects ,etc) in their own accounts. Each student
work is safe and secure from other students.
3 Latest Technologies like DOT NET and J2EE are installed in some
systems. Before submitting their final project, they can start doing mini
project from 2nd
year onwards.
4 MASM ( Macro Assembler ) is installed in all the systems
Students can execute their assembly language programs using MASM.
MASM is very useful students because when they execute their programs
they can see contents of Processor Registers and how each instruction is
being executed in the CPU.
1 Rational Rose Software is installed in some systems
Using this software, students can depict UML diagrams of their
projects.
2 Software installed : C, C++, JDK1.5, MASM, OFFICE-XP, J2EE and DOT
NET, Rational Rose.
3 Systems are provided for students in the 1:1 ratio.
4 Systems are assigned numbers and same system is allotted for students when they
do the lab.
7
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.
2 Students are required to carry their observation / programs book with completed
exercises while entering the lab.
3 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.
4 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.
5 Lab records need to be submitted on or before date of submission.
6 Students are not supposed to use floppy disks
8
Lab Programs
OOPS THROUGH JAVA Lab schedules
Submissions should include-
a) Aim of the program
b) Description
c) Procedure
d) Algorithm
e) Program( printout, which includes Name, rollno, date on the top)
f) Expected output
g) Observed output.
Week 1
1 Write a Java program to find simple Interest.
2 Defining a class called Student. Observe the members of the class i.e the data and
functions.
3 Program on Method overloading
4 Program on Constructor overloading
Week-2
5 Program on usage of final keyword
6 Using Static key in a variable
7 Java Program using Object reference variables
Week-3
8 Program on inheritance.
10 Write a java program that prompts the user for an integer and then prints out all prime
numbers up to that integer.
11 Write a java program that checks whether a given string is palindrome or not. Ex:
MADAM is a palindrome.
12 Write a java program to find the biggest & smallest number from the given array of 10
integers.
Week -4
13 Write a java program to sort given array of 10 integers in ascending & descending order.
14 Write a java program to delete an element from an array of 10 elements.
15 Write a java program to add two given matrices.
16 Write a java program that prints transpose of a given matrix.
Week-5
17 Write a java program to multiply two given matrices.
18 Write a java program for sorting a given list of names in ascending order.
19 Write a java program to display literal values of all the elements in a given matrix.
Week-6
20 Write a java program that reads a line of integers, and then displays each integer, and the
sum of all the integers (use string tokenizer class).
9
21 Write a java program to create an ordinary file.
22 Write a java program to copy contents from one file into another file.
23 Write a java program to display the contents in a given file.
Week-7
24 Write a java program reads one file name from the user then displays information about
whether the file exists, whether the file is readable, whether the file is writable, the type of
file and the length of the files in bytes.
25 Write a java program that reads a file and display file on the screen, line number before
each line.
26 Write a java program that displays the numbers of characters, lines and words in a text file.
Week-8
27 Write a java program to implement inheritance and overloading methods.
28 Write a java program to create a package and importing the package.
29 Write a java program that implements stack ADT.
30 Write a java program to convert infix expression into postfix form.
31 Write a java program to implement exception handling.
Week-9
31 Write an applet that displays a simple message
32 Creating a moving banner applet.
Week-10
33 Write an applet that computes the payment of a loan based on the amount of the loan, the
interest rate and the number of months. It takes one parameter from the browser: Monthly
rate; if true, the interest is per month; Other wise the interest rate is annual.
Week-11
34 Write a java program that works as a simple calculator. Use a grid layout to arrange buttons
for the digits and for the + - * % operations. Add a text field to display the result.
35 Write a java program to for handling mouse events.
Week 12
36 Write a java program for creating a thread using Thread class.
37 Write a java program for creating a thread by implementing runnable interface.
38 Write a java program for creating a multiple threads
Week-13
39 Write a java program that correctly implements producer consumer problem using the
concept of inter thread communication.
40 Write a java program that lets users create pie charts. Design your own user interface (with
swing & AWT)
Week-14
41 Write a java program that allows the user to draw-lines, rectangles etc..
42 Write a java program that illustrates how run time polymorphism is achieved.
Week-15
43 Write a java program that implements a simple client/server application. The client sends
data to a server. The server receives the data, uses it to produce a result, an then sends the
result back to the client. The client displays the result n the console. For Ex. The data sent
from the client is the radius of a circle, and the result produced by the server is the area of
the circle.
10
OBJECT ORIENTED PROGRAMMING:
OOP Concepts:
The object oriented paradigm is built on the foundation laid by the
structured programming concepts. The fundamental change in OOP is that a program is
designed around the data being operated upon rather upon the operations themselves.
Data and its functions are encapsulated into a single entity.OOP facilitates creating
reusable code that can eventually save a lot of work. A feature called polymorphism
permits to create multiple definitions for operators and functions. Another feature called
inheritance permits to derive new classes from old ones. OOP introduces many new ideas
and involves a different approach to programming than the procedural programming.
Benefits of object oriented programming:
Data security is enforced.
Inheritance saves time.
User defined data types can be easily constructed.
Inheritance emphasizes inventions of new data types.
Large complexity in the software development cn be easily managed.
Basic C++ Knowledge:
C++ began its life in Bell Labs, where Bjarne Stroustrup developed the language in the
early 1980s. C++ is a powerful and flexible programming language. Thus, with minor
exceptions, C++ is a superset of the C Programming language.
The principal enhancement being the object –oriented concept of a class.
A Class is a user defined type that encapsulates many important mechanisms. Classes
enable programmers to break an application up into small, manageable pieces, or objects.
Basic concepts of Objectoriented programming:
Object:
Objects are the basic run time entities in an object-oriented system.
thy may represent a person, a place,a bank account,a table of data or any item that
the program has to handle.
class:
the entire set of data and code of an object can be made of auserdefined data type
with the help of a clss.
in fact,Objects are variables of the type class.
once a class has been defined ,we can create any number of objects belonging to
that class.
A class is thus a collection of objects of similar type.
for example:mango,apple,and orange are members of the class fruit.
ex:
fruit mango;
will create an object mango belonging to the class fruit.
11
Data Abstraction and Encapsulation:
the wrapping up of data and functions in to a single unit is known as encapsulation.
Data encapsulation is the most striking feature of a class.
the data is not accessabile to the outside world,and only those functions which are
wrapped in the class can access.
this insulation of the data from direct access by the program is calld data hiding.
Abstraction :
abstraction referes to the act of representing esseential feartures without including
the background details or explanations.
since the classes use the concept of data abstraction ,thy are known as abstraction
data type(ADT).
Inheritance :
interitance is the process by which objects of one class acquire the
properities of objects of another class. Inheritance supports the concept of hierarchical
classification.
for example:
12
Bird
Attributes:
Feathers
Lay eggs
Flying
bird
Attributes:
-----------
----------
Non flying
bird
Attributes:
-----------
-----------
Robin
Attributes:
_________
Swallow
Attributes:
_________
Penguin
Attributes:
_________
Kiwi
Attributes:
_________
the bird 'robin ' is a part of the class 'flying bird' which is agian a part of the class
'bird'. the concept of inheritance provide the idea of reusability.
POLYMORPHISM:
Polymorphism is another important oop concept. Polymorphism means the ability to
take more than one form. an operation may exhibit different instances. The behavior
depends upon the types of data used in the operation.
The process of making an operator to exhibit different behaviors in different instance
is known as operator overloading.
Polymorphism plays an important role in allowing objects having different internal
structures to share the same external interface. Polymorphism is extensively used if
implementing inheritance.
The Object-Oriented Approach
The fundamental idea behind object-oriented languages is to combine into a single
program entity both data and the functions that operate on that data. Such an entity is
called an object.
An object's functions, called member functions in C++ (because they belong to a
particular class of objects), typically provide the only way to access its data. If you want
to read a data item in an object, you call a member function in the object. It will read the
item and return the value to you. You can't access the data directly. The data is hidden, so
it is safe from accidental alteration. Data and its functions are said to be encapsulated into
a single entity. Encapsulation and data hiding are key terms in the description of object-
oriented languages.
13
Shape
Draw()
Circle Object
Draw()
Box Object
Draw()
Triangle Object
Draw()
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++.
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
14
C++
C Java
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.
--------------------------------------------------------------------------------
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;
15
DATA TYPES IN JAVA
Primitive
(intrinsic)
Non-Primitive
(Derived)
Numeric
Non-Numeric
Integer Floating-point Character Boolean
Class
Interface
Arrays
Integer
Floating point
Byte Short Int Long
DoubleFloat
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.E-36 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.E-303 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;
--------------------------------------------------------------------------------
16
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
17
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.
18
Process of building and running java application programs:
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
19
Text Editor
Java Source
Code
Javadoc
HTML
files
Javac
Java Class
File
Javah
Header
Files
Java (only file name) Jdb (database)
Java
progra
m
Output
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);
System.out.println("s2(java) == s3(java):" +s2== s3);
System.out.println("s1(java)==s4(java):" + s1==s4);
}
20
}
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, it’s 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
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
21
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
program-based 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.
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. Let’s 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 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
22
Main thread
______________
______________
___________
Thread A
_________
_________
_________
_________
Thread B
_________
_________
_________
_________
Thread C
_________
_________
_________
_________
environment, such as those that process transactions from many computers, need to make
a CPU’s 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.
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:
23
Newborn
Blocked
Running Runnable
Dead
Killed Thread
yield
start
stop
stop
stop
New thread
Active
Thread
Idle Thread
(not Runnable)
Resume
notifySuspend
sleep wait
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
24
ClassCast Exception
ArrayIndexOutBounds Exception.
Other exceptions :These include exceptions for multithreading, malformed
URL,reading past end of file etc.
Some of the subclasses:
IOException
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.
25
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);
}
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:
26
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.
27
Stop()
Start()
Paint()
Display
Born
Dead
Running
Idle
Begin
(load Applet) initialization
Start()
stopped
Destroy()
Destroyed
Exit of Browser
Applet state transition diagram
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. Start the program.
2. Declare the variables and assume values
3. InterestTopay=principle*time*rate/100;
4. print the values.
5. End of class and main method.
6. 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
28
2. Experiment no .2 : Program To Find The Arithmetic 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
29
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;
30
case 6:
System.out.println("Six");
break;
case 7:
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
31
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
32
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 if…else 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
33
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. Start the program.
2. Create a class and variables with data types.
3. Read a string with DatainputstreamReader(System.in).
4. convert the string into Integer.parseInt(stdin.readLine());
5. By using for loop rotating the array.
6. Print the concatenation of arrays.
7. 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
34
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.
35
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)
36
{
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);
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
37
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
38
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);
39
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);
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
40
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]);
41
}
}
4. OUTPUT:
Enter 10 integers in to array:
9 8 7 6 5 4 3 2 1 0
Required order is: 0 1 2 3 4 5 6 7 8 9
42
12. Experiment no. 12: Program to find the 2 largest numbers of a given array
1. AIM:
To find the largest number of given numbers, by using arrays.
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 for loop rotating the single dimensional arrays value.
6. Repeats enter the value until end of loop.
7. Print the concatenation of string.
8. Stop the program.
3. PROGRAM:
import java.io.*; //Importing io package
import java.lang.*; //Importing lang package
class Largest
{
public static void main(String args[]) throws IOException
{
int a[]= new int[10];
int i,j,k;
System.out.println("Enter the numbers of the array");
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
for(i=0;i<10;i++)
{
a[i]=Integer.parseInt(stdin.readLine());
}
for(i=0;i<10;i++)
{
for(j=(i+1);j<10;j++)
{
if(a[i]>a[j])
{
k=a[i];
a[i]=a[j];
a[j]=k;
} //End of if
} //End of inner for loop
} //End of outer for loop
System.out.println("The first largest number in the array is " + a[9]);
43
System.out.println("The second largest number in the array is " + a[8]);
} //End of main
} //End of class Largest
4. OUTPUT
Enter the numbers of the array 1 2 6 3 78 7 8 45 32 23
The first largest number in the array is 78
The second largest number in the array is 45
Enter the numbers of the array 12 23 34 45 56 67 68 78 89 100
The first largest number in the array is 100
The second largest number in the array is 89
Enter the numbers of the array 11 12 13 14 15 16 17 18 19 20
The first largest number in the array is 20
The second largest number in the array is 19
44
13. Experiment no. 13: 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++)
45
{
b[i][j]=Integer.parseInt(stdin.readLine());
}
}
for(i=0;i<3;i++) //Calculating additon and substraction
{
for(j=0;j<3;j++)
{
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();
}
}
}
46
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
47
14. Experiment no. 14: 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);
}
48
double area()
{
return((dim1*dim2)/2);
}
}
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*/
49
15. Experiment no. 15: 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[])
50
{
A a=new A(6);
A a2=new A(7,8);
A a1=new A(9,10,11);
a.show();
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
51
16. Experiment no. 16: 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
52
17. Experiment no. 17: 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");
53
wt=id.weight(24.58);
System.out.println("Dog weights" +wt + "kgs");
}
}
4. OUTPUT:
Dog barks
Dog has got 4 legs
dog moves on four legs on land
Dog weights 24.58 kgs
54
18. Experiment no. 18: 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);
55
}
}
class Inherit
{
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();
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
56
19. Experiment no. 19: 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.*; //importing io package
import java.lang.*; //importing Lang package
class A
{
int Square( int x )
{
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
57
class Methover
{
public static void main(String args[]) throws IOException
{
System.out.println("Enter the integer number you want to calculate square");
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
58
20. Experiment no. 20: Program to invoke constructors using "Super" Keyword
1. AIM:
Write a java program to Invoke constructors using "Super" Keyword.
2. Algorithm:
1. Start the program.
2. Create a class and variables with data types.
3. Declare the method of void show ();
4. Print the concatenation of values.
5. 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
59
{
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
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*/
60
21. Experiment no. 21: 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
61
4. OUTPUT:
62
22. Experiment no. 22: Program To show The MULTITHREADING
1. AIM:
Write a java program to show the multithreading using try and catch() methods.
2. Algorithm:
1. Start the program.
2. Create a class and variables User Thread ().
3. Using try catch () methods.
4. For loop executions.
5. Print the try statements and catch () statements.
6. Print the concatenation of string.
7. 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[])
63
{
int i;
UserThread ut=new UserThread();
try
{
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
64
23. Experiment no. 23: 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);
}
}
65
import java.io.*;
import Mypack.*;
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
66
24. Experiment no. 24 : 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
67
25. Experiment no. 25 : 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);
}
}
68
4. OUTPUT
*/
69
26. Experiment no. 26: 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);
}
}
70
4. OUTPUT:
71
27. Experiment no. 27: 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);
72
c.add(t1);
c.add(l2);
c.add(t2);
c.add(b1);
c.add(b2);
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
73
28. Experiment no. 28: 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();
74
}
public void mousePressed(MouseEvent me)
{
mx=30;
my=60;
msg="Mouse Pressed";
repaint();
}
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);
75
g.drawString(msg,60,40);
}
}
4. OUTPUT
76
29. Experiment no. 29: 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();
77
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;
}
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
78
30. Experiment no. 30: 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);
}
}
79
4. OUTPUT
80
31. Experiment no. 31: 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);
81
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand()=="CSE")
{
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
82
References:
1. The complete reference Java, J2SE 5th
edition, Herbert Schild, TMH publishing Company
limited, New Delhi.
2. Big Java 2nd
edition, Cay Horstmann, John Wiley and Sons.
3. Java how to programme, sixth edition, H.M.Dietel and P.J. Deitel.
4. Core java 2,Vol2, Advanced Fundamentals Cay, S. Horshmann and Gary Comell
Seventh edition Person edition.
83

More Related Content

What's hot

Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for DesignersR. Sosa
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 
Object oriented programming concepts
Object oriented programming conceptsObject oriented programming concepts
Object oriented programming conceptsrahuld115
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java ProgrammingMath-Circle
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in javaHitesh Kumar
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented ProgrammingRAJU MAKWANA
 
Java Presentation
Java PresentationJava Presentation
Java Presentationpm2214
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)slire
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaAjay Sharma
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Conceptsthinkphp
 
String in c programming
String in c programmingString in c programming
String in c programmingDevan Thakur
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdmHarshal Misalkar
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For SyntaxPravinYalameli
 

What's hot (20)

Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for Designers
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Java &amp; advanced java
Java &amp; advanced javaJava &amp; advanced java
Java &amp; advanced java
 
Classes&amp;objects
Classes&amp;objectsClasses&amp;objects
Classes&amp;objects
 
Object oriented programming concepts
Object oriented programming conceptsObject oriented programming concepts
Object oriented programming concepts
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Java Notes
Java Notes Java Notes
Java Notes
 
Java programming course for beginners
Java programming course for beginnersJava programming course for beginners
Java programming course for beginners
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Operators in python
Operators in pythonOperators in python
Operators in python
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
String in c programming
String in c programmingString in c programming
String in c programming
 
Oop
OopOop
Oop
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdm
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
 

Similar to 66781291 java-lab-manual

SE-IT JAVA LAB SYLLABUS
SE-IT JAVA LAB SYLLABUSSE-IT JAVA LAB SYLLABUS
SE-IT JAVA LAB SYLLABUSnikshaikh786
 
Strayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade newStrayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade newuopassignment
 
Strayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade newStrayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade newlroselyn
 
Strayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade newStrayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade newshyaminfo16
 
Strayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade newStrayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade newdixonbakerr
 
Strayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade newStrayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade newcharlesangles123
 
Strayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade newStrayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade newchanduruc123
 
Strayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade newStrayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade newshyaminfo40
 
Library Managemnet System
Library Managemnet SystemLibrary Managemnet System
Library Managemnet SystemAbhishek Shakya
 
PRG 420 Education for Service--prg420.com
PRG 420 Education for Service--prg420.comPRG 420 Education for Service--prg420.com
PRG 420 Education for Service--prg420.comwilliamwordsworth25
 
Review Paper on Online Java Compiler
Review Paper on Online Java CompilerReview Paper on Online Java Compiler
Review Paper on Online Java CompilerIRJET Journal
 
PRG 420 NERD Become Exceptional--prg420nerd.com
PRG 420 NERD Become Exceptional--prg420nerd.comPRG 420 NERD Become Exceptional--prg420nerd.com
PRG 420 NERD Become Exceptional--prg420nerd.comagathachristie127
 
PRG 420 Effective Communication - snaptutorial.com
PRG 420 Effective Communication - snaptutorial.comPRG 420 Effective Communication - snaptutorial.com
PRG 420 Effective Communication - snaptutorial.comdonaldzs37
 
PRG 420 Education Counseling / prg420.com
PRG 420 Education Counseling / prg420.comPRG 420 Education Counseling / prg420.com
PRG 420 Education Counseling / prg420.comkopiko76
 
PRG 420 Inspiring Innovation--prg420.com
PRG 420 Inspiring Innovation--prg420.comPRG 420 Inspiring Innovation--prg420.com
PRG 420 Inspiring Innovation--prg420.comkopiko112
 
PRG 420 NERD Education Counseling--prg420nerd.com
PRG 420 NERD Education Counseling--prg420nerd.comPRG 420 NERD Education Counseling--prg420nerd.com
PRG 420 NERD Education Counseling--prg420nerd.comvenkat60044
 
_OOP with JAVA Solution Manual (1).pdf
_OOP with JAVA Solution Manual (1).pdf_OOP with JAVA Solution Manual (1).pdf
_OOP with JAVA Solution Manual (1).pdfvanithagp1
 

Similar to 66781291 java-lab-manual (20)

SE-IT JAVA LAB SYLLABUS
SE-IT JAVA LAB SYLLABUSSE-IT JAVA LAB SYLLABUS
SE-IT JAVA LAB SYLLABUS
 
Strayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade newStrayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade new
 
Strayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade newStrayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade new
 
Strayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade newStrayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade new
 
Strayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade newStrayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade new
 
Strayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade newStrayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade new
 
Strayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade newStrayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade new
 
Strayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade newStrayer cis 406 week 10 assignment 2 u grade new
Strayer cis 406 week 10 assignment 2 u grade new
 
Library Managemnet System
Library Managemnet SystemLibrary Managemnet System
Library Managemnet System
 
PRG 420 Education for Service--prg420.com
PRG 420 Education for Service--prg420.comPRG 420 Education for Service--prg420.com
PRG 420 Education for Service--prg420.com
 
CAR SHOWROOM SYSTEM
CAR SHOWROOM SYSTEMCAR SHOWROOM SYSTEM
CAR SHOWROOM SYSTEM
 
All experiment of java
All experiment of javaAll experiment of java
All experiment of java
 
Review Paper on Online Java Compiler
Review Paper on Online Java CompilerReview Paper on Online Java Compiler
Review Paper on Online Java Compiler
 
PRG 420 NERD Become Exceptional--prg420nerd.com
PRG 420 NERD Become Exceptional--prg420nerd.comPRG 420 NERD Become Exceptional--prg420nerd.com
PRG 420 NERD Become Exceptional--prg420nerd.com
 
PRG 420 Effective Communication - snaptutorial.com
PRG 420 Effective Communication - snaptutorial.comPRG 420 Effective Communication - snaptutorial.com
PRG 420 Effective Communication - snaptutorial.com
 
PRG 420 Education Counseling / prg420.com
PRG 420 Education Counseling / prg420.comPRG 420 Education Counseling / prg420.com
PRG 420 Education Counseling / prg420.com
 
PRG 420 Inspiring Innovation--prg420.com
PRG 420 Inspiring Innovation--prg420.comPRG 420 Inspiring Innovation--prg420.com
PRG 420 Inspiring Innovation--prg420.com
 
PRG 420 NERD Education Counseling--prg420nerd.com
PRG 420 NERD Education Counseling--prg420nerd.comPRG 420 NERD Education Counseling--prg420nerd.com
PRG 420 NERD Education Counseling--prg420nerd.com
 
Presentation5
Presentation5Presentation5
Presentation5
 
_OOP with JAVA Solution Manual (1).pdf
_OOP with JAVA Solution Manual (1).pdf_OOP with JAVA Solution Manual (1).pdf
_OOP with JAVA Solution Manual (1).pdf
 

66781291 java-lab-manual

  • 1. Department of Information Technology OOPS THROUGH JAVA Lab Manual for the Academic Year 2007-2008 II B. Tech Guru Nanak Engineering College Ibrahimpatnam, R R District – 501 506 (A. P.) In-charge HOD Principal
  • 2. Prepared by: Approved & Reviewed by: Issued by: w.e.f Date: D. RAMA RAO G. PRABHAKAR RAJU Guru Nanak Engineering College Ibrahimpatnam, R R District – 501 506 (A. P.) Department of Information Technology Lab Manual for the Academic Year 2007-08 (In accordance with JNTU syllabus) SUBJECT : JAVA LAB SUBJECT CODE : CS (05338) SEMESTER : II - II STREAM : Information Technology INSTRUCTOR : D. RAMA RAO : G. PRABHAKAR RAJU PROGRAMMERS : 1) G. SRINIVASULU 2) M.B. NEELAKANTESHWARA REDDY 2
  • 4. Guru Nanak Engineering College Ibrahimpatnam, R R District – 501 506 (A. P.) Department of Information Technology Lab Manual for the Academic Year 2007-08 (In accordance with JNTU syllabus) Suggestions from Principal: Enhancement if any: Comments: 4
  • 5. S.No Contents Page No 1 Lab Objective 4 2 Introduction About Lab 5 3 Guidelines to Students 6 4 List of Lab Exercises 4.1 Syllabus Programs (JNTU) 4.2 Additional and Advanced Programs 7-8 5 Description about Oops Concepts 9-17 6 Solutions for Programs 18-59 7 Solutions for Additional Programs 60-80 8 References 81 5
  • 6. Lab Objective 1) Introduction to object oriented programming concepts- java as an object oriented programming language. Introduction to java application and applets- control structures-methods-arrays. 2) Object based and object oriented programming creating packages-using overloaded constructors-static class variables-data abstraction and information hiding-relation between super class objects and subclass objects composition verses inheritance-polymorphism- dynamic method binding abstract super classes and concrete super classes –inheriting interface-use of inner classes and wrapper classes-String to kenizer and String Suffer classes. 3) Role of object oriented programming in designing GUI –Graphs and Java20overview of swing- event handling, adapter classes and layout managers. Advance GUI components- JPopup Menus- JDesktopPane- advance layout managers. 4) Exception handling and multithreading in object oriented programming- When exception handling should be used-java exception handling – exceptions and inheritance-multithreading in java-thread synchronization-daemon threads Runnable interface- Files and streams in java. 5) Network and Database handling through object oriented programming –using JOSC –processing queries-overview of servlet –introduction to networking – establishing a simple server and a client – introduction to RMI – implementing the remote interface. 6
  • 7. INTRODUCTION ABOUT LAB There are 66 systems ( Compaq Presario ) installed in this Lab. Their configurations are as follows : Processor : AMD Athelon ™ 1.67 GHz RAM : 256 MB Hard Disk : 40 GB Mouse : Optical Mouse Network Interface card : Present Software 1 All systems are configured in DUAL BOOT mode i.e, Students can boot from Windows XP or Linux as per their lab requirement. This is very useful for students because they are familiar with different Operating Systems so that they can execute their programs in different programming environments. 2 Each student has a separate login for database access Oracle 9i client version is installed in all systems. On the server, account for each student has been created. This is very useful because students can save their work ( scenarios’, pl/sql programs, data related projects ,etc) in their own accounts. Each student work is safe and secure from other students. 3 Latest Technologies like DOT NET and J2EE are installed in some systems. Before submitting their final project, they can start doing mini project from 2nd year onwards. 4 MASM ( Macro Assembler ) is installed in all the systems Students can execute their assembly language programs using MASM. MASM is very useful students because when they execute their programs they can see contents of Processor Registers and how each instruction is being executed in the CPU. 1 Rational Rose Software is installed in some systems Using this software, students can depict UML diagrams of their projects. 2 Software installed : C, C++, JDK1.5, MASM, OFFICE-XP, J2EE and DOT NET, Rational Rose. 3 Systems are provided for students in the 1:1 ratio. 4 Systems are assigned numbers and same system is allotted for students when they do the lab. 7
  • 8. 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. 2 Students are required to carry their observation / programs book with completed exercises while entering the lab. 3 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. 4 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. 5 Lab records need to be submitted on or before date of submission. 6 Students are not supposed to use floppy disks 8
  • 9. Lab Programs OOPS THROUGH JAVA Lab schedules Submissions should include- a) Aim of the program b) Description c) Procedure d) Algorithm e) Program( printout, which includes Name, rollno, date on the top) f) Expected output g) Observed output. Week 1 1 Write a Java program to find simple Interest. 2 Defining a class called Student. Observe the members of the class i.e the data and functions. 3 Program on Method overloading 4 Program on Constructor overloading Week-2 5 Program on usage of final keyword 6 Using Static key in a variable 7 Java Program using Object reference variables Week-3 8 Program on inheritance. 10 Write a java program that prompts the user for an integer and then prints out all prime numbers up to that integer. 11 Write a java program that checks whether a given string is palindrome or not. Ex: MADAM is a palindrome. 12 Write a java program to find the biggest & smallest number from the given array of 10 integers. Week -4 13 Write a java program to sort given array of 10 integers in ascending & descending order. 14 Write a java program to delete an element from an array of 10 elements. 15 Write a java program to add two given matrices. 16 Write a java program that prints transpose of a given matrix. Week-5 17 Write a java program to multiply two given matrices. 18 Write a java program for sorting a given list of names in ascending order. 19 Write a java program to display literal values of all the elements in a given matrix. Week-6 20 Write a java program that reads a line of integers, and then displays each integer, and the sum of all the integers (use string tokenizer class). 9
  • 10. 21 Write a java program to create an ordinary file. 22 Write a java program to copy contents from one file into another file. 23 Write a java program to display the contents in a given file. Week-7 24 Write a java program reads one file name from the user then displays information about whether the file exists, whether the file is readable, whether the file is writable, the type of file and the length of the files in bytes. 25 Write a java program that reads a file and display file on the screen, line number before each line. 26 Write a java program that displays the numbers of characters, lines and words in a text file. Week-8 27 Write a java program to implement inheritance and overloading methods. 28 Write a java program to create a package and importing the package. 29 Write a java program that implements stack ADT. 30 Write a java program to convert infix expression into postfix form. 31 Write a java program to implement exception handling. Week-9 31 Write an applet that displays a simple message 32 Creating a moving banner applet. Week-10 33 Write an applet that computes the payment of a loan based on the amount of the loan, the interest rate and the number of months. It takes one parameter from the browser: Monthly rate; if true, the interest is per month; Other wise the interest rate is annual. Week-11 34 Write a java program that works as a simple calculator. Use a grid layout to arrange buttons for the digits and for the + - * % operations. Add a text field to display the result. 35 Write a java program to for handling mouse events. Week 12 36 Write a java program for creating a thread using Thread class. 37 Write a java program for creating a thread by implementing runnable interface. 38 Write a java program for creating a multiple threads Week-13 39 Write a java program that correctly implements producer consumer problem using the concept of inter thread communication. 40 Write a java program that lets users create pie charts. Design your own user interface (with swing & AWT) Week-14 41 Write a java program that allows the user to draw-lines, rectangles etc.. 42 Write a java program that illustrates how run time polymorphism is achieved. Week-15 43 Write a java program that implements a simple client/server application. The client sends data to a server. The server receives the data, uses it to produce a result, an then sends the result back to the client. The client displays the result n the console. For Ex. The data sent from the client is the radius of a circle, and the result produced by the server is the area of the circle. 10
  • 11. OBJECT ORIENTED PROGRAMMING: OOP Concepts: The object oriented paradigm is built on the foundation laid by the structured programming concepts. The fundamental change in OOP is that a program is designed around the data being operated upon rather upon the operations themselves. Data and its functions are encapsulated into a single entity.OOP facilitates creating reusable code that can eventually save a lot of work. A feature called polymorphism permits to create multiple definitions for operators and functions. Another feature called inheritance permits to derive new classes from old ones. OOP introduces many new ideas and involves a different approach to programming than the procedural programming. Benefits of object oriented programming: Data security is enforced. Inheritance saves time. User defined data types can be easily constructed. Inheritance emphasizes inventions of new data types. Large complexity in the software development cn be easily managed. Basic C++ Knowledge: C++ began its life in Bell Labs, where Bjarne Stroustrup developed the language in the early 1980s. C++ is a powerful and flexible programming language. Thus, with minor exceptions, C++ is a superset of the C Programming language. The principal enhancement being the object –oriented concept of a class. A Class is a user defined type that encapsulates many important mechanisms. Classes enable programmers to break an application up into small, manageable pieces, or objects. Basic concepts of Objectoriented programming: Object: Objects are the basic run time entities in an object-oriented system. thy may represent a person, a place,a bank account,a table of data or any item that the program has to handle. class: the entire set of data and code of an object can be made of auserdefined data type with the help of a clss. in fact,Objects are variables of the type class. once a class has been defined ,we can create any number of objects belonging to that class. A class is thus a collection of objects of similar type. for example:mango,apple,and orange are members of the class fruit. ex: fruit mango; will create an object mango belonging to the class fruit. 11
  • 12. Data Abstraction and Encapsulation: the wrapping up of data and functions in to a single unit is known as encapsulation. Data encapsulation is the most striking feature of a class. the data is not accessabile to the outside world,and only those functions which are wrapped in the class can access. this insulation of the data from direct access by the program is calld data hiding. Abstraction : abstraction referes to the act of representing esseential feartures without including the background details or explanations. since the classes use the concept of data abstraction ,thy are known as abstraction data type(ADT). Inheritance : interitance is the process by which objects of one class acquire the properities of objects of another class. Inheritance supports the concept of hierarchical classification. for example: 12 Bird Attributes: Feathers Lay eggs Flying bird Attributes: ----------- ---------- Non flying bird Attributes: ----------- ----------- Robin Attributes: _________ Swallow Attributes: _________ Penguin Attributes: _________ Kiwi Attributes: _________
  • 13. the bird 'robin ' is a part of the class 'flying bird' which is agian a part of the class 'bird'. the concept of inheritance provide the idea of reusability. POLYMORPHISM: Polymorphism is another important oop concept. Polymorphism means the ability to take more than one form. an operation may exhibit different instances. The behavior depends upon the types of data used in the operation. The process of making an operator to exhibit different behaviors in different instance is known as operator overloading. Polymorphism plays an important role in allowing objects having different internal structures to share the same external interface. Polymorphism is extensively used if implementing inheritance. The Object-Oriented Approach The fundamental idea behind object-oriented languages is to combine into a single program entity both data and the functions that operate on that data. Such an entity is called an object. An object's functions, called member functions in C++ (because they belong to a particular class of objects), typically provide the only way to access its data. If you want to read a data item in an object, you call a member function in the object. It will read the item and return the value to you. You can't access the data directly. The data is hidden, so it is safe from accidental alteration. Data and its functions are said to be encapsulated into a single entity. Encapsulation and data hiding are key terms in the description of object- oriented languages. 13 Shape Draw() Circle Object Draw() Box Object Draw() Triangle Object Draw()
  • 14. 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++. 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 14 C++ C Java
  • 15. 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. -------------------------------------------------------------------------------- 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; 15 DATA TYPES IN JAVA Primitive (intrinsic) Non-Primitive (Derived) Numeric Non-Numeric Integer Floating-point Character Boolean Class Interface Arrays Integer Floating point Byte Short Int Long DoubleFloat
  • 16. 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.E-36 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.E-303 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; -------------------------------------------------------------------------------- 16
  • 17. 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 17
  • 18. 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. 18
  • 19. Process of building and running java application programs: 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 19 Text Editor Java Source Code Javadoc HTML files Javac Java Class File Javah Header Files Java (only file name) Jdb (database) Java progra m Output
  • 20. 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); System.out.println("s2(java) == s3(java):" +s2== s3); System.out.println("s1(java)==s4(java):" + s1==s4); } 20
  • 21. } 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, it’s 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 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 21
  • 22. 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 program-based 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. 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. Let’s 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 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 22 Main thread ______________ ______________ ___________ Thread A _________ _________ _________ _________ Thread B _________ _________ _________ _________ Thread C _________ _________ _________ _________
  • 23. environment, such as those that process transactions from many computers, need to make a CPU’s 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. 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: 23 Newborn Blocked Running Runnable Dead Killed Thread yield start stop stop stop New thread Active Thread Idle Thread (not Runnable) Resume notifySuspend sleep wait
  • 24. 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 24
  • 25. ClassCast Exception ArrayIndexOutBounds Exception. Other exceptions :These include exceptions for multithreading, malformed URL,reading past end of file etc. Some of the subclasses: IOException 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. 25
  • 26. 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); } 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: 26
  • 27. 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. 27 Stop() Start() Paint() Display Born Dead Running Idle Begin (load Applet) initialization Start() stopped Destroy() Destroyed Exit of Browser Applet state transition diagram
  • 28. 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. Start the program. 2. Declare the variables and assume values 3. InterestTopay=principle*time*rate/100; 4. print the values. 5. End of class and main method. 6. 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 28
  • 29. 2. Experiment no .2 : Program To Find The Arithmetic 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 29
  • 30. 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; 30
  • 31. case 6: System.out.println("Six"); break; case 7: 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 31
  • 32. 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 32
  • 33. 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 if…else 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 33
  • 34. 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. Start the program. 2. Create a class and variables with data types. 3. Read a string with DatainputstreamReader(System.in). 4. convert the string into Integer.parseInt(stdin.readLine()); 5. By using for loop rotating the array. 6. Print the concatenation of arrays. 7. 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 34
  • 35. 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. 35
  • 36. 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) 36
  • 37. { 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); 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 37
  • 38. 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 38
  • 39. 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); 39
  • 40. 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); 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 40
  • 41. 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]); 41
  • 42. } } 4. OUTPUT: Enter 10 integers in to array: 9 8 7 6 5 4 3 2 1 0 Required order is: 0 1 2 3 4 5 6 7 8 9 42
  • 43. 12. Experiment no. 12: Program to find the 2 largest numbers of a given array 1. AIM: To find the largest number of given numbers, by using arrays. 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 for loop rotating the single dimensional arrays value. 6. Repeats enter the value until end of loop. 7. Print the concatenation of string. 8. Stop the program. 3. PROGRAM: import java.io.*; //Importing io package import java.lang.*; //Importing lang package class Largest { public static void main(String args[]) throws IOException { int a[]= new int[10]; int i,j,k; System.out.println("Enter the numbers of the array"); BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in)); for(i=0;i<10;i++) { a[i]=Integer.parseInt(stdin.readLine()); } for(i=0;i<10;i++) { for(j=(i+1);j<10;j++) { if(a[i]>a[j]) { k=a[i]; a[i]=a[j]; a[j]=k; } //End of if } //End of inner for loop } //End of outer for loop System.out.println("The first largest number in the array is " + a[9]); 43
  • 44. System.out.println("The second largest number in the array is " + a[8]); } //End of main } //End of class Largest 4. OUTPUT Enter the numbers of the array 1 2 6 3 78 7 8 45 32 23 The first largest number in the array is 78 The second largest number in the array is 45 Enter the numbers of the array 12 23 34 45 56 67 68 78 89 100 The first largest number in the array is 100 The second largest number in the array is 89 Enter the numbers of the array 11 12 13 14 15 16 17 18 19 20 The first largest number in the array is 20 The second largest number in the array is 19 44
  • 45. 13. Experiment no. 13: 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++) 45
  • 46. { b[i][j]=Integer.parseInt(stdin.readLine()); } } for(i=0;i<3;i++) //Calculating additon and substraction { for(j=0;j<3;j++) { 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(); } } } 46
  • 47. 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 47
  • 48. 14. Experiment no. 14: 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); } 48
  • 49. double area() { return((dim1*dim2)/2); } } 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*/ 49
  • 50. 15. Experiment no. 15: 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[]) 50
  • 51. { A a=new A(6); A a2=new A(7,8); A a1=new A(9,10,11); a.show(); 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 51
  • 52. 16. Experiment no. 16: 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 52
  • 53. 17. Experiment no. 17: 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"); 53
  • 54. wt=id.weight(24.58); System.out.println("Dog weights" +wt + "kgs"); } } 4. OUTPUT: Dog barks Dog has got 4 legs dog moves on four legs on land Dog weights 24.58 kgs 54
  • 55. 18. Experiment no. 18: 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); 55
  • 56. } } class Inherit { 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(); 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 56
  • 57. 19. Experiment no. 19: 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.*; //importing io package import java.lang.*; //importing Lang package class A { int Square( int x ) { 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 57
  • 58. class Methover { public static void main(String args[]) throws IOException { System.out.println("Enter the integer number you want to calculate square"); 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 58
  • 59. 20. Experiment no. 20: Program to invoke constructors using "Super" Keyword 1. AIM: Write a java program to Invoke constructors using "Super" Keyword. 2. Algorithm: 1. Start the program. 2. Create a class and variables with data types. 3. Declare the method of void show (); 4. Print the concatenation of values. 5. 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 59
  • 60. { 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 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*/ 60
  • 61. 21. Experiment no. 21: 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 61
  • 63. 22. Experiment no. 22: Program To show The MULTITHREADING 1. AIM: Write a java program to show the multithreading using try and catch() methods. 2. Algorithm: 1. Start the program. 2. Create a class and variables User Thread (). 3. Using try catch () methods. 4. For loop executions. 5. Print the try statements and catch () statements. 6. Print the concatenation of string. 7. 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[]) 63
  • 64. { int i; UserThread ut=new UserThread(); try { 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 64
  • 65. 23. Experiment no. 23: 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); } } 65
  • 66. import java.io.*; import Mypack.*; 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 66
  • 67. 24. Experiment no. 24 : 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 67
  • 68. 25. Experiment no. 25 : 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); } } 68
  • 70. 26. Experiment no. 26: 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); } } 70
  • 72. 27. Experiment no. 27: 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); 72
  • 73. c.add(t1); c.add(l2); c.add(t2); c.add(b1); c.add(b2); 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 73
  • 74. 28. Experiment no. 28: 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(); 74
  • 75. } public void mousePressed(MouseEvent me) { mx=30; my=60; msg="Mouse Pressed"; repaint(); } 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); 75
  • 77. 29. Experiment no. 29: 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(); 77
  • 78. 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; } 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 78
  • 79. 30. Experiment no. 30: 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); } } 79
  • 81. 31. Experiment no. 31: 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); 81
  • 82. } public void actionPerformed(ActionEvent ae) { if(ae.getActionCommand()=="CSE") { 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 82
  • 83. References: 1. The complete reference Java, J2SE 5th edition, Herbert Schild, TMH publishing Company limited, New Delhi. 2. Big Java 2nd edition, Cay Horstmann, John Wiley and Sons. 3. Java how to programme, sixth edition, H.M.Dietel and P.J. Deitel. 4. Core java 2,Vol2, Advanced Fundamentals Cay, S. Horshmann and Gary Comell Seventh edition Person edition. 83