Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Java index
Core Java
Core Java : What is it?
Java (with a capital J) is a high-level, third generation programming language,expressly
designed for use
in the distributed environment of the Internet. It was designed to have the "look and feel" of
the C++ language, but it is simpler to use than C++ and enforces an object-oriented
programming model. Java can be used to create complete applications that may run on a
single computer or be distributed among servers and clients in a network. It can also be used
to build a small application module or applet for use as part of a Web page. Applets make it
possible for a Web page user to interact with the page.
Core Java : What it does?
The general-purpose, high-level Java programming language is a powerful software platform. Every full
implementation of the Java platform gives you the following features: Development Tools: The development
tools provide everything you'll need for compiling, running, monitoring, debugging, and documenting your
applications. As a new developer, the main tools you'll be using are the javac compiler, the java launcher, and
the javadoc documentation tool. Application Programming Interface (API): The API provides the core
functionality of the Java programming language. It offers a wide array of useful classes ready for use in your
own applications. Deployment Technologies: The JDK software provides standard mechanisms such as the Java
Web Start software and Java Plug-In software for deploying your applications to end users. User Interface
Toolkits: The Swing and Java 2D toolkits make it possible to create sophisticated Graphical User Interfaces
(GUIs). Integration Libraries: Integration libraries such as the Java IDL API, JDBCTM API, Java Naming and
Directory InterfaceTM ("J.N.D.I.") API, Java RMI, and Java Remote Method Invocation over Internet Inter-
Contact us :- 9313565406, 65495934
1
ORB Protocol Technology (Java RMI-IIOP Technology) enable database access and manipulation of remote
objects
Why Core Java ?
Java has been tested, refined, extended, and proven by a dedicated community. And
numbering more than 6.5 million developers, it's the largest and most active on the planet.
With its versatilty, efficiency, and portability, Java has become invaluable to developers by
enabling them to:
• Write software on one platform and run it on virtually any other platform
• Create programs to run within a Web browser and Web services
• Develop server-side applications for online forums, stores, polls, HTML forms processing, and more
• Combine applications or services using the Java language to create highly customized applications
or services
• Write powerful and efficient applications for mobile phones, remote processors, low-cost consumer
products, and practically any other device with a digital heartbeat
What You Should Know?
•Person with a basic knowledge of OOPs can opt for Core Java.
• Basic knowledge of RDBMS (Relational Database Management System).
Java is a Platform
Java (with a capital J) is a platform for application development. A platform is a loosely defined
computer industry buzzword that typically means some combination of hardware and system software
that will mostly run all the same software. For instance PowerMacs running Mac OS 9.2 would be one
platform. DEC Alphas running Windows NT would be another.
There's another problem with distributing executable programs from web pages. Computer programs
are very closely tied to the specific hardware and operating system they run. A Windows program will
not run on a computer that only runs DOS. A Mac application can't run on a Unix workstation. VMS
code can't be executed on an IBM mainframe, and so on. Therefore major commercial applications
like Microsoft Word or Netscape have to be written almost independently for all the different
platforms they run on. Netscape is one of the most cross-platform of major applications, and it still
only runs on a minority of platforms.
Java solves the problem of platform-independence by using byte code. The Java compiler does not
produce native executable code for a particular machine like a C compiler would. Instead it produces
a special format called byte code. Java byte code written in hexadecimal, byte by byte, looks like this:
CA FE BA BE 00 03 00 2D 00 3E 08 00 3B 08 00 01 08 00 20 08
Java is Simple
Java was designed to make it much easier to write bug free code. According to Sun's Bill Joy, shipping C code
has, on average, one bug per 55 lines of code. The most important part of helping programmers write bug-free
code is keeping the language simple. Java has the bare bones functionality needed to implement its rich
Contact us :- 9313565406, 65495934
2
feature set. It does not add lots of syntactic sugar or unnecessary features. Despite its simplicity, Java has
considerably more functionality than C, primarily because of the large class library.
Java is Object-Oriented
Object oriented programming is the catch phrase of computer programming in the 1990's. Although object
oriented programming has been around in one form or another since the Simula language was invented in the
1960's, it's really begun to take hold in modern GUI environments like Windows, Motif and the Mac. In objectoriented programs data is represented by objects. Objects have two sections, fields (instance variables) and
methods. Fields tell you what an object is. Methods tell you what an object does. These fields and methods are
closely tied to the object's real world characteristics and behavior. When a program is run messages are
passed back and forth between objects. When an object receives a message it responds accordingly as defined
by its methods.
Object oriented programming is alleged to have a number of advantages including:
Simpler, easier to read programs
More efficient reuse of code
Faster time to market
More robust, error-free code
Java is Platform Independent
Java was designed to not only be cross-platform in source form like C, but also in compiled binary form. Since
this is frankly impossible across processor architectures Java is compiled to an intermediate form called bytecode. A Java program never really executes natively on the host machine. Rather a special native program
called the Java interpreter reads the byte code and executes the corresponding native machine instructions.
Thus to port Java programs to a new platform all that is needed is to port the interpreter and some of the
library routines. Even the compiler is written in Java. The byte codes are precisely defined, and remain the
same on all platforms.
Java is Safe
Java was designed from the ground up to allow for secure execution of code across a network, even when the
source of that code was untrusted and possibly malicious.
Java is High Performance
Java byte codes can be compiled on the fly to code that rivals C++ in speed using a "just-in-time compiler."
Several companies are also working on native-machine-architecture compilers for Java. These will produce
executable code that does not require a separate interpreter, and that is indistinguishable in speed from C++.
.
Java is Multi-Threaded
Java is inherently multi-threaded. A single Java program can have many different threads executing
independently and continuously. Three Java applets on the same page can run together with each getting
equal time from the CPU with very little extra effort on the part of the programmer.
Java is Dynamic(ly linked)
Java does not have an explicit link phase. Java source code is divided into .java files, roughly one per each class
in your program. The compiler compiles these into .class files containing byte code. Each .java file generally
produces exactly one .class file.
Java is Garbage Collected
Contact us :- 9313565406, 65495934
3
You do not need to explicitly allocate or deallocate memory in Java. Memory is allocated as needed, both on
the stack and the heap, and reclaimed by the garbage collector when it is no longer needed. There's no
malloc(), free(), or destructor methods.
There are constructors and these do allocate memory on the heap, but this is transparent to the programmer.
The Hello World Application
class HelloWorld
{
public static void main (String args[])
{
System.out.println("Hello JAVA World!");
}
}
Save this code in a file called HelloWorld.java. Use exactly that name including case. Congratulations! You've
written your first Java program.
Compiling and Running Hello World
Under Windows, it's similar. You just do this in a DOS shell.
C:> javac HelloWorld.java
C:> java HelloWorld
Hello JAVA World
C:>
Example. Variable declaration inside for loop.
class Count {
public static void main (String args[]) {
for (int i = 0; i < 50; i = i+1) {
System.out.println(i);
}
}
}
Increment and decrement operators
Java has ++ and -- operators like C.
class Count {
public static void main (String args[]) {
for (int i = 0; i < 50; i++) {
System.out.println(i);
}
}
}
Contact us :- 9313565406, 65495934
4
Java Operators
They are used to manipulate primitive data types. Java operators can be classified as unary,
binary, or ternary—meaning taking one, two, or three arguments, respectively. A unary
operator may appear
before (prefix) its argument or after (postfix) its argument. A binary or ternary operator
appears between its arguments.
Assignment Operators
=
Arithmetic Operators
+
*
Relational Operators
> <
>=
Logical Operators
&&
||
&
Bit wise Operator
&
|
^ >>
Compound Assignment Operators
+=
Conditional Operator
/
%
<=
| !
>>>
-=
++
==
^
-!=
*=
<<=
/=
%=
>>= >>>=
?:
Operator Precedence
The order in which operators are applied is known as precedence. Operators with a higher
precedence are applied before operators with a lower precedence. The operator precedence
order of Java is shown below. Operators at the top of the table are applied before operators
lower down in the table. If two operators have the same precedence, they are applied in the
order they appear in a statement.
Java language supports few special escape sequences for String and char literals as well.
They are:
Contact us :- 9313565406, 65495934
5
Unicode
You can refer to a particular Unicode character by using the escape sequence \u followed by a four digit
hexadecimal number. For example
\u00A9
©
The copyright symbol
\u0022
"
The double quote
\u00BD
½
The fraction 1/2
\u0394
Δ
The capital Greek letter delta
\u00F8
�d>
A little o with a slash through it
Primitive Data Types in Java
Java's primitive data types are very similar to those of C. They include boolean, byte, short, int, long, float, double,
and char. The boolean type has been added. However, the implementation of the data types has been
substantially cleaned up in several ways.
Keyword
byte
short
int
long
float
double
char
boolean
Description
Byte-length integer
Short integer
Integer
Long integer
Single-precision floating point
Double-precision floating point
A single character
A boolean value (true or false)
Size/Format
8-bit two's complement
16-bit two's complement
32-bit two's complement
64-bit two's complement
32-bit IEEE
64-bit IEEE
16-bit Unicode character
true or false
Literals
Literals are pieces of Java source code that mean exactly what they say. For instance "Hello World!" is a String
literal and its meaning is the words Hello World!
Identifiers in Java
Identifiers are the names of variables, methods, classes, packages and interfaces.
Contact us :- 9313565406, 65495934
6
The following are legal variable names:
MyVariable
myvariable
MYVARIABLE
_myvariable
$myvariable
_9pins
andros
ανδρος
The following are not legal variable names:
My Variable // Contains a space
9pins // Begins with a digit
a+c // The plus sign is not an alphanumeric character
testing1-2-3 // The hyphen is not an alphanumeric character
O'Reilly // Apostrophe is not an alphanumeric character
OReilly_&_Associates // ampersand is not an alphanumeric character
Keywords
Keywords are reserved for their intended use and cannot be used by the programmer for variable or method
names. Keywords are identifiers like public, static and class that have a special meaning inside Java source code
and outside of comments and Strings. Four keywords are used in Hello World, public, static, void and class.
Keyword
boolean
declares a boolean variable or return type
byte
declares a byte variable or return type
char
declares a character variable or return type
double
declares a double variable or return type
float
declares a floating point variable or return type
short
declares a short integer variable or return type
void
declare that a method does not return a value
int
declares an integer variable or return type
long
declares a long integer variable or return type
while
begins a while loop
for
begins a for loop
do
begins a do while loop
switch
tests for the truth of various possible cases
break
prematurely exits a loop
continue
prematurely return to the beginning of a loop
case
one case in a switch statement
default
default action for a switch statement
if
execute statements if the condition is true
else
signals the code to be executed if an if statement is not true
try
attempt an operation that may throw an exception
catch
handle an exception
finally
declares a block of code guaranteed to be executed
class
signals the beginning of a class definition
abstract
declares that a class or method is abstract
Contact us :- 9313565406, 65495934
7
extends
specifies the class which this class is a subclass of
final
declares that a class may not be subclassed or that a field or method may not be overridden
implements
declares that this class implements the given interface
import
permit access to a class or group of classes in a package
instanceof
tests whether an object is an instanceof a class
interface
signals the beginning of an interface definition
native
declares that a method is implemented in native code
new
allocates a new object
package
defines the package in which this source code file belongs
private
declares a method or member variable to be private
protected
declares a class, method or member variable to be protected
public
declares a class, method or member variable to be public
return
returns a value from a method
static
declares that a field or a method belongs to a class rather than an object
super
a reference to the parent of the current object
synchronized
Indicates that a section of code is not thread-safe
this
a reference to the current object
throw
throw an exception
throws
declares the exceptions thrown by a method
transient
This field should not be serialized
volatile
Warns the compiler that a variable changes asynchronously
Java - Class, Object and Methods in Java
Object : Objects are the basic run time entity or in other words object is
a instance of a class . An object is a software bundle of variables and
related methods of the special class.
Class : Classes are the fundamental building blocks of a Java program.
class Employee
{
int age;
double salary;
}
Fields
public class Employee{
int age;
int salary
}
Contact us :- 9313565406, 65495934
8
1. Field names should follow the camel naming convention.
2. The initial of each word in the field, except for the first word, is written with a capital
letter.
3. For example: age, maxAge, address, validAddress, numberOfRows.
Creating Objects of a Class
class Sphere {
double radius; // Radius of a sphere
Sphere() {
}
// Class constructor
Sphere(double theRadius) {
radius = theRadius; // Set the radius
}
}
public class MainClass {
public static void main(String[] arg){
Sphere sp = new Sphere();
}
}
Class declaration with a method that has a parameter
public class MainClass
{
public static void main( String args[] )
{
GradeBook myGradeBook = new GradeBook();
String courseName = "Java ";
myGradeBook.displayMessage( courseName );
}
}
class GradeBook
{
public void displayMessage( String courseName )
{
System.out.printf( "Welcome to the grade book for\n%s!\n",
courseName );
}
}
Overriding and Hiding Methods
Instance Methods
An instance method in a subclass with the same signature (name, plus the
number and the type of its parameters) and return type as an instance method
in the superclass overrides the superclass's method.
Contact us :- 9313565406, 65495934
9
The ability of a subclass to override a method allows a class to inherit from a
superclass whose behavior is "close enough" and then to modify behavior as
needed. The overriding method has the same name, number and type of
parameters, and return type as the method it overrides. An overriding method
can also return a subtype of the type returned by the overridden method. This is
called a covariant return type.
When overriding a method, you might want to use the @Override annotation
that instructs the compiler that you intend to override a method in the
superclass. If, for some reason, the compiler detects that the method does not
exist in one of the superclasses, it will generate an error.
Class Methods
If a subclass defines a class method with the same signature as a class method
in the superclass, the method in the subclass hides the one in the superclass.
The distinction between hiding and overriding has important implications. The
version of the overridden method that gets invoked is the one in the subclass.
The version of the hidden method that gets invoked depends on whether it is
invoked from the superclass or the subclass. Let's look at an example that
contains two classes. The first is Animal, which contains one instance method
and one class method:
public class Animal {
public static void testClassMethod() {
System.out.println("The class" +
" method in Animal.");
}
public void testInstanceMethod() {
System.out.println("The instance "
+ " method in Animal.");
}
}
The second class, a subclass of Animal, is called Cat:
public class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The class method" +
" in Cat.");
}
public void testInstanceMethod() {
System.out.println("The instance method" +
" in Cat.");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
Animal.testClassMethod();
myAnimal.testInstanceMethod();
Contact us :- 9313565406, 65495934
10
}
}
The Cat class overrides the instance method in Animal and hides the class
method in Animal. The main method in this class creates an instance of Cat and
calls testClassMethod() on the class and testInstanceMethod() on the instance.
The output from this program is as follows:
The class method in Animal.
The instance method in Cat.
As promised, the version of the hidden method that gets invoked is the one in
the superclass, and the version of the overridden method that gets invoked is
the one in the subclass.
Modifiers
The access specifier for an overriding method can allow more, but not less,
access than the overridden method. For example, a protected instance method
in the superclass can be made public, but not private, in the subclass.
You will get a compile-time error if you attempt to change an instance method in
the superclass to a class method in the subclass, and vice versa.
Java Flow Control
if
else
else if
for
switch case
continue
while
do while
break
The if statement in Java
All programming languages have some form of an if statement that tests conditions. In the previous code you
should have tested whether there actually were command line arguments before you tried to use them.
class Hello {
public static void main (String args[]) {
if (args.length > 0) {
System.out.println("Hello " + args[0]);
}
}
}
The else statement in Java
class Hello {
Contact us :- 9313565406, 65495934
11
public static void main (String args[]) {
if (args.length > 0) {
System.out.println("Hello " + args[0]);
}
else {
System.out.println("Hello whoever you are.");
}
}
Else If
if statements are not limited to two cases. You can combine an else and an if to make an else if and test a whole
range of mutually exclusive possibilities. For instance, here's a version of the Hello program that handles up to
four names on the command line:
// This is the Hello program in Java
class Hello {
public static void main (String args[]) {
if (args.length == 0) {
System.out.println("Hello whoever you are");
}
else if (args.length == 1) {
System.out.println("Hello " + args[0]);
}
else if (args.length == 2) {
System.out.println("Hello " + args[0] + " " + args[1]);
}
else if (args.length == 3) {
System.out.println("Hello " + args[0] + " " + args[1] + " " + args[2]);
}
else if (args.length == 4) {
System.out.println("Hello " + args[0] +
" " + args[1] + " " args[2] + " " + args[3]);
}
else {
System.out.println("Hello " + args[0] + " " + args[1] + " " args[2]
+ " " + args[3] + " and all the rest!");
}
}
}
The while loop in Java
// This is the Hello program in Java
class Hello {
public static void main (String args[]) {
System.out.print("Hello "); // Say Hello
int i = 0; // Declare and initialize loop counter
while (i < args.length) { // Test and Loop
System.out.print(args[i]);
Contact us :- 9313565406, 65495934
12
System.out.print(" ");
i = i + 1; // Increment Loop Counter
}
System.out.println(); // Finish the line
}
The for loop in Java
// This is the Hello program in Java
class Hello {
public static void main (String args[]) {
System.out.print("Hello "); // Say Hello
for (int i = 0; i < args.length; i = i + 1) { // Test and Loop
System.out.print(args[i]);
System.out.print(" ");
}
System.out.println(); // Finish the line
}
}
The do while loop in Java
// This is the Hello program in Java
class Hello {
public static void main (String args[]) {
int i = -1;
do {
if (i == -1) System.out.print("Hello ");
else {
System.out.print(args[i]);
System.out.print(" ");
}
i = i + 1;
} while (i < args.length);
System.out.println(); // Finish the line
}
}
Booleans
Booleans are named after George Boole, a nineteenth century logician. Each boolean variable has one of two
values, true or false. These are not the same as the Strings "true" and "false".
boolean test1 = true;
boolean test2 = false;
Continue
For these purposes Java provides the break and continue statements. A continue statement returns to the
beginning of the innermost enclosing loop without completing the rest of the statements in the body of the loop.
Contact us :- 9313565406, 65495934
13
for (int i = 0; i < m.length; i++) {
if (m[i] % 2 == 0) continue;
// process odd elements...
}
if (m[i] % 2 != 0) {
// process odd elements...
}}
The switch statement in Java
Switch statements are shorthands for a certain kind of if statement. It is not uncommon to see a stack of if
statements all relate to the same quantity like this:
if (x == 0) doSomething0();
else if (x == 1) doSomething1();
else if (x == 2) doSomething2();
else if (x == 3) doSomething3();
else if (x == 4) doSomething4();
else doSomethingElse();
Java has a shorthand for these types of multiple if statements, the switch-case statement. Here's how you'd write
the above using a switch-case:
switch (x)
{
case 0:
doSomething0();
break;
case 1:
doSomething1();
break;
case 2:
doSomething2();
break;
case 3:
doSomething3();
break;
case 4:
doSomething4();
break;
default:
doSomethingElse();
}
The ? : operator in Java
The value of a variable often depends on whether a particular boolean expression is or is not true and on nothing
else. For instance one common operation is setting the value of a variable to the maximum of two quantities. In
Java you might write
if (a > b) {
max = a;
}
else {
max = b;
}
max = (a > b) ? a : b;
Contact us :- 9313565406, 65495934
14
Type Casting
/* Simple Type casting program */
class cast
{
public static void main(String args[])
{
double a=5.35, b=55.6;
int rem;
rem = (int)a% (int)b;
System.out.println("Remainder : "+rem);
}
}
/* Output
Remainder : 5 */
Java Program To Find Whether a Number is Armstrong
class Armstrong
{
int sumcube(int x)
{
int dig,sum = 0;
while(x >= 1)
{
dig = x % 10;
sum = sum + dig * dig * dig;
x = x / 10;
}
return(sum);
}
void display(int n)
{
if(sumcube (n)==n)
System.out.println(n + " is Armstrong Number");
else
System.out.println(n + " is not Armstrong Number");
}
void disp()
{
int x = 0,y = 0;
for(int k = x;k <= y;k++)
if(sumcube (k)==k)
System.out.println(k);
}
}
Contact us :- 9313565406, 65495934
15
The Math Class
While the Math class is quite extensive, we will limit our attention to the
methods listed below for the time being.
Method
Purpose
abs(int x)
Returns the absolute value of an integer x.
abs(double x)
Returns the absolute value of a double x
pow(double base, double exponent)
Returns the base raised to the exponent.
round(double x)
Returns x rounded to the nearest whole number.
Returned value must be cast to an int before
assignment to an int variable.
max(int a, int b)
Returns the greater of a and b.
min(int a, int b)
Returns the lesser of a and b.
double sqrt(double x)
Returns the square root of x.
random( )
Returns a random number greater than or equal to 0.0
and less than 1.0.
These methods are used by invoking the name of the class (Math), followed by a dot (.),
followed by the name of the method and any needed parameters.
SYNTAX:
radius = Math.sqrt(area/Math.PI));
More Examples:
int ans1;
double ans2;
ans1 = Math.abs(-4);
ans1 = Math.abs(-3.6);
//ans1 equals 4
//ans1 equals 3.6
ans2 = Math.pow(2.0,3.0); //ans2 equals 8.0
ans2 = Math.pow(25.0, 0.5); //ans2 equals 5.0
ans1 = Math.max(30,50);
//ans1 equals 50
ans1 = Math.min(30,50);
//ans1 equals 30
ans1 = (int) Math.round(5.66); //ans1 equals 6
Random Number Generation
Computers can be used to simulate the generation of random numbers with the use of the
random( ) method. This random generation is referred to as a pseudo-random generation.
These created values are not truly "random" because a seeded mathematical formula is used
to generate the values.
Remember that the random( ) method will return a value greater than or equal to zero and
less than 1. But don't expect values necessarily like .5 or .25. The following line of code:
double randomNumber = Math.random( );
will most likely generate a number such as 0.7342789374658514. Yeek!
Contact us :- 9313565406, 65495934
16
When you think of random numbers for a game or an activity, you are probably thinking of
random "integers". Let's do a little adjusting to the random( ) method to see if we can create
random integers.
Generating random integers within a specified range:
In order to produce random "integer" values within a specified range, you need to manipulate
the random( ) method.
Obviously, we will need to cast our value to force it to become an integer.
The formula is:
int number = (int) (a + Math.random( ) * (b - a + 1));
a = the first number in your range
b = the last number in your range
(b - a + 1 ) is the number of terms in your range.
(range computed by largest value - smallest value + 1)
Examples:
• random integers in the interval from 1 to 10 inclusive.
int number = (int) (1 + Math.random( ) * 10);
• random integers in the interval from 22 to 54 inclusive.
int number = (int) (1 + Math.random( ) * 33);
note: the number of possible integers from 22 to 54 inclusive is 33
b - a + 1 = 54 - 22 + 1 = 33
Constructors
A constructor is a special method that is used to initialize a newly created object and is called
just after the memory is allocated for the object
1. Every class must have at least one constructor.
2. If there is no constructors for your class, the compiler will supply a default
constructor(no-arg constructor).
3. A constructor is used to construct an object.
4. A constructor looks like a method and is sometimes called a constructor method.
5. A constructor never returns a value
6. A constructor always has the same name as the class.
7. A constructor may have zero argument, in which case it is called a no-argument (or
no-arg, for short) constructor.
8. Constructor arguments can be used to initialize the fields in the object.
public class Cube1 {
Contact us :- 9313565406, 65495934
17
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Cube1() {
length = 10;
breadth = 10;
height = 10;
}
Cube1(int l, int b, int h) {
length = l;
breadth = b;
height = h;
}
public static void main(String[] args) {
Cube1 cubeObj1, cubeObj2;
cubeObj1 = new Cube1();
cubeObj2 = new Cube1(10, 20, 30);
System.out.println("Volume of Cube1 is : " +
cubeObj1.getVolume());
System.out.println("Volume of Cube1 is : " +
cubeObj2.getVolume());
}
}
constructor overloading
class Demo{
int value1;
int value2;
/*Demo(){
value1 = 10;
value2 = 20;
System.out.println("Inside 1st Constructor");
}*/
Demo(int a){
value1 = a;
System.out.println("Inside 2nd Constructor");
}
Demo(int a,int b){
value1 = a;
value2 = b;
System.out.println("Inside 3rd Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
Demo d1 = new Demo();
Demo d2 = new Demo(30);
Demo d3 = new Demo(30,40);
d1.display();
d2.display();
d3.display();
}
}
Contact us :- 9313565406, 65495934
18
Constructor Chaining
Every constructor calls its superclass constructor. An implied super() is therefore included in
each constructor which does not include either the this() function or an explicit super() call as
its first statement. The super() statement invokes a constructor of the super class. The implicit
super() can be replaced by an explicit super(). The super statement must be the first statement
of the constructor. The explicit super allows parameter values to be passed to the constructor
of its superclass and must have matching parameter types A super() call in the constructor of
a subclass will result in the call of the relevant constructor from the superclass, based on the
signature of the call. This is called constructor chaining.
Below is an example of a class demonstrating constructor chaining using super() method.
class Cube {
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Cube() {
this(10, 10);
System.out.println("Finished with Default Constructor of
Cube");
}
Cube(int l, int b) {
this(l, b, 10);
System.out.println("Finished with Parameterized Constructor
having
2
params of Cube");
}
Cube(int l, int b, int h) {
length = l;
breadth = b;
height = h;
System.out.println("Finished with Parameterized Constructor
having
3
params of Cube");
}
}
public class SpecialCube extends Cube {
int weight;
SpecialCube() {
super();
weight = 10;
}
SpecialCube(int l, int b) {
this(l, b, 10);
System.out.println("Finished with Parameterized Constructor
having
2
params of SpecialCube");
}
SpecialCube(int l, int b, int h) {
Contact us :- 9313565406, 65495934
19
super(l, b, h);
weight = 20;
System.out.println("Finished with Parameterized Constructor
having
3
params of SpecialCube");
}
public static void main(String[] args) {
SpecialCube specialObj1 = new SpecialCube();
SpecialCube specialObj2 = new SpecialCube(10,
System.out.println("Volume of SpecialCube1 is
+ specialObj1.getVolume());
System.out.println("Weight of SpecialCube1 is
+ specialObj1.weight);
System.out.println("Volume of SpecialCube2 is
+ specialObj2.getVolume());
System.out.println("Weight of SpecialCube2 is
+ specialObj2.weight);
}
}
20);
: "
: "
: "
: "
Arrays
An array is a container object that holds a fixed number of values of a single type. The length
of an array is established when the array is created. After creation, its length is fixed.
class ArrayDemo {
public static void main(String[] args) {
// declares an array of integers
int[] anArray;
// allocates memory for 10 integers
anArray = new int[10];
// initialize first element
anArray[0] = 100;
// initialize second element
anArray[1] = 200;
// etc.
anArray[2] = 300;
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;
Contact us :- 9313565406, 65495934
20
System.out.println("Element
System.out.println("Element
System.out.println("Element
System.out.println("Element
System.out.println("Element
System.out.println("Element
System.out.println("Element
System.out.println("Element
System.out.println("Element
System.out.println("Element
at
at
at
at
at
at
at
at
at
at
index
index
index
index
index
index
index
index
index
index
0:"+anArray[0]);
1:”+anArray[1]);
2:"+anArray[2]);
3:"+anArray[3]);
4:"+anArray[4]);
5:"+anArray[5]);
6:"+anArray[6]);
7:"+anArray[7]);
8:"+anArray[8]);
9:"+anArray[9]);
}
}
The output from this program is:
Element
Element
Element
Element
Element
Element
Element
Element
Element
Element
at
at
at
at
at
at
at
at
at
at
index
index
index
index
index
index
index
index
index
index
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
100
200
300
400
500
600
700
800
900
1000
Multi-Dimensional Arrays
The most common kind of multidimensional array is the two-dimensional array. If you think of a one-dimensional
array as a column of values, you can think of a two-dimensional array as a table of values like this
Declaring, Allocating and Initializing Two Dimensional Arrays
This example fills a two-dimensional array with the sum of the row and column indexes
class FillArray {
public static void main (String args[]) {
int[][] matrix;
matrix = new int[4][5];
for (int row=0; row < 4; row++) {
for (int col=0; col < 5; col++) {
matrix[row][col] = row+col;
} } } }
class IDMatrix {
public static void main (String args[]) {
double[][] id;
id = new double[4][4];
for (int row=0; row < 4; row++) {
for (int col=0; col < 4; col++) {
if (row != col) {
id[row][col]=0.0;
}
Contact us :- 9313565406, 65495934
21
else {
id[row][col] = 1.0;
} } } }
}
Matrices - Two-dimensional arrays
import java.io.*;
import BreezyGUI.*;
public class matrixtest
{
public static void main(String[] args)
{
double [ ] [ ] grades = new double [ 30 ] [ 4 ] ; //create memory space for entire matrix
// Fill the matrix with user input and compute average
int row, column;
double sum, average;
for ( row = 0; row < 3; row ++ )
{
sum = 0;
for(column = 0; column < 3; column++)
{
grades[row][column] = Console.readDouble("Enter grade " + (column +1) +
"for student " +
(row+1));
sum = sum + grades[row][column];
}
average = sum / 3;
grades[row][3] = average;
}
// Print averages only
System.out.println("You saved the following averages: ");
for( row = 0; row < 3; row ++ )
{
System.out.println("Student " + (row + 1) + ": " + grades[row][3]);
}
}
}
Passing Arrays to Methods
(pass-by-reference)
Contact us :- 9313565406, 65495934
22
When discussing arguments/parameters and methods, we talked about passing-by-value.
Copies of argument values are sent to the method, where the copy is manipulated and in
certain cases, one value may be returned. While the copied values may change in the
method, the original values in main did not change (unless purposely reassigned after the
method).
The situation, when working with arrays, is somewhat different. If we were to make copies
of arrays to be sent to methods, we could potentially be copying very large amounts of data.
Not very efficient!
Arrays are passed-by-reference. Passing-by-reference means that when an array is passed as
an argument, its memory address location is actually passed, referred to as its "reference".
In this way, the contents of an array CAN be changed inside of a method, since we are
dealing directly with the actual array and not with a copy of the array.
int [ ] num = {1, 2, 3};
testingArray(num); //Method call
System.out.println("num[0] = " + num[0] + "\n num[1] = " + num[1] + "\n num[2] =" + num[2]);
...
//Method for testing
public static void testingArray(int[ ] value)
{
value[0] = 4;
value[1] = 5;
value[2] = 6;
}
Output:
num[0] = 4
num[1] = 5
num[2] = 6
(The values in the array have been changed.
Notice that nothing was "returned".)
Example:
Fill an array with 10 integer values. Pass the array to a method that
will add up the values and return the sum. (In this example, no original data in the array
was altered. The array information was simply used to find the sum.)
import java.io.*;
import BreezyGUI.*;
public class FindSum
{
public static void main (String [ ] args)
{
int [ ] number = new int [ 10]; // instantiate the array
int i;
int sum=0;
for ( i = 0; i < 10; i++ )
// fill the array
number[ i ] = Console.readInt("Enter number: " );
int sum = find_sum(number); // invoke the method
System.out.println("The sum is" +sum + ".");
}
public static int find_sum(int [ ] value) //method definition to find sum
{
Contact us :- 9313565406, 65495934
23
int i, total = 0;
for(i=0; i<10; i++)
{
total = total + value[ i ];
}
return (total);
}
Searching for a Specific Value
// Search for the number 31 in a set of integers
// This search takes place in main.
// This search could also have been placed in a method.
public class BreakBooleanDemo
{
public static void main(String[ ] args)
{
int[ ] numbers = { 12, 13, 2, 33, 23, 31, 22, 6, 87, 16 };
int key = 31;
int i = 0;
boolean found = false;
// set the boolean value to false until the key is found
for ( i = 0; i < numbers.length; i++)
{
if (numbers[ i ] == key)
{
found = true;
break;
}
}
if (found) //When found is true, the index of the location of key will be printed.
{
System.out.println("Found " + key + " at index " + i + ".");
}
else
{
System.out.println(key + "is not in this array.");
}
}
}
Binary Search
import java.io.*;
import BreezyGUI.*;
public class BinarySearchExample
{
public static void main(String[] args)
{
int key = 77;
int[ ] num = new int [10];
// Fill the array
for (int i = 0; i < 10; i++)
Contact us :- 9313565406, 65495934
24
num[ i ]=Console.readInt("Enter integer: ");
//The binary search method
binarySearch (num, 0, 9, key);
}
//Binary Search Method
// This method accepts a pre-sorted array, the subscript of the starting element for the search,
// the subscript of the ending element for the search,
// and the key number for which we are searching.
public static void binarySearch(int[ ] array, int lowerbound, int upperbound, int key)
{
int position;
int comparisonCount = 1; // counting the number of comparisons (optional)
// To start, find the subscript of the middle position.
position = ( lowerbound + upperbound) / 2;
while((array[position] != key) && (lowerbound <= upperbound))
{
comparisonCount++;
if (array[position] > key)
// If the number is > key, ..
{
// decrease position by one.
upperbound = position - 1;
}
else
{
lowerbound = position + 1; // Else, increase position by one.
}
position = (lowerbound + upperbound) / 2;
}
if (lowerbound <= upperbound)
{
System.out.println("The number was found in array subscript" + position);
System.out.println("The binary search found the number after " + comparisonCount +
"comparisons.");
// printing the number of comparisons is optional
}
else
System.out.println("Sorry, the number is not in this array. The binary search made "
+comparisonCount + " comparisons.");
}
}
Sorting
There are many times when it is necessary to put an array in order from highest to lowest
(descending) or vice versa (ascending). Because sorting arrays requires exchanging values,
computers must use a special technique to swap the positions of array elements so as not to
lose any elements.
// Bubble Sort Method for Descending Order
public static void BubbleSort( int [ ] num )
{
int j;
Contact us :- 9313565406, 65495934
25
boolean flag = true; // set flag to true to begin first pass
int temp; //holding variable
while ( flag )
{
flag= false; //set flag to false awaiting a possible swap
for( j=0; j < num.length -1; j++ )
{
if ( num[ j ] < num[j+1] ) // change to > for ascending sort
{
temp = num[ j ];
//swap elements
num[ j ] = num[ j+1 ];
num[ j+1 ] = temp;
flag = true;
//shows a swap occurred
}
}
}
}
Selection Sort
public static void SelectionSort ( int [ ] num )
{
int i, j, first, temp;
for ( i = num.length - 1; i > 0; i - - )
{
first = 0; //initialize to subscript of first element
for(j = 1; j <= i; j ++) //locate smallest element between positions 1 and i.
{
if( num[ j ] < num[ first ] )
first = j;
}
temp = num[ first ]; //swap smallest found with element in position i.
num[ first ] = num[ i ];
num[ i ] = temp;
}
}
Insertion Sort
public static void InsertionSort( int [ ] num)
{
int j;
// the number of items sorted so far
int key;
// the item to be inserted
int i;
for (j = 1; j < num.length; j++)
{
Contact us :- 9313565406, 65495934
// Start with 1 (not 0)
26
key = num[ j ];
for(i = j - 1; (i >= 0) && (num[ i ] < key); i--) // Smaller values are moving up
{
num[ i+1 ] = num[ i ];
}
num[ i+1 ] = key; // Put the key in its proper location
}
}
Implementation of Matrix Operation Using Arrays *********/
// Matrix Addtion, Subtraction, Transpose, Multiplication
class Matrix
{
public static void main(String args[])
{
int i,j,k;
int mat1 [][]={ {1,2,3}, {4,5,6}, {7,8,9} };
int mat2 [][]={ {10,11,12}, {13,14,15}, {16,17,18} };
//Matrix A
System.out.println("\nMatrix A:");
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
System.out.print("\t"+mat1[i][j]);
System.out.println("");
}
//Matrix B
System.out.println("\nMatrix B:");
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
System.out.print("\t"+mat2[i][j]);
System.out.println("");
}
System.out.println("\nOperation ON Matrices \n1.Addition \n");
int sum [][] = new int [3][3];
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
{
sum[i][j] = mat1[i][j] + mat2[i][j];
System.out.print("\t" + sum[i][j]);
}
System.out.println("");
Contact us :- 9313565406, 65495934
27
}
System.out.println("2.Subtraction\n");
int diff[][] = new int[3][3];
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
{
diff [i][j] = mat1[i][j] - mat2[i][j];
System.out.print("\t"+ diff[i][j]);
}
System.out.println("");
}
System.out.println("3. Transpose Of A\n");
int trans[][] = new int[3][3];
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
{
trans [i][j] = mat1[j][i];
System.out.print("\t"+ trans[i][j]);
}
System.out.println("");
}
System.out.println("4.Multiplication\n");
int prod[][] = new int[3][3];
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
{
prod[i][j] = 0;
{
for(k=0;k< 3;k++)
prod[i][j] = prod[i][j]+mat1[i][k]*mat2[k][j];
}
System.out.print("\t"+ prod[i][j]);
}
System.out.println("");
}
}
}
Length Convertor
Contact us :- 9313565406, 65495934
28
/* (Length Convertor): Simple Java Program to convert miles, kilometers, meter, feet,
centimeter and inches
*/
Enter value for Miles: 45
Kilometer: 72.4185
Meter: 72418.5
Feet: 237593.50429815002
Inches: 2851122.0515778
Centimeter: 7241850.011007612
import java.io.*;
public class ConverterIO
{
public static void main(String[] args) throws IOException
{
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
String strChoose;
int choose;
String strMiles, strKilometer, strMeter, strFeet, strInches, strCentimeter;
double miles, kilometer, meter,feet, inches, centimeter;
boolean done = false;
while (!done)
{
//Getting input from the user
println("\n\n\n\t\tLENGTH CONVERTER");
println("\n\tWhat you would like to convert?");
println("");
println("\t1) Miles 4) Feet");
println("\t2) Kilometer 5) Inches");
println("\t3) Meter 6) Centimeter");
println("\t\t 7) Exit");
print("\n\tEnter your choice: ");
strChoose = dataIn.readLine();
choose = Integer.parseInt(strChoose);
if ((choose < = 0) || (choose >= 8))
{
println("\tInvalid entry, please try again!");
}
switch (choose)
{
case 1:
print("\n\tEnter value for Miles: ");
strMiles = dataIn.readLine();
miles = Double.parseDouble(strMiles);
println("\n\t\tKilometer: " + (miles*1.6093));
Contact us :- 9313565406, 65495934
29
println("\t\tMeter: " + (miles*1609.3));
println("\t\tFeet: " + (miles*5279.85565107));
println("\t\tInches: " + (miles*63358.26781284));
println("\t\tCentimeter: " + (miles*160930.0002446136));
break;
case 2:
print("\n\tEnter value for Kilometer: ");
strKilometer = dataIn.readLine();
kilometer = Double.parseDouble(strKilometer);
println("\n\t\tMiles: " + (kilometer*0.6213882));
println("\t\tMeter: " + (kilometer*1000));
println("\t\tFeet: " + (kilometer*3280.8399));
println("\t\tInches: " + (kilometer*39370.0788));
println("\t\tCentimeter: " + (kilometer*100000)); break;
case 3:
print("\n\tEnter value for Meter: ");
strMeter = dataIn.readLine();
meter = Double.parseDouble(strMeter);
println("\n\t\tMiles: " + (meter*621.3882));
println("\t\tKilometer: " + (meter*1000));
println("\t\tFeet: " + (meter*3.2808399));
println("\t\tInches: " + (meter*39.3700788));
println("\t\tCentimeter: " + (meter*100));
break;
case 4:
print("\n\tEnter value for Feet: ");
strFeet = dataIn.readLine();
feet = Double.parseDouble(strFeet);
println("\n\t\tMiles: " + (feet*0.0001893991176));
println("\t\tKilometer: " + (feet*0.0003048));
println("\t\tMeter: " + (feet*0.3048));
println("\t\tInches: " + (feet*12));
println("\t\tCentimeter: " + (feet*30.48));
break;
case 5:
print("\n\tEnter value for Inches: ");
strInches = dataIn.readLine();
inches = Double.parseDouble(strInches);
println("\n\t\tMiles: " + (inches*0.000015783254));
println("\t\tKilometer: " + (inches*0.000025349));
println("\t\tMeter: " + (inches*0.02534));
println("\t\tFeet: " + (inches*0.08333));
println("\t\tCentimeter: " + (inches*2.51));
break;
case 6:
print("\n\tEnter value for Centimeter: ");
Contact us :- 9313565406, 65495934
30
strCentimeter = dataIn.readLine();
centimeter = Double.parseDouble(strCentimeter);
println("\n\t\tMiles: " + (centimeter*0.000006218797));
println("\t\tKilometer: " + (centimeter*0.000004));
println("\t\tMeter: " + (centimeter*0.004));
println("\t\tFeet: " + (centimeter*0.032808386877));
println("\t\tInches: " + (centimeter*0.3937008));
break;
case 7:
done = true;
println("\n\tThank you for using this program!");
println("\n\n");
break;
default: throw new NumberFormatException();
} // end switch
} // end while
} // end main
//short cut for print
private static void print(String s)
{
System.out.print(s);
}
//short cut for println
private static void println(String s)
{
System.out.println(s);
}
}
String
Strings, which are widely used in Java programming, are a sequence of
characters. In the Java programming language, strings are objects.
String str = "abc";
1.
2.
3.
4.
In Java, ordinary strings are objects of the class String.
A String object represents a string, i.e. a piece of text.
String is a sequence of Unicode characters.
A string literal is a sequence of characters between double quotes.
Contact us :- 9313565406, 65495934
31
5. String objects are immutable.
public class MainClass
{
public static void main( String args[] )
{
char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y
' };
String s = new String( "hello" );
// use
String
String
String
String
String constructors
s1 = new String();
s2 = new String( s );
s3 = new String( charArray );
s4 = new String( charArray, 6, 3 );
System.out.printf("s1 = %s\ns2 = %s\ns3 = %s\ns4 = %s\n",
s1, s2, s3, s4 );
}
}
Java Compare String (== operator)
public class stringmethod{
public static void main(String[] args){
String string1 = "Hi";
String string2 = new String("Hello");
if (string1 == string2) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are unequal.");
}
}
}
Creation of StringBuffer
public class StringBufferExample{
public static void main(String[] args) {
StringBuffer strBuffer1 = new StringBuffer("Bonjour");
StringBuffer strBuffer2 = new StringBuffer(60);
StringBuffer strBuffer3 = new StringBuffer();
System.out.println("strBuffer1 : " +strBuffer1);
System.out.println("strBuffer2 capacity : " +strBuffer2.capacity());
System.out.println("strBuffer3 capacity : " +strBuffer3.capacity());
}
}
String replaceFirst() Method
public class ReplaceFirstDemo {
public static void main(String[] args) {
String str = "Her name is Tamana and Tamana is a good girl.";
String strreplace = "Sonia";
Contact us :- 9313565406, 65495934
32
String result = str.replaceFirst("Tamana", strreplace);
System.out.println(result);
}
}
Important String Methods
Following are most commonly used methods in the String class.
1. public String concat(String s)
This method returns a string with the value of string passed in to the method appended to the
end of String which used to invoke the method.
String s="abcdefg";
System.out.println(s.concat("hijlk"));
2.public charAt(int index)
This method returns a specific character located at the String's specific
index.Remember,String indexes are zero based.Example
String s="Alfanso Mango";
System.out.println(s.charAt(0));
The output is 'A'
3.public int length()
This method returns the length of the String used to invoke the method.example:String s="name";
System.out.println(s.length());
The output is 4
4.public String replace(char old,char new)
This method return a String whose value is that of the String to invoke the method ,updated
so that any occurrence of the char in the first argument is replaced by the char in the second
argument .Example:String s="VaVavavav";
System.out.println(s.replace('v','V'));
The output is VaVaVaVaV
5.public boolean equalsIgnoreCase(String s)
This method returns a boolean value depending on whether the value of the string in the
argument is the same as the String used to invoke the method.This method will return true
Contact us :- 9313565406, 65495934
33
even when character in the string object being compared have different cases.Example:String s="Vaibhav";
System.out.println(s.equalsIgnoreCase("VAIBHAV"));
The output is true
6.public String substring(int begin) / public String substring(int begin,int end)
substring method is used to return a part or substring of the String used to invoke the
method.The first argument represents the starting location of the substring.Remember the
indexes are zero based.example:String s="abcdefghi";
System.out.println(s.substring(5));
System.out.println(s.substring(5,8));
The output would be
" fghi "
" fg "
7.public String toLowerCase()
This method returns a string whose value is the String used to invoke the method,but with
any uppercase converted to lowercase.:String s="AbcdefghiJ";
System.out.println(s.toLowerCase());
Output is " abcdefghij "
8.public String trim()
This method returns a String whose value is the String used to invoke the method ,but with
any leading or trailing blank spaces removed.Example:String s="hey here is the blank space ";
System.out.println(s.trim())
The output is " heyhereistheblankspace"
9.public String toUpperCase()
This method returns a String whose value is String used to invoke the method ,but with any
lowercase character converted to uppercase.Example:String s="AAAAbbbbb";
System.out.println(s.to UpperCase());
The output is " aaaabbbbb "
Contact us :- 9313565406, 65495934
34
Above mentioned String methods are most commonly used in String class.Do remember
them or otherwise I am always up for you and of course you can refer this site every time you
need something.
Java Count Vowels
import java.lang.String;
import java.io.*;
import java.util.*;
public class CountVowels{
public static void main(String args[])throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the String:");
String text = bf.readLine();
int count = 0;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c=='a' || c=='e' || c=='i' || c=='o' || c=='u') {
count++;
}
}
System.out.println("There are" + " " + count + " " + "vowels");
}
}
String substring(int beginIndex, int endIndex)
public class StringSearch{
public static void main(String args[]){
String s = "Bonjour";
//String begin = 3;
//String end = 7;
String t = s.substring(3, 7);
System.out.println(t);
}
}
Banners
import java.io.*;
public class banners1
{
public static void main(String[ ] args) throws InterruptedException
{
String message = "Java";
for (int k=0; k < message.length( ); k++)
{
System.out.print(message.charAt(k)+ " ");
Contact us :- 9313565406, 65495934
35
Thread.sleep (1000 /* millisec */);
}
}
}
Alphabetic Sorting
public class AlphaSortingBubble
{
public static void main(String[ ] args)
{
String[ ] names = {"joe", "slim", "ed", "george"};
sortStringBubble (names);
for ( int k = 0; k < 4; k++ )
System.out.println( names [ k ] );
}
public static void sortStringBubble( String x [ ] )
{
int j;
boolean flag = true; // will determine when the sort is finished
String temp;
while ( flag )
{
flag = false;
for ( j = 0; j < x.length - 1; j++ )
{
if ( x [ j ].compareToIgnoreCase( x [ j+1 ] ) > 0 )
{
// ascending sort
temp = x [ j ];
x [ j ] = x [ j+1]; // swapping
x [ j+1] = temp;
flag = true;
}
}
}
}
}
Exchange Sort:
public class AlphaSortingExchange
{
public static void main(String[ ] args)
{
String[ ] names = {"joe", "slim", "ed", "george"};
sortStringExchange (names);
for ( int k = 0; k < 4; k++ )
System.out.println( names [ k ] );
}
public static void sortStringExchange( String x [ ] )
{
Contact us :- 9313565406, 65495934
36
int i, j;
String temp;
for ( i = 0; i < x.length - 1; i++ )
{
for ( j = i + 1; j < x.length; j++ )
{
if ( x [ i ].compareToIgnoreCase( x [ j ] ) > 0 )
{
// ascending sort
temp = x [ i ];
x [ i ] = x [ j ]; // swapping
x [ j ] = temp;
}
}
}
}
}
Inheritance
Definitions:
A class that is derived from another class is called a subclass (also a derived class, extended
class, or child class). The class from which the subclass is derived is called a superclass (also
a base class or a parent class).
Excepting Object, which has no superclass, every class has one and only one direct
superclass (single inheritance). In the absence of any other explicit superclass, every class is
implicitly a subclass of Object.
Classes can be derived from classes that are derived from classes that are derived from
classes, and so on, and ultimately derived from the topmost class, Object. Such a class is said
to be descended from all the classes in the inheritance chain stretching back to Object.
The following kinds of inheritance are there in java.
Simple Inheritance
Multilevel Inheritance
Multiple Inheritance
Contact us :- 9313565406, 65495934
37
Simple Inheritance
class A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
}
}
class B extends A{
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}
void display(){
System.out.println("B");
}
}
Multilevel Inheritance
class A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
}
}
class B extends A{
void Showb(){
System.out.println("B");
}
}
class C extends B{
Contact us :- 9313565406, 65495934
38
void display(){
System.out.println("C");
}
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}
}
Multiple Inheritance
The mechanism of inheriting the features of more than one base class into a single class is
known as multiple inheritance. Java does not support multiple inheritance but the multiple
inheritance can be achieved by using the interface.
In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more
than one interfaces in a class.
Simple Inheritance using super
class A{
int a;
int b;
int c;
A(int p, int q, int r){
a=p;
b=q;
c=r;
}
}
class B extends A{
int d;
B(int l, int m, int n, int o){
super(l,m,n);
d=o;
}
void Show(){
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
public static void main(String args[]){
B b = new B(4,3,8,7);
b.Show();
}
}
Interfaces
Contact us :- 9313565406, 65495934
39
An interface in the Java programming language is an abstract type that is used to specify an
interface (in the generic sense of the term) that classes must implement. Interfaces are
declared using the interface keyword, and may only contain method signature and constant
declarations (variable declarations that are declared to be both static and final). An
interface may never contain method definitions.
Interfaces cannot be instantiated. A class that implements an interface must implement all of
the methods described in the interface, or be an abstract class. Object references in Java may
be specified to be of an interface type; in which case, they must either be null, or be bound to
an object that implements the interface.
Defining an interface
[visibility] interface InterfaceName [extends other interfaces] {
constant declarations
abstract method declarations
}
public interface Predator {
boolean chasePrey(Prey p);
void eatPrey(Prey p);
}
Interface Usage Example
interface Act {
void act();
}
class Actor1 implements Act {
public void act() {
System.out.println("To be, or not to be");
}
}
class Actor2 implements Act {
public void act() {
System.out.println("Wherefore art thou Romeo?");
}
}
public class TryOut {
public static void main(String args[]) {
Actor1 hamlet = new Actor1();
Actor2 juliet = new Actor2();
tryout(hamlet);
tryout(juliet);
}
private static void tryout(Act actor) {
actor.act();
}
}
Multiple interfaces
Contact us :- 9313565406, 65495934
40
interface CanFight {
void fight();
}
interface CanSwim {
void swim();
}
interface CanFly {
void fly();
}
class ActionCharacter {
public void fight() {
}
}
class Hero extends ActionCharacter implements CanFight, CanSwim, CanFly {
public void swim() {
}
public void fly() {
}
}
public class Adventure {
public static void t(CanFight x) {
x.fight();
}
public static void u(CanSwim x) {
x.swim();
}
public static void v(CanFly x) {
x.fly();
}
public static void w(ActionCharacter x) {
x.fight();
}
public static void main(String[] args) {
Hero h = new Hero();
t(h); // Treat it as a CanFight
u(h); // Treat it as a CanSwim
v(h); // Treat it as a CanFly
w(h); // Treat it as an ActionCharacter
}
}
Multiple Inheritance using Interfaces
/* Area Of Rectangle and Triangle using Interface * /
interface Area
{
float compute(float x, float y);
Contact us :- 9313565406, 65495934
41
}
class Rectangle implements Area
{
public float compute(float x, float y)
{
return(x * y);
}
}
class Triangle implements Area
{
public float compute(float x,float y)
{
return(x * y/2);
}
}
class InterfaceArea
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Triangle tri = new Triangle();
Area area;
area = rect;
System.out.println("Area Of Rectangle = "+ area.compute(1,2));
area = tri;
System.out.println("Area Of Triangle = "+ area.compute(10,2));
}
}
/** OUTPUT **
Area Of Rectangle = 2.0
Area Of Triangle = 10.0
*/
Exceptions and Errors
A program often encounters problems as it executes. It may have trouble reading data, there
might be illegal characters in the data, or an array index might go out of bounds. Java Errors
and Exceptions enable the programmer deal with such problems. You can write a program
that recovers from errors and keeps on running. This is important. A word processor program
should not crash when the user makes an error!
Exceptions and Errors.
Runtime Exceptions.
Arithmetic Exceptions.
try, catch, and finally statements.
User-friendly programs.
Contact us :- 9313565406, 65495934
42
Exceptions and Errors
Nothing is wrong with the program. The problem is that parseInt cannot convert "Rats" into an
int. When parseInt found the problem it threw a NumberFormatException. The Java runtime system caught the exception, halted the program, and printed the error messages.
An exception is a problem that occurs when a program is running. Often the problem is caused by
circustances outside the control of the program, such as bad user input. When an exception occurs, the
Java virtual machine creates an object of class Exception which holds information about the problem.
A Java program itself may catch an exception. It can then use the Exception object to recover
from the problem.
An error, also, is a problem that occurs when a program is running. An error is represented by an
object of class Error. But an error is too severe for a program to handle. The program must stop
running.
Throwable Hierarchy
Class Exception and class Error both descend from Throwable. A Java method can
"throw" an object of class Throwable. (We will do this later on in this chapter.) For example,
the method Integer.ParseInt() throws an exception when it tries to convert "Rats" into an
integer.
Exceptions
are different from Errors because programs can be written to recover from
Exceptions, but programs can't be written to recover from Errors. The rest of this chapter
discusses Exceptions.
Syntax of try{} and catch{}
try
{
// statements, some of which might
// throw an exception
}
catch ( SomeExceptionType ex )
{
// statements to handle this
// type of exception
}
....
// more catch blocks
catch ( AnotherExceptionType ex )
{
// statements to handle this
// type of exception
}
// Statements following the structure
Contact us :- 9313565406, 65495934
43
try{} and catch{}
To catch an exception:
1. Put code that might throw an exception inside a try{} block.
2. Put code that handles the exception inside a catch{} block.
3. import java.lang.* ;
4. import java.io.* ;
5. public class Square
6. {
7.
public static void main ( String[] a ) throws IOException
8.
{
9.
BufferedReader stdin =
10.
new BufferedReader ( new InputStreamReader( System.in ) );
11.
String inData;
12.
int
num ;
13.
System.out.println("Enter an integer:");
14.
inData = stdin.readLine();
15.
16.
try
17.
{
18.
num
= Integer.parseInt( inData );
19.
System.out.println("The square of " + inData + " is " +
num*num );
20.
}
21.
22.
catch (NumberFormatException ex )
23.
{
24.
System.out.println("You entered bad data." );
25.
System.out.println("Run the program again." );
26.
}
27.
System.out.println("Good-by" );
28.
}
29. }
User-friendly Code
Exception handling is important for user-friendly programs. Here is the compute-the-square
program again, this time written so that the user is prompted again if the input is bad:
import java.lang.* ;
import java.io.* ;
public class SquareUser
{
public static void main ( String[] a ) throws IOException
{
BufferedReader stdin =
new BufferedReader ( new InputStreamReader( System.in ) );
Contact us :- 9313565406, 65495934
44
String inData = null;
int
num = 0;
boolean goodData = false;
while ( !goodData )
{
System.out.println("Enter an integer:");
inData = stdin.readLine();
try
{
num
= Integer.parseInt( inData );
goodData = true;
}
catch (NumberFormatException ex )
{
System.out.println("You entered bad data." );
System.out.println("Please try again.\n" );
}
}
System.out.println("The square of " + inData + " is " + num*num );
}
}
Sample Output
Here is some sample output from the program:
Enter an integer:
rats
You entered bad data.
Please try again.
Enter an integer:
-12
The square of -12 is 144
Types of Exceptions
IOException
AWTException
RunTimeException
ArithmeticException
IllegalArgumentException
NumberFormatException
IndexOutOfBoundsException
others
The finally{} block
Contact us :- 9313565406, 65495934
45
If an IOExeption occurs in this program, it immediately looses contol. The exception is
thown to the method that called it, which in this case is the Java run time system. For this
program, execution will halt.
By using a finally{} block, you can ensure that some statements will always run, no matter
how the try{} block was exited. Here is the try/catch/finally{} structure.
try
{
// statements, some of which might
// throw an exception
}
catch ( SomeExceptionType ex )
{
// statements to handle this
// type of exception
}
....
// more catch blocks
catch ( AnotherExceptionType ex )
{
// statements to handle this
// type of exception
}
finally
{
// statements which will execute no matter
// how the try block was exited.
}
// Statements following the structure
import java.lang.* ;
import java.io.* ;
public class FinallyPractice
{
public static void main ( String[] a ) throws IOException
{
BufferedReader stdin =
new BufferedReader ( new InputStreamReader( System.in ) );
String inData; int num=0, div=0 ;
try
{
System.out.println("Enter the numerator:");
inData = stdin.readLine();
num
= Integer.parseInt( inData );
System.out.println("Enter the divisor:");
inData = stdin.readLine();
div
= Integer.parseInt( inData );
System.out.println( num + " / " + div + " is " + (num/div) );
}
catch (ArithmeticException ex )
{
System.out.println("You can't divide " + num + " by " + div);
Contact us :- 9313565406, 65495934
46
}
finally
{
System.out.println("If the division didn't work, you entered bad
data." );
}
System.out.println("Good-by" );
}
}
Omitting the catch{} Blocks
try
{
// statements, some of which might
// throw an exception
}
finally
{
// statements which will execute no matter
// how the try block was exited.
}
// Statements following the structure
JAVA Applet
HTML
HTML is the HyperText Markup Language. HTML files are text files featuring semantically tagged elements.
HTML filenames are suffixed with .html. Here's a simple HTML file:
<html>
<head>
<title>My First HTML Document</title>
</head>
<body>
<h1>A level one heading</h1>
Hello there. This is <STRONG>very</STRONG> important.
</body>
</html>
Links in
<a href="http://www.w3schools.com">This is a link</a>
<html>
<body style="background-color:yellow;">
Contact us :- 9313565406, 65495934
47
<h2 style="background-color:red;">This is a heading</h2>
<p style="background-color:green;">This is a paragraph.</p>
</body>
</html>
Introduction
Applet is java program that can be embedded into HTML pages. Java applets runs on the java
enables web browsers such as mozila and internet explorer. Applet is designed to run
remotely on the client browser, so there are some restrictions on it. Applet can't access system
resources on the local computer. Applets are used to make the web site more dynamic and
entertaining.
Advantages of Applet:
Applets are cross platform and can run on Windows, Mac OS and Linux platform
Applets can work all the version of Java Plug-in
Applets runs in a sandbox, so the user does not need to trust the code, so it can work
without security approval
Applets are supported by most web browsers
Applets are cached in most web browsers, so will be quick to load when returning to a
web page
User can also have full access to the machine if user allows
The Life cycle of An Applet
init(): method is called exactly once in an applet's life, when the applet is first loaded. It's normally
used to read PARAM tags, start downloading any other images or media files you need, and set up the
user interface. Most applets have init() methods.
start(): method is called at least once in an applet's life, when the applet is started or restarted. In
some cases it may be called more than once. Many applets you write will not have explicit start()
The stop():
method is called at least once in an applet's life, when the browser leaves the page
in which the applet is embedded. The applet's start() method will be called if at some later point the
browser returns to the page containing the applet.
destroy():
method is called exactly once in an applet's life, just before the browser unloads the
applet. This method is generally used to perform any final clean-up.
import java.applet.*;
import java.awt.*;
public class FirstApplet extends Applet{
public void paint(Graphics g){
g.drawString("Welcome in Java Applet.",40,20);
}
}
<HTML>
<HEAD>
</HEAD>
<BODY>
<APPLET ALIGN="CENTER" CODE="FirstApplet.class" WIDTH="800" HEIGHT="500"></APPLET>
</BODY>
</HTML>
Contact us :- 9313565406, 65495934
48
Passing Parameters to Applets
Parameters are passed to applets in NAME=VALUE pairs in <PARAM> tags between the opening and closing
APPLET tags. Inside the applet, you read the values passed through the PARAM tags with the getParameter()
method of the java.applet.Applet class.
import java.applet.*;
import java.awt.*;
public class appletParameter extends Applet {
private String strDefault = "Hello! Java Applet.";
public void paint(Graphics g) {
String strParameter = this.getParameter("Message");
if (strParameter == null)
strParameter = strDefault;
g.drawString(strParameter, 50, 25);
}
}
<HTML>
<HEAD>
<TITLE>Passing Parameter in Java Applet</TITLE>
</HEAD>
<BODY>
This is the applet:<P>
<APPLET code="appletParameter.class" width="800" height="100">
<PARAM name="message" value="Welcome in Passing parameter in java applet example.">
</APPLET>
</BODY>
</HTML>
Java - Drawing Shapes Example in java
import java.applet.*;
import java.awt.*;
public class CircleLine extends Applet{
int x=300,y=100,r=50;
public void paint(Graphics g){
g.drawLine(3,300,200,10);
g.drawString("Line",100,100);
g.drawOval(x-r,y-r,100,100);
g.drawString("Circle",275,100);
g.drawRect(400,50,200,100);
g.drawString("Rectangel",450,100);
}
}
<HTML>
<HEAD>
</HEAD>
<BODY>
<div align="center">
<APPLET CODE="CircleLine.class" WIDTH="800" HEIGHT="500"></APPLET>
</div>
</BODY>
</HTML>
Contact us :- 9313565406, 65495934
49
Java - Clock Applet in Java
import java.applet.*;
import java.awt.*;
import java.util.*;
public class ClockApplet extends Applet implements Runnable{
Thread t,t1;
public void start(){
t = new Thread(this);
t.start();
}
public void run(){
t1 = Thread.currentThread();
while(t1 == t){
repaint();
try{
t1.sleep(1000);
}catch(InterruptedException e){}
}
}
public void paint(Graphics g){
Calendar cal = new GregorianCalendar();
String hour = String.valueOf(cal.get(Calendar.HOUR));
String minute = String.valueOf(cal.get(Calendar.MINUTE));
String second = String.valueOf(cal.get(Calendar.SECOND));
g.drawString(hour + ":" + minute + ":" + second, 20, 30);
}
}
Play Audio in Java Applet
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class PlaySoundApplet extends Applet implements ActionListener{
Button play,stop;
AudioClip audioClip;
public void init(){
play = new Button(" Play in Loop ");
add(play);
play.addActionListener(this);
stop = new Button(" Stop ");
add(stop);
stop.addActionListener(this);
audioClip = getAudioClip(getCodeBase(), "TestSnd.wav");
}
public void actionPerformed(ActionEvent ae){
Button source = (Button)ae.getSource();
if (source.getLabel() == " Play in Loop "){
audioClip.play();
}
else if(source.getLabel() == " Stop "){
audioClip.stop();
}
Contact us :- 9313565406, 65495934
50
}
}
<HTML>
<BODY>
<APPLET CODE="PlaySoundApplet" WIDTH="200" HEIGHT="300"></APPLET>
</BODY>
</HTML>
Color
Color is a class in the AWT. Individual colors like red or mauve are instances of this class, java.awt.Color. Be
sure to import it if you want to use other than the default colors. You create new colors using the same RGB
triples that you use to set background colors on web pages. However you use decimal numbers instead of the
hex values used by HTML's bgcolor attribute. For example medium gray is Color(127, 127, 127). Pure white is
Color(255, 255, 255). Pure red is (255, 0, 0) and so on. As with any variable you should give your colors
descriptive names. For instance
Color medGray = new Color(127, 127, 127);
Color cream = new Color(255, 231, 187);
Color lightGreen = new Color(0, 55, 0);
A few of the most common colors are available by name. These are
Color.black
Color.blue
Color.cyan
Color.darkGray
Color.gray
Color.green
Color.lightGray
Color.magenta
Color.orange
Color.pink
Color.red
Color.white
Color.yellow
System Colors
The java.awt.SystemColor class is a subclass of java.awt.Color which provides color constants that match
native component colors. For example, if you wanted to make the background color of your applet, the same
as the background color of a window, you might use this init() method:
public void paint (Graphics g) {
g.setColor(SystemColor.control);
g.fillRect(0, 0, this.getSize().width, this.getSize().height);
}
Fonts
g.drawString(String s, int x, int y)
import java.awt.*;
import java.applet.*;
public class FontList extends Applet {
Contact us :- 9313565406, 65495934
51
private String[] availableFonts;
public void init () {
Toolkit t = Toolkit.getDefaultToolkit();
availableFonts = t.getFontList();
}
public void paint(Graphics g) {
for (int i = 0; i < availableFonts.length; i++) {
g.drawString(availableFonts[i], 5, 15*(i+1));
}
}
}
Java - The Sample Banner Example in Java
import java.awt.*;
import java.applet.*;
public class SampleBanner extends Applet implements Runnable{
String str = "This is a simple Banner developed by Roseindia.net. ";
Thread t ;
boolean b;
public void init() {
setBackground(Color.gray);
setForeground(Color.yellow);
}
public void start() {
t = new Thread(this);
b = false;
t.start();
}
public void run () {
char ch;
for( ; ; ) {
try {
repaint();
Thread.sleep(250);
ch = str.charAt(0);
str = str.substring(1, str.length());
str = str + ch;
} catch(InterruptedException e) {}
}
}
public void paint(Graphics g) {
g.drawRect(1,1,300,150);
Contact us :- 9313565406, 65495934
52
g.setColor(Color.yellow);
g.fillRect(1,1,300,150);
g.setColor(Color.red);
g.drawString(str, 1, 150);
}
}
<HTML>
<BODY>
<APPLET CODE = "SampleBanner" WIDTH = "500" HEIGHT = "300"></APPLET>
</BODY>
</HTML>
Java - Opening a URL from an Applet
mport java.applet.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
public class tesURL extends Applet implements ActionListener{
public void init(){
String link_Text = "google";
Button b = new Button(link_Text);
b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent ae){
//get the button label
Button source = (Button)ae.getSource();
String link = "http://www."+source.getLabel()+".com";
try
{
AppletContext a = getAppletContext();
URL u = new URL(link);
// a.showDocument(u,"_blank");
// _blank to open page in new window
a.showDocument(u,"_self");
}
catch (MalformedURLException e){
System.out.println(e.getMessage());
}
}
}
~AWT~
The Abstract Window Toolkit (AWT) contains several graphical widgets which can be
added and positioned to the display area with a layout manager.
As the Java programming language, the AWT is also platform-independent. A common set of
tools is provided by the AWT for graphical user interface design. The implementation of the
user interface elements provided by the AWT is done using every platform's native GUI
Contact us :- 9313565406, 65495934
53
toolkit. One of the AWT's significance is that the look and feel of each platform can be
preserved.
Basic GUI Logic
The GUI application or applet is created in three steps. These are:
Add components to Container objects to make your GUI.
Then you need to setup event handlers for the user interaction with GUI.
Explicitly display the GUI for application.
AWT -Components
In Java all components are subclasses of java.awt.Component. Subclasses of Component include
TextField
TextArea
Label
List
Button
Choice
Checkbox
Frame
Button
Label
ComboBox
Menu
Checkboxgroup
Canvas
Button
import java.awt.*;
import java.applet.Applet;
public class MyButton extends Applet {
public void init() {
Button button = new Button("SUBMIT");
add(button);
}
}
Labels
import java.applet.*;
import java.awt.*;
public class HelloContainer extends Applet {
public void init()
{
Label label;
label = new Label("Hello Container");
add(label);
}
Contact us :- 9313565406, 65495934
54
}
Canvas
import java.awt.*;
import java.applet.*;
public class MyCanvas extends Applet {
public MyCanvas() {
setSize(80, 40);
}
public void paint(Graphics g) {
g.drawRect(0, 0, 90, 50);
g.drawString("A Canvas", 15,15);
}
}
Checkbox
import java.awt.*;
import java.applet.Applet;
public class MyCheckbox extends Applet {
public void init() {
Checkbox c = new Checkbox("Choose this option");
add(c);
}
}
Frame
import
import
import
public
java.awt.*;
javax.swing.*;
java.awt.event.*;
class Frame{
public static void main(String[] args)
{
JFrame f=new JFrame();
f.setLayout(new FlowLayout(FlowLayout.CENTER));
JLabel label1=new JLabel("Name: ");
JLabel label2=new JLabel("Address: ");
final JTextField text1=new JTextField(20);
final JTextField text2=new JTextField(20);
JButton b=new JButton("Submit");
f.add(label1);
f.add(text1);
f.add(label2);
f.add(text2);
f.add(b);
f.setVisible(true);
f.pack();
}
}
Contact us :- 9313565406, 65495934
55
CubScouts
import java.awt.*;
import java.applet.*;
public class CubScouts extends Applet {
public void init() {
Label cubScouts = new Label("Cub Scouts!");
cubScouts.setForeground(Color.blue);
cubScouts.setBackground(Color.yellow);
cubScouts.setFont(new Font("Sans", Font.BOLD, 24));
this.add(cubScouts);
}
}
Using Component Methods in an Applet
Since applets are subclasses of java.awt.Component they also have all these methods. You can use these
methods to set the default values of color, font, and so on used by the Graphics object passed to the paint()
method. For example, Here's another way to write an applet that uses a Label whose text is 24 point,
SansSerif, bold and blue and whose background color is yellow.
import java.awt.*;
import java.applet.*;
public class CubScoutApplet extends Applet {
int height = 0;
public void init() {
this.setForeground(Color.blue);
this.setBackground(Color.yellow);
this.setFont(new Font("Sans", Font.BOLD, 24));
this.height = this.getSize().height;
}
public void paint(Graphics g) {
g.drawString("Cub Scouts!", 5, height/2);
}
}
Contact us :- 9313565406, 65495934
56
Menu
Java's Abstract Windowing Toolkit (AWT) includes four concrete menu classes: menu bars
representing a group of menus that appears across the top of the window or the screen (class
MenuBar); pull-down menus that pull from menu bars or from other menus (class Menu); menu
items that represent menu selections (class MenuItem); and menu items that the user can turn on and
off (class CheckBoxMenuItem)
Syntax:
FileMenu fileMenu = new FileMenu(this);
HelpMenu helpMenu = new HelpMenu(this);
MenuBar mb = new MenuBar();
mb.add(fileMenu);
mb.add(helpMenu);
setMenuBar(mb);
A Visual Guide to Layout Managers
BorderLayout
BoxLayout
CardLayout
FlowLayout
GridBagLayout
GridLayout
GroupLayout
SpringLayout
Border-Layout: The Border Layout is arranging and resizing components to set in five
positions which is used in this program. The java program uses and declares all positions as a
NORTH, SOUTH, WEST, EAST, and CENTER.
import java.awt.*;
import java.awt.event.*;
public class
BorderLayoutExample{
public static void main(String[] args)
{
Frame frame= new Frame("BorderLayout Frame");
Panel pa= new Panel();
Button ba1= new Button();
Button ba2=new Button();
Button ba3=new Button();
Button ba4=new Button();
Contact us :- 9313565406, 65495934
57
Button ba5=new Button();
frame.add(pa);
pa.setLayout(new BorderLayout());
pa.add(new Button("Wel"), BorderLayout.NORTH);
pa.add(new Button("Come"), BorderLayout.SOUTH);
pa.add(new Button("Rose"), BorderLayout.EAST);
pa.add(new Button("India"), BorderLayout.WEST);
pa.add(new Button("Ravi"), BorderLayout.CENTER);
frame.setSize(300,300);
frame.setVisible(true);
}
}
Traditional, procedu
ral programs have a single order of execution. Control moves in a linear fashion from the first statement to the
second statement to the third statement and so forth with occasional loops and branches. User input occurs at
precisely defined points in the program. A user cannot input data except when the computer is ready to
receive it.
Low Level Events
Low level events represent direct communication from the user. A low level event is a key press or a key
release, a mouse click, drag, move, or release, and so on.
These include:
java.awt.event.ComponentEvent
component resized, moved, etc.
java.awt.event.FocusEvent
component got focus, lost focus
java.awt.event.KeyEvent
key press, key release, etc.
java.awt.event.MouseEvent
mouse down, mouse move, mouse drag, mouse up
java.awt.event.ContainerEvent
a component was added to or removed from the container
java.awt.event.WindowEvent
the window was activated, deactivated, opened, closed, inconified, or deiconified
java.lang.Object
|
+---java.util.EventObject
|
+---java.awt.AWTEvent
|
+---java.awt.event.ComponentEvent
|
+---java.awt.event.InputEvent
|
|
|
+---java.awt.event.KeyEvent
|
|
|
+---java.awt.event.MouseEvent
|
+---java.awt.event.FocusEvent
|
+---java.awt.event.ContainerEvent
|
+---java.awt.event.WindowEvent
High Level Events
High level or semantic events encapsulate the meaning of a user interface component. These include:
java.awt.event.ActionEvent
Contact us :- 9313565406, 65495934
58
do a command
java.awt.event.AdjustmentEvent
value was adjusted
java.awt.event.ItemEvent
item state has changed
java.awt.event.TextEvent
the value of the text object changed
Processing Events
The Java runtime is responsible for handling the event queue. In particular it makes sure that each low-level
event is directed to the proper component. You do not need to worry about deciding which component the
event is meant for. The runtime handles this for you. In particular the runtime passes the event to the
component's processEvent() method:
protected void processEvent(AWTEvent evt)
The processEvent() method determines the type of the event and passes it on to one of five other methods in
the java.awt.Component class:
protected void processComponentEvent(ComponentEvent evt)
protected void processFocusEvent(FocusEvent evt)
protected void processKeyEvent(KeyEvent evt)
protected void processMouseEvent(MouseEvent evt)
protected void processMouseMotionEvent(MouseEvent evt)
EventListeners
To respond to an event a component receives you register an event listener for the event type with the
component. Event listeners are objects which implement a java.util.EventListener interface. The AWT defines
eleven sub-interfaces of java.util.EventListener, one for each type of event:
java.awt.event.ComponentListener
java.awt.event.ContainerListener
java.awt.event.FocusListener
java.awt.event.KeyListener
java.awt.event.MouseListener
java.awt.event.MouseMotionListener
java.awt.event.WindowListener
java.awt.event.ActionListener
java.awt.event.AdjustmentListener
java.awt.event.ItemListener
java.awt.event.TextListener
Mouse Events
A java.awt.event.MouseEvent is sent to a component when the mouse state changes over the component.
There are seven types of mouse events, each represented by an integer constant:
MouseEvent.MOUSE_CLICKED
A mouse button was pressed, then released
MouseEvent.MOUSE_DRAGGED
The mouse was moved over the component while a mouse button was held
down
MouseEvent.MOUSE_ENTERED The cursor entered the component's space
Contact us :- 9313565406, 65495934
59
MouseEvent.MOUSE_EXITED
The cursor left the component's space
MouseEvent.MOUSE_MOVED
The mouse moved in the component's space
MouseEvent.MOUSE_PRESSED The mouse button was pressed (but not released) over the component
MouseEvent.MOUSE_RELEASED The mouse button was released over the component.
Besides its type, the main thing you want to know about a MouseEvent is the location; that is, where the
mouse was clicked. You can either request the x and y locations separately, or together as a java.awt.Point
object.
public int getX()
public int getY()
public Point getPoint()
Mouse Listeners and Mouse Motion Listeners
Generally you respond to mouse events directed at your component, by registering a MouseListener object
with the component.
public interface MouseListener extends EventListener
For reasons of efficiency, the MouseListener interface only declares five methods:
public abstract void mouseClicked(MouseEvent evt)
public abstract void mousePressed(MouseEvent evt)
public abstract void mouseReleased(MouseEvent evt)
public abstract void mouseEntered(MouseEvent evt)
public abstract void mouseExited(MouseEvent evt)
public interface MouseMotionListener extends EventListener
The MouseMotionListener interface declares these two methods that are missing from MouseListener:
public abstract void mouseDragged(MouseEvent evt)
public abstract void mouseMoved(MouseEvent evt)
If you don't care about mouse dragged and mouse moved events, then you simply don't register a
MouseMotionListener on the component; and the component won't bother to report such events
KeyEvents
A java.awt.event.KeyEvent is sent to a component when a key is pressed while the component has the focus.
There are three types of key events, each represented by an integer constant:
KeyEvent.KEY_PRESSED A key was pressed
KeyEvent.KEY_RELEASED A key was released
KeyEvent.KEY_TYPED
A key press followed by a key release.
Most of the time you'll only respond to the last event, KeyEvent.KEY_TYPED.
The main thing you want to know about a KeyEvent is what key was pressed. You get this with the
getKeyChar() method.
public char getKeyChar()
Focus Events
The focus can be adjusted in a number of ways. For example, if the user hits the tab key, the focus will
generally shift from one component to the next. If the user hits Shift-Tab, the focus will move back one
component. When the user selects a component with the mouse, that component gets the focus. When a
component gains or loses the focus, it gets a FocusEvent. A change in the focus can be permanent or
temporary. Permanent focus change occurs when the focus is directly moved from one component to another,
either by calling requestFocus() or by direct user action such as the Tab key. Temporary focus change occurs
when a component gains or loses focus as an indirect result of another operation, such as a window
Contact us :- 9313565406, 65495934
60
deactivation. In this case, the original focus state is automatically restored once the operation is finished, or
the window is reactivated.
The isTemporary() method returns true if the focus change is temporary, false if it's permanent.
public boolean isTemporary()
You respond to changes in focus by installing a FocusListener in the component. This interface declares two
methods:
public abstract void focusGained(FocusEvent evt)
public abstract void focusLost(FocusEvent evt)
Component Events
java.awt.event.ComponentEvent is the superclass of all the events we've discussed so far. It also has a few
events of its own that allow you to react when a component is shown, hidden, moved, or resized. These are
ComponentEvent.COMPONENT_MOVED
ComponentEvent.COMPONENT_RESIZED
ComponentEvent.COMPONENT_SHOWN
ComponentEvent.COMPONENT_HIDDEN
As you might guess, you respond to these events by registering a java.awt.event.ComponentListener with your
component. This interface declares four methods:
public abstract void componentResized(ComponentEvent evt)
public abstract void componentMoved(ComponentEvent evt)
public abstract void componentShown(ComponentEvent evt)
public abstract void componentHidden(ComponentEvent evt)
The ComponentEvent class doesn't have any particularly useful methods of its own, but you can use the
various methods of the java.awt.Component class to determine where a component was moved or to what
size it was resized
Converting low-level events to high level events
The native operating system and user interface only send low-level events. They do not send ActionEvents,
TextEvents, ItemEvents, or AdjustmentEvents. Instead each component which fires these events first listens
for low-level events like key presses. (Actually, the component's peer does this.) When it sees the right lowlevel event or combination of low level events, it eats those events and fires a new high level event.
Adapter Classes
The AWT provides a number of adapter classes for the different EventListener interfaces. These are:
ComponentAdapter
ContainerAdapter
FocusAdapter
KeyAdapter
MouseAdapter
MouseMotionAdapter
WindowAdapter
Each adapter class implements the corresponding interface with a series of do-nothing methods. For example,
MouseListener declares these five methods:
public abstract void mouseClicked(MouseEvent evt)
public abstract void mousePressed(MouseEvent evt)
public abstract void mouseReleased(MouseEvent evt)
public abstract void mouseEntered(MouseEvent evt)
public abstract void mouseExited(MouseEvent evt)
Therefore, MouseAdapter looks like this:
package java.awt.event;
import java.awt.*;
Contact us :- 9313565406, 65495934
61
import java.awt.event.*;
public class MouseAdapter implements MouseListener {
public void mouseClicked(MouseEvent evt) {}
public void mousePressed(MouseEvent evt) {}
public void mouseReleased(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {}
}
By subclassing MouseAdapter rather than implementing MouseListener directly, you avoid having to write the
methods you don't actually need. You only override those that you plan to actually implement.
An example of Adapter Classes
Here's a mouse adapter that beeps when the mouse is clicked
import java.awt.*;
import java.awt.event.*;
public class MouseBeeper extends MouseAdapter {
public void mouseClicked(MouseEvent evt) {
Toolkit.getDefaultToolkit().beep();
}
}
Without extending the MouseAdapter class, I would have had to write the same class like this
import java.awt.*;
import java.awt.event.*;
public class MouseBeeper implements MouseListener {
public void mouseClicked(MouseEvent evt) {
Toolkit.getDefaultToolkit().beep();
}
public void mousePressed(MouseEvent evt) {}
public void mouseReleased(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {}
}
Adapter classes are a minor convenience. You do not need to use the adapter classes if you don't want to.
Consuming Events
Sometimes an application needs to keep some events from being processed normally by a component.
For example, a visual interface builder might need to allow a user to drag a button around the screen. In this
case, you wouldn't want the mouse press to activate the button.
You can consume an InputEvent, that is a MouseEvent or a KeyEvent, by calling its consume() method:
public void consume()
Contact us :- 9313565406, 65495934
62
Working with the event queue
The java.awt.EventQueue class represents a queue of events waiting to be processed. You can create your own
instances of this class using the noargs constructor:
public EventQueue()
For example,
EventQueue MyQueue = new EventQueue();
Custom Components
It's often useful to create new subclasses of Component with particular behavior. For example, you might want
a button that's round instead of a rectangle. The most common way to do this is to subclass java.awt.Canvas.
You would need to provide a paint() method for your component.
What is a LayoutManager
When you add a component to an applet or a container, the container uses its layout manager to decide
where to put the component. Different LayoutManager classes use different rules to place components.
java.awt.LayoutManager is an interface. Five classes in the java.awt package implement it:
FlowLayout
BorderLayout
CardLayout
GridLayout
GridBagLayout
plus javax.swing.BoxLayout
The LayoutManagers
A FlowLayout
arranges widgets from left to right until there's no more space left. Then it begins a row
lower and moves from left to right again. Each component in a FlowLayout gets as much space as it needs and
no more. A FlowLayout is useful for laying out buttons but not for much else. This is the default
LayoutManager for applets and panels (special containers to aid with layouts about which you'll learn more
very shortly).
A BorderLayout organizes an applet into North, South, East, West and Center sections. North, South, East and
West are the rectangular edges of the applet. They're continually resized to fit the sizes of the widgets
included in them. Center is whatever's left over in the middle.
A CardLayout
breaks the applet into a deck of cards, each of which has its own LayoutManager. Only one
card appears on the screen at a time. The user flips between cards, each of which shows a different set of
components. The common analogy is with HyperCard on the Mac and Toolbook on Windows. In Java this
might be used for a series of data input screens, where more input is needed than can comfortably be fit on
one screen.
A GridLayout
divides an applet into a specified number of rows and columns which form a grid of cells,
each equally sized and spaced. As components are added to the layout, they are placed in the cells, starting at
the upper left hand corner and moving to the right and down the page. Each component is sized to fit into its
cell. This layout manager tends to squeeze and stretch components unnecessarily. However the GridLayout is
great for arranging Panels.
GridBagLayout is the most precise of the five AWT LayoutManagers. It's similar to the GridLayout, but
components do not need to be the same size. Each component can occupy one or more cells of the layout.
Contact us :- 9313565406, 65495934
63
Furthermore components are not necessarily placed in the cells beginning at the upper left-hand corner and
moving to the right and down.
BoxLayout ????.
FlowLayout
The following applet uses a FlowLayout to position a series of buttons that mimic the buttons on a tape deck.
import java.applet.*;
import java.awt.*;
public class TapeDeck extends Applet {
public void init() {
this.setLayout(new FlowLayout());
this.add( new Button("Play"));
this.add( new Button("Rewind"));
this.add( new Button("Fast Forward"));
this.add( new Button("Pause"));
this.add( new Button("Stop"));
}
}
BorderLayout
A BorderLayout places objects in the North, South, East, West and center of an applet. You create a new
BorderLayout object much like a FlowLayout object, in the init() method inside a call to setLayout like this:
this.setLayout(new BorderLayout());
Example of BorderLayout
import java.applet.*;
import java.awt.*;
public class BorderButtons extends Applet {
public void init() {
this.setLayout(new BorderLayout(20, 10));
this.add(new Button("North"), BorderLayout.NORTH);
this.add(new Button("South"), BorderLayout.SOUTH);
this.add(new Button("Center"), BorderLayout.CENTER);
this.add(new Button("East"), BorderLayout.EAST);
this.add(new Button("West"), BorderLayout.WEST);
}
}
Contact us :- 9313565406, 65495934
64
CardLayout
this.setLayout(new CardLayout());
this.add("Pizza", new Label("How do you like your pizza?"));
this.add("Pizza", new Button("OK"));
this.add("Payment", new Label("How would you like to pay?"));
this.add("Payment", new Button("OK"));
this.add("Address", new Label("Delivery Instructions"));
this.add("Address", new Button("Order"));
One common technique is to name each card after a number.
this.setLayout(new CardLayout());
this.add("1", new Label("First Card"));
this.add("2", new Label("Second Card"));
this.add("3", new Label("Third Card"));
this.add("4", new Label("Fourth Card"));
this.add("5", new Label("Fifth Card"));
this.add("6", new Label("Sixth Card"));
Flipping Cards
The following five CardLayout methods allow you to switch cards. In all cases you must specify the container
inside of which you're flipping. This can be the applet, the window, or the panel that's arranged with this card
layout.
public void first(Container parent)
public void next(Container parent)
public void previous(Container parent)
public void last(Container parent)
public void show(Container parent, String name)
GridLayout
Here's the source code:
import java.applet.*;
import java.awt.*;
public class Ingredients2 extends Applet {
private TextField t;
private double price = 7.00;
public void init() {
this.setLayout(new GridLayout(11,1));
Contact us :- 9313565406, 65495934
65
this.add(
new Label("What do you want on your pizza?", Label.CENTER));
this.add(new Checkbox("Pepperoni"));
this.add(new Checkbox("Olives"));
this.add(new Checkbox("Onions"));
this.add(new Checkbox("Sausage"));
this.add(new Checkbox("Peppers"));
this.add(new Checkbox("Extra Cheese"));
this.add(new Checkbox("Ham"));
this.add(new Checkbox("Pineapple"));
this.add(new Checkbox("Anchovies"));
this.t = new TextField("$" + String.valueOf(price));
// so people can't change the price of the pizza
this.t.setEditable(false);
this.add(this.t);
}
/* I've removed the code to handle events
since it isn't relevant to this example */
}
GridBagConstraints
A GridBagConstraints object specifies the location and area of the component's display area within the
container and how the component is laid out inside its display area. The GridBagConstraints, in conjunction
with the component's minimum size and the preferred size of the component's container, determines where
the component is placed within the applet.
The GridBagConstraints() constructor is trivial
Fill
The GridBagConstraints fill field determines whether and how a component is resized if the component's
display area is larger than the component itself. The mnemonic constants you use to set this variable are
displayConstraints.fill = GridBagConstraints.HORIZONTAL;
ipadx and ipady
The ipadx and ipady fields let you increase this minimum size by padding the edges of the component with
extra pixels. For instance setting ipadx to two will guarantee that the component is at least four pixels wider
than its normal minimum. (ipadx adds two pixels to each side.) This is not needed for the calculator applet.
Insets
The insets field is an instance of the java.awt.Insets class. It specifies the padding between the component and
the edges of its display area. For all the keys in the calculator applet the insets are set like this:
equalsConstraints.insets = new Insets(3, 3, 3, 3);
anchor
When a component is smaller than its display area, the anchor field specifies where to place it in the grid cell.
The mnemonic constants you use for this purpose are similar to those used in a BorderLayout but a little more
specific. They are
GridBagConstraints.CENTER
GridBagConstraints.NORTH
GridBagConstraints.NORTHEAST
GridBagConstraints.EAST
GridBagConstraints.SOUTHEAST
Contact us :- 9313565406, 65495934
66
GridBagConstraints.SOUTH
GridBagConstraints.SOUTHWEST
GridBagConstraints.WEST
GridBagConstraints.NORTHWEST
A GridBagLayout Example
Here's the init() method that lays out the calculator applet.
void init() {
GridBagLayout gbl = new GridBagLayout();
this.setLayout(gbl);
// Add the display to the top four cells
GridBagConstraints displayConstraints = new GridBagConstraints();
displayConstraints.gridx = 0;
displayConstraints.gridy = 0;
displayConstraints.gridwidth = 4;
displayConstraints.gridheight = 1;
displayConstraints.fill = GridBagConstraints.HORIZONTAL;
// Add the text field
TextField display = new TextField(12);
gbl.setConstraints(display, displayConstraints);
this.add(display);
// Add the clear button
GridBagConstraints clearConstraints = new GridBagConstraints();
clearConstraints.gridx = 0;
clearConstraints.gridy = 1;
clearConstraints.gridwidth = 1;
clearConstraints.gridheight = 1;
clearConstraints.fill = GridBagConstraints.BOTH;
clearConstraints.insets = new Insets(3, 3, 3, 3);
// Add the button
Button clear = new Button("C");
gbl.setConstraints(clear, clearConstraints);
this.add(clear);
// Add the equals button
GridBagConstraints equalsConstraints = new GridBagConstraints();
equalsConstraints.gridx = 1;
equalsConstraints.gridy = 1;
equalsConstraints.gridwidth = 1;
equalsConstraints.gridheight = 1;
equalsConstraints.fill = GridBagConstraints.BOTH;
equalsConstraints.insets = new Insets(3, 3, 3, 3);
// Add the = button
Button equals = new Button("=");
gbl.setConstraints(equals, equalsConstraints);
this.add(equals);
// Add the / button
GridBagConstraints slashConstraints = new GridBagConstraints();
Contact us :- 9313565406, 65495934
67
slashConstraints.gridx = 2;
slashConstraints.gridy = 1;
slashConstraints.gridwidth = 1;
slashConstraints.gridheight = 1;
slashConstraints.fill = GridBagConstraints.BOTH;
slashConstraints.insets = new Insets(3, 3, 3, 3);
// Add the button
Button slash = new Button("/");
gbl.setConstraints(slash, slashConstraints);
this.add(slash);
// Add the * button
GridBagConstraints timesConstraints = new GridBagConstraints();
timesConstraints.gridx = 3;
timesConstraints.gridy = 1;
timesConstraints.gridwidth = 1;
timesConstraints.gridheight = 1;
timesConstraints.fill = GridBagConstraints.BOTH;
timesConstraints.insets = new Insets(3, 3, 3, 3);
// Add the button
Button star = new Button("*");
gbl.setConstraints(star, timesConstraints);
this.add(star);
// Add the 7 key
GridBagConstraints sevenConstraints = new GridBagConstraints();
sevenConstraints.gridx = 0;
sevenConstraints.gridy = 2;
sevenConstraints.gridwidth = 1;
sevenConstraints.gridheight = 1;
sevenConstraints.fill = GridBagConstraints.BOTH;
sevenConstraints.insets = new Insets(3, 3, 3, 3);
// Add the button
Button b7 = new Button("7");
gbl.setConstraints(b7, sevenConstraints);
this.add(b7);
// Add the 8 key
GridBagConstraints eightConstraints = new GridBagConstraints();
eightConstraints.gridx = 1;
eightConstraints.gridy = 2;
eightConstraints.gridwidth = 1;
eightConstraints.gridheight = 1;
eightConstraints.fill = GridBagConstraints.BOTH;
eightConstraints.insets = new Insets(3, 3, 3, 3);
// Add the button
Button b8 = new Button("8");
gbl.setConstraints(b8, eightConstraints);
this.add(b8);
// Add the 9 key
Contact us :- 9313565406, 65495934
68
GridBagConstraints nineConstraints = new GridBagConstraints();
nineConstraints.gridx = 2;
nineConstraints.gridy = 2;
nineConstraints.gridwidth = 1;
nineConstraints.gridheight = 1;
nineConstraints.fill = GridBagConstraints.BOTH;
nineConstraints.insets = new Insets(3, 3, 3, 3);
// Add the button
Button b9 = new Button("9");
gbl.setConstraints(b9, nineConstraints);
this.add(b9);
// Add the - key
GridBagConstraints minusConstraints = new GridBagConstraints();
minusConstraints.gridx = 3;
minusConstraints.gridy = 2;
minusConstraints.gridwidth = 1;
minusConstraints.gridheight = 1;
minusConstraints.fill = GridBagConstraints.BOTH;
minusConstraints.insets = new Insets(3, 3, 3, 3);
// Add the button
Button minus = new Button("-");
gbl.setConstraints(minus, minusConstraints);
this.add(minus);
// Add the 4 key
GridBagConstraints fourConstraints = new GridBagConstraints();
fourConstraints.gridx = 0;
fourConstraints.gridy = 3;
fourConstraints.gridwidth = 1;
fourConstraints.gridheight = 1;
fourConstraints.fill = GridBagConstraints.BOTH;
fourConstraints.insets = new Insets(3, 3, 3, 3);
// Add the button
Button b4 = new Button("4");
gbl.setConstraints(b4, fourConstraints);
this.add(b4);
// Add the 5 key
GridBagConstraints fiveConstraints = new GridBagConstraints();
fiveConstraints.gridx = 1;
fiveConstraints.gridy = 3;
fiveConstraints.gridwidth = 1;
fiveConstraints.gridheight = 1;
fiveConstraints.fill = GridBagConstraints.BOTH;
fiveConstraints.insets = new Insets(3, 3, 3, 3);
// Add the button
Button b5 = new Button("5");
gbl.setConstraints(b5, fiveConstraints);
this.add(b5);
Contact us :- 9313565406, 65495934
69
// Add the 6 key
GridBagConstraints sixConstraints = new GridBagConstraints();
sixConstraints.gridx = 2;
sixConstraints.gridy = 3;
sixConstraints.gridwidth = 1;
sixConstraints.gridheight = 1;
sixConstraints.fill = GridBagConstraints.BOTH;
sixConstraints.insets = new Insets(3, 3, 3, 3);
// Add the button
Button b6 = new Button("6");
gbl.setConstraints(b6, sixConstraints);
this.add(b6);
// Add the + key
GridBagConstraints plusConstraints = new GridBagConstraints();
plusConstraints.gridx = 3;
plusConstraints.gridy = 3;
plusConstraints.gridwidth = 1;
plusConstraints.gridheight = 1;
plusConstraints.fill = GridBagConstraints.BOTH;
plusConstraints.insets = new Insets(3, 3, 3, 3);
// Add the button
Button plus = new Button("+");
gbl.setConstraints(plus, plusConstraints);
this.add(plus);
// Add the 1 key
GridBagConstraints oneConstraints = new GridBagConstraints();
oneConstraints.gridx = 0;
oneConstraints.gridy = 4;
oneConstraints.gridwidth = 1;
oneConstraints.gridheight = 1;
oneConstraints.fill = GridBagConstraints.BOTH;
oneConstraints.insets = new Insets(3, 3, 3, 3);
// Add the button
Button b1 = new Button("1");
gbl.setConstraints(b1, oneConstraints);
this.add(b1);
// Add the 2 key
GridBagConstraints twoConstraints = new GridBagConstraints();
twoConstraints.gridx = 1;
twoConstraints.gridy = 4;
twoConstraints.gridwidth = 1;
twoConstraints.gridheight = 1;
twoConstraints.fill = GridBagConstraints.BOTH;
twoConstraints.insets = new Insets(3, 3, 3, 3);
// Add the button
Button b2 = new Button("2");
gbl.setConstraints(b2, twoConstraints);
add(b2);
Contact us :- 9313565406, 65495934
70
// Add the 3 key
GridBagConstraints threeConstraints = new GridBagConstraints();
threeConstraints.gridx = 2;
threeConstraints.gridy = 4;
threeConstraints.gridwidth = 1;
threeConstraints.gridheight = 1;
threeConstraints.fill = GridBagConstraints.BOTH;
threeConstraints.insets = new Insets(3, 3, 3, 3);
// Add the button
Button b3 = new Button("3");
gbl.setConstraints(b3, threeConstraints);
this.add(b3);
// Add the = key
GridBagConstraints bigEqualsConstraints = new GridBagConstraints();
bigEqualsConstraints.gridx = 3;
bigEqualsConstraints.gridy = 4;
bigEqualsConstraints.gridwidth = 1;
bigEqualsConstraints.gridheight = 2;
bigEqualsConstraints.fill = GridBagConstraints.BOTH;
bigEqualsConstraints.insets = new Insets(3, 3, 3, 3);
// Add the button
Button bigEquals = new Button("=");
gbl.setConstraints(bigEquals, bigEqualsConstraints);
this.add(bigEquals);
// Add the 0 key
GridBagConstraints zeroConstraints = new GridBagConstraints();
zeroConstraints.gridx = 0;
zeroConstraints.gridy = 5;
zeroConstraints.gridwidth = 2;
zeroConstraints.gridheight = 1;
zeroConstraints.fill = GridBagConstraints.BOTH;
zeroConstraints.insets = new Insets(3, 3, 3, 3);
// Add the button
Button b0 = new Button("0");
gbl.setConstraints(b0, zeroConstraints);
this.add(b0);
// Add the . key
GridBagConstraints decimalConstraints = new GridBagConstraints();
decimalConstraints.gridx = 2;
decimalConstraints.gridy = 5;
decimalConstraints.gridwidth = 1;
decimalConstraints.gridheight = 1;
decimalConstraints.fill = GridBagConstraints.BOTH;
decimalConstraints.insets = new Insets(3, 3, 3, 3);
// Add the button
Button bdecimal = new Button(".");
gbl.setConstraints(bdecimal, decimalConstraints);
Contact us :- 9313565406, 65495934
71
this.add(bdecimal);
}
What is a Container?
A container is a component which can contain other components inside itself. It is also an instance of a
subclass of java.awt.Container. java.awt.Container extends java.awt.Component so containers are themselves
components.
The Two Kinds of Containers
The AWT defines two different kinds of containers, panels and windows.
Panels are subclasses of java.awt.Panel. A panel is contained inside another container, or perhaps inside the
web browser's window. Panels do not stand on their own. Applets are panels.
Windows are subclasses of java.awt.Window. A window is a free-standing, native window. There are two kinds
of windows: frames and dialogs. A frame is an instance of a subclass of java.awt.Frame. It represents a normal,
native window. A dialog is a subclass of java.awt.Dialog. A dialog is a transitory window that exists merely to
impart some information or get some input from the user.
What is a Menu?
Menus are composed of three hierarchical pieces. The menu bar contains the various menus. The menu bar is
at the top of the screen on a Macintosh and in the top of the window in Windows and Motif.
Each menu bar contains one or more menus. Menus are organized topically. File would be one menu. Edit
would be another.
Each menu contains one or more menu items. The menu items are the individual actions such as Open, Print,
Cut or Copy. They are not shown except when the menu is active. No more than one menu will be active at a
time.
This Edit menu has a disabled Undo menu item followed by a separator, followed by enabled Cut, Copy, paste
and Clear menu items, followed by another separator, followed by an enabled Select All menu item.
The Menu Classes
The AWT contains four main classes to handle menus:
java.awt.Menu
java.awt.MenuBar
java.awt.MenuItem
java.awt.PopupMenu
Contact us :- 9313565406, 65495934
72
java.lang.Object
|
+---java.awt.MenuComponent
|
+---java.awt.MenuBar
|
+---java.awt.MenuItem
|
+---java.awt.Menu
|
+---java.awt.PopupMenu
Swing Menus
Swing contains three main classes to handle menus:
javax.swing.JMenu
javax.swing.JMenuBar
javax.swing.JMenuItem
javax.swing.JCheckboxMenuItem
javax.swing.JRadioButtonMenuItem
java.lang.Object
|
+---java.awt.Component
|
+---java.awt.Container
|
+---javax.swing.JComponent
|
+--javax.swing.JContainer
|
+--javax.swing.AbstractButton
|
+--javax.swing.JMenuItem
|
+--javax.swing.JMenu
|
+--javax.swing.CheckboxMenuItem
|
+--javax.swing.RadioButtonMenuItem
Creating Menus
You should build the menus before you display them. The typical order is:
1. Create a new MenuBar.
2. Create a new Menu.
3. Add items to the Menu.
4. Add the Menu to the MenuBar.
5. If necessary repeat steps 2 through 4.
Contact us :- 9313565406, 65495934
73
6.
Add the MenuBar to the Frame.
The constructors you need are all simple. To create a new MenuBar object:
MenuBar myMenubar = new MenuBar();
To create a new Menu use the Menu(String title) constructor. Pass it the title of the menu you want. For
example, to create File and Edit menus,
Menu fileMenu = new Menu("File");
Menu editMenu = new Menu("Edit");
MenuItems are created similarly with the MenuItem(String menutext) constructor. Pass it the title of the menu
you want like this
MenuItem cut = new MenuItem("Cut");
You can create MenuItems inside the Menus they belong to, just like you created widgets inside their layouts.
Menu's have add methods that take an instance of MenuItem. Here's how you'd build an Edit Menu complete
with Undo, Cut, Copy, Paste, Clear and Select All MenuItems:
Menu editMenu = new Menu("Edit");
MenuItem undo = new MenuItem("Undo")
editMenu.add(undo);
editMenu.addSeparator();
MenuItem cut = new MenuItem("Cut")
editMenu.add(cut);
MenuItem copy = new MenuItem("Copy")
editMenu.add(copy);
MenuItem paste = new MenuItem("Paste")
editMenu.add(paste);
MenuItem clear = new MenuItem("Clear")
editMenu.add(clear);
editMenu.addSeparator();
MenuItem selectAll = new MenuItem("Select All");
editMenu.add(selectAll);
The addSeparator() method adds a horizontal line across the menu. It's used to separate logically separate
functions in one menu.
Once you've created the Menus, you add them to the MenuBar using the MenuBar's add(Menu m) method
like this:
myMenubar.add(fileMenu);
myMenubar.add(editMenu);
Finally when the MenuBar is fully loaded, you add the Menu to a Frame using the frame's
setMenuBar(MenuBar mb) method. Given a Frame f this is how you would do it:
f.setMenuBar(myMenuBar);
Input and Output in Java
The java.io package contains classes that perform input and output. In Java, I/O classes are differentiated
according to the type of data being read or written. Byte oriented and numeric data is written with output
streams and read with input streams. Character data, that is text, is written with writers and read with readers.
Whether you use streams or readers and writers depends on the type of data you're dealing with. All text data,
especially non-ASCII text, should be passed through a reader or writer.
The two main stream classes are java.io.InputStream and java.io.OutputStream. The two main reader and
writer classes are java.io.Reader and java.io.Writer These are abstract base classes for many different
subclasses with more specialized abilities.
Contact us :- 9313565406, 65495934
74
What is a Stream?
A stream is a sequence of data of undetermined length. It's called a stream because it's like a stream of water
that continues to flow. There's no definite end to it. In Java a stream is composed of discrete bytes. The bytes
may represent chars or other kinds of data. They may come faster than you can handle them, or your thread
may block while waiting for the next one to arrive. It often doesn't matter.
The key to processing the stream is a while loop that processes each piece of data, until you encounter the
end-of-stream character or some other exceptional condition occurs. In Unix you type end-of-stream with
Control-D. On Windows, you type end-of-stream with Control-Z.
The Stream Classes
Most stream classes are part of the java.io package. (There are also a few more in the sun.io and sun.net
packages, but those are deliberately hidden from you. There are also a couple in java.util.zip.) The two main
classes are java.io.InputStream and java.io.OutputStream. These are abstract base classes for many different
subclasses with more specialized abilities, including:
BufferedInputStream
BufferedOutputStream
ByteArrayInputStream
ByteArrayOutputStream
DataInputStream
DataOutputStream
FileInputStream
FileOutputStream
FilterInputStream
FilterOutputStream
LineNumberInputStream
ObjectInputStream
ObjectOutputStream
PipedInputStream
PipedOutputStream
PrintStream
PushbackInputStream
SequenceInputStream
StringBufferInputStream
The InputStream Class
java.io.InputStream is an abstract class that contains the basic methods for reading raw bytes of data from a
stream. Although InputStream is an abstract class, many methods in the class library are only specified to
return an InputStream, s o you'll often have to deal directly with only the methods declared in this class.
public abstract int read() throws IOException
public int read(byte[] data) throws IOException
public int read(byte[] data, int offset, int length)
throws IOException
public long skip(long n) throws IOException
public int available() throws IOException
public void close() throws IOException
public void mark(int readLimit)
Contact us :- 9313565406, 65495934
75
public void reset() throws IOException
public boolean markSupported()
Reading bytes of data
The basic read() method of the InputStream class reads a single unsigned byte of data and returns the int value
of the unsigned byte. This is a number between 0 and 255. If the end of stream is encountered, it returns -1
instead; and you can use this as a flag to watch for the end of stream.
public abstract int read() throws IOException
import java.io.*;
public class Echo {
public static void main(String[] args) {
try {
echo(System.in);
}
catch (IOException ex) {
System.err.println(ex);
}
}
public static void echo(InputStream in) throws IOException {
while (true) {
// Notice that although a byte is read, an int
// with value between 0 and 255 is returned.
// Then this is converted to an ISO Latin-1 char
// in the same range before being printed.
int i = in.read();
// -1 is returned to indicate the end of stream
if (i == -1) break;
// without the cast a numeric string like "65"
// would be printed instead of the character "A"
char c = (char) i;
System.out.print(c);
}
System.out.println();
}}
Reading many bytes of data
The basic read() method reads a byte at a time. This is less than perfectly efficient. The following two
overloaded variants read multiple bytes into an array of bytes.
public int read(byte[] data) throws IOException
public int read(byte[] data, int offset, int length)
throws IOException
Counting the available bytes
The available() method tests how many bytes are ready to be read from the stream without blocking.
Contact us :- 9313565406, 65495934
76
public int available() throws IOException
import java.io.*;
public class EfficientEcho {
public static void main(String[] args) {
try {
echo(System.in);
}
catch (IOException ex) {
System.err.println(ex);
}
}
public static void echo(InputStream in) throws IOException {
while (true) {
int n = in.available();
if (n > 0) {
byte[] b = new byte[n];
int result = in.read(b);
if (result == -1) break;
String s = new String(b);
System.out.print(s);
} // end if
} // end while
}
}
Skipping bytes
The skip() method reads a specified number of bytes and throws them away.
public int skip(long n) throws IOException
Closing Streams
When you're done with a stream, you should close it to release any resources associated with the stream.
Once the stream is closed attempts to read from it, will throw IOExceptions.
You close a stream with the close() method:
public void close() throws IOException
An IOException is thrown if the stream can't be closed.
Streams should normally be closed in a finally block to guarantee the release of resources:
InputStream in;
try {
in = new FileInputStream("data.txt");
// read from the stream...
}
catch (IOException ex) {
// handle exceptions...
}
finally {
Contact us :- 9313565406, 65495934
77
if (in != null) {
try {
in.close();
}
catch (IOException ex) {
// normally can ignore this
} }}
Output Streams
The java.io.OutputStream class sends raw bytes of data to a target such as the console or a network server.
Like InputStream, OutputStream is an abstract class. However, many methods in the class library are only
specified to return OutputStream rather than the more specific subclass.
public abstract void write(int b) throws IOException
public void write(byte[] data) throws IOException
public void write(byte[] data, int offset, int length)
throws IOException
public void flush() throws IOException
public void close() throws IOException
The write() methods send raw bytes of data to whomever is listening to this stream.
flush() method forces the data to be written whether or not the buffer is full.
The close()
method closes the stream and releases any resources associated with the stream. After the
stream is closed, attempts to write to it throw IOExceptions.
Output Stream Example
The only output streams you've seen so far are System.out and System.err. The following example uses the
write() and flush() methods of the OutputStream class to write the
String "Hello World" on System.out.
import java.io.*;
public class HelloOutputStream {
public static void main(String[] args) {
String s = "Hello World\r\n";
// Convert s to a byte array
byte[] b = new byte[s.length()];
s.getBytes(0, s.length()-1, b, 0);
try {
System.out.write(b);
System.out.flush();
}
catch (IOException ex) {
System.err.println(ex);
} }
}
Input from Files
The java.io.FileInputStream class represents an InputStream that reads bytes from a file. It has the following
public methods:
Contact us :- 9313565406, 65495934
78
public FileInputStream(String name) throws FileNotFoundException
public FileInputStream(File file) throws FileNotFoundException
public FileInputStream(FileDescriptor fd)
public int read() throws IOException
public int read(byte[] data) throws IOException
public int read(byte[] data, int offset, int length)
throws IOException
public long skip(long n) throws IOException
public int available() throws IOException
public void close() throws IOException
public final FileDescriptor getFD() throws IOException
Except for the constructors and getFD(), these methods merely override the methods of the same name in
java.io.InputStream. You use them exactly like you use those methods, only you'll end up reading data from a
file.
Examples of Input from Files
You create a new FileInputStream object by passing the name of the file to the constructor, like this:
FileInputStream fis = new FileInputStream("14.html");
The following simple application reads the files named on the command line and prints them on System.out.
import java.io.*;
public class Type {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
try {
FileInputStream fis = new FileInputStream(args[i]);
byte[] b = new byte[1024];
while (true) {
int result = fis.read(b);
if (result == -1) break;
String s = new String(b, 0, result);
System.out.print(s);
} // end while
} // end try
// Is this catch strictly necessary?
catch (FileNotFoundException ex) {
System.err.println("Could not find file " + args[i]);
}
catch (IOException ex) {
System.err.println(ex);
}
System.out.println();
} // end for
} // end main
}
Writing data to Files
The java.io.FileOutputStream class represents an OutputStream that writes bytes to a file. It has the following
public methods:
public FileOutputStream(String name) throws IOException
public FileOutputStream(String name, boolean append)
throws IOException
Contact us :- 9313565406, 65495934
79
public FileOutputStream(File file) throws IOException
public FileOutputStream(FileDescriptor fd)
public void write(int b) throws IOException
public void write(byte[] data) throws IOException
public void write(byte[] data, int offset, int length)
throws IOException
public void close() throws IOException
public final FileDescriptor getFD() throws IOException
Example of Output to Files
FileOutputStream fos = new FileOutputStream("16.html");
The following example reads user input from System.in and writes it into the files specified on the command
line.
import java.io.*;
public class MultiType {
public final static int BUFFER_SIZE = 4096;
public static void main(String[] args) {
FileOutputStream[] fos = new FileOutputStream[args.length];
for (int i = 0; i < args.length; i++) {
try {
fos[i] = new FileOutputStream(args[i]);
}
catch (IOException ex) {
System.err.println(e);
}
} // end for
try {
byte[] buffer = new byte[BUFFER_SIZE];
while (true) {
int result = System.in.read(buffer);
if (result == -1) break;
for (int i = 0; i < args.length; i++) {
try {
fos[i].write(buffer, 0, result);
}
catch (IOException ex) {
System.err.println(ex.getMessage());
}
} // end for
} // end while
} // end try
catch (IOException ex) {
System.err.println(e);
}
} // end main
}
Appending data to files
FileOutputStream fos = new FileOutputStream("16.html", true);
Contact us :- 9313565406, 65495934
80
The following example reads user input from System.in and appends it to the files specified on the command
line.
import java.io.*;
public class Append {
public static final int BUFFER_SIZE = 1024;
public static void main(String[] args) {
FileOutputStream[] fos = new FileOutputStream[args.length];
for (int i = 0; i < args.length; i++) {
try {
fos[i] = new FileOutputStream(args[i], true);
}
catch (IOException ex) {
System.err.println(e);
}
} // end for
byte[] buffer = new byte[BUFFER_SIZE];
try {
while (true) {
int result = System.in.read(buffer);
if (result == -1) break;
for (int i = 0; i < args.length; i++) {
try {
fos[i].write(buffer, 0, result);
}
catch (IOException ex) {
System.err.println(ex);
}
} // end for
} // end while
} // end try
catch (IOException ex) {
System.err.println(ex);
}
for (int i = 0; i < args.length; i++) {
try {
fos[i].close();
}
catch (IOException ex) {
System.err.println(ex);
}
} // end for
} // end main
}
Filter Streams
The java.io.FilterInputStream and java.io.FilterOutputStream classes are concrete subclasses of InputStream
and OutputStream that somehow modify data read from an underlying stream. You rarely use these classes
directly, but their subclasses are extremely important, especially DataInputStream and DataOutputStream.
FileOutputStream fos = new FileOutputStream("ln.txt");
DataOutputStream dos = new DataOutputStream(fos);
Contact us :- 9313565406, 65495934
81
It's not uncommon to combine these into one line like this:
DataOutputStream dos = new DataOutputStream(new FileOutputStream("ln.txt"));
Filter Stream Classes
BufferedInputStream and BufferedOutputStream
These classes buffer reads and writes by reading data first into a buffer (an internal array of bytes). Thus an
application can read bytes from the stream without necessarily calling the underlying native method. The data
is read from or written into the buffer in blocks; subsequent accesses go straight to the buffer.
DataInputStream and DataOutputStream
These classes read and write primitive Java data types and strings in a machine-independent way.
(Big-endian for integer types, IEEE-754 for floats and doubles, modified UTF-8 for Unicode)
PrintStream
PrintStream allows very simple printing of both primitive values, objects, and string literals. It uses the
platform's default character encoding to convert characters into bytes. This class traps all
IOExceptions. This class is primarily intended for debugging. System.out and System.err are instances
of PrintStream.
PushbackInputStream
This input stream has a one byte pushback buffer so a program can unread the last character read.
The next time data is read from the stream, the "unread" character is re-read.
GZIPInputStream and GZIPOutputStream
From the java.util.zip package, these classes provide compression and decompression services
DigestInputStream and DigestOutputStream
From the java.util.security package, these classes can calculate a message digest for a stream using a
strong hash function like SHA.
Buffered Streams
The java.io.BufferedInputStream and java.io.BufferedOutputStream classes buffer reads and writes by first
storing the data in a buffer (an internal array of bytes). Then the program reads bytes from the stream without
calling the underlying native method until the buffer is empty. The data is read from or written into the buffer
in blocks; subsequent accesses go straight to the buffer.
public BufferedInputStream(InputStream in)
public BufferedInputStream(InputStream in, int size)
public BufferedOutputStream(OutputStream out)
public BufferedOutputStream(OutputStream out, int size)
For example
URL u = new URL("http://java.developer.com");
BufferedInputStream bis = new BufferedInputStream(u.openStream(), 256);
Print Streams
The java.io.PrintStream class is a subclass of FilterOutputStream. It is implemented by System.out and
System.err. It allows very simple console output of both primitive values, objects, and string literals. It uses the
platform's default character encoding to convert characters into bytes.
Contact us :- 9313565406, 65495934
82
This class traps all IOExceptions. However you can test the error status with checkError(). This returns true if an
error has occurred, false otherwise.
public boolean checkError()
The main use of the class is the exceptionally overloaded print() and println() methods. They differ in that
println() adds an end-of-line character to whatever it prints while print() does not.
public void print(boolean b)
public void print(int i)
public void print(long l)
public void print(float f)
public void print(double d)
public void print(char[] text)
public void print(String s)
public void print(Object o)
public void println()
public void println(boolean b)
public void println(char c)
public void println(int i)
public void println(long l)
public void println(float f)
public void println(double d)
public void println(char[] text)
public void println(String s)
public void println(Object o)
The File Class
The java.io.File class represents a file name on the host system. It attempts to abstract system-dependent file
name features like the path separator character.
Unix: "/home/users/elharo/file1"
DOS: "C:\home\users\elharo\file1"
Mac OS 9: "Macintosh HD:home:users:elharo:file1"
File Constructors
There are three constructors in java.io.File. Each takes some variation of a filename as an argument(s). The
simplest is
public File(String path)
File Methods
Once you have a File object in place, there are a number of questions you can ask about it and things you can
do with it.
public String getName()
The most basic question you can ask a file is, "What is your name?" You do this with the getName () method
which takes no arguments and returns a String. This String is just the name of the file. It does not include any
piece of the directory or directories that contain this file. In other words you get back "file1" instead of
"/home/users/elharo/file1."
import java.io.*;
public class FileInfo {
Contact us :- 9313565406, 65495934
83
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
File f = new File(args[i]);
if (f.exists()) {
System.out.println("getName: " + f.getName());
System.out.println("getPath: " + f.getPath());
System.out.println("getAbsolutePath: " + f.getAbsolutePath());
try {
System.out.println("getCanonicalPath: "
+ f.getCanonicalPath());
}
catch (IOException ex) {
}
System.out.println("getParent: " + f.getParent());
if (f.canWrite()) {
System.out.println(f.getName() + " is writable.");
}
if (f.canRead()) {
System.out.println(f.getName() + " is readable.");
}
if (f.isFile()) {
System.out.println(f.getName() + " is a file.");
}
else if (f.isDirectory()) {
System.out.println(f.getName() + " is a directory.");
}
else {
System.out.println("What is this?");
}
if (f.isAbsolute()) {
System.out.println(f.getName() + " is an absolute path.");
}
else {
System.out.println(
f.getName() + " is not an absolute path.");
}
try {
System.out.println("Last Modified" + f.lastModified());
System.out.println(f.getName() + " is "
+ f.length() + " bytes.");
System.out.println(f.getName() + " is "
+ f.length() + " bytes.");
}
catch (IOException ex) {
}
}
else {
System.out.println("Can't find the file " + args[i]);
}
} }}
File Dialogs
The java.awt.FileDialog class is a subclass of java.awt.Dialog used for choosing a file to open or save. This class
uses the host platform's standard open and save file dialogs. You won't add components to a FileDialog, or
Contact us :- 9313565406, 65495934
84
handle user interaction. You'll just retrieve the result which will be the name and directory of a file. Since an
applet can't rely on having access to the file system, FileDialogs are primarily useful in applications.
There are three steps to using a FileDialog:
1. Create the FileDialog
2. Make the FileDialog visible.
3. Get the directory name and file name of the chosen file
You create a FileDialog with the constructor
Use these two strings to create a new File object. In short,
FileDialog fd = new FileDialog(new Frame(),
"Please choose a file:", FileDialog.LOAD);
fd.show();
if (fd.getFile() != null) {
File f = new File(fd.getDirectory(), fd.getFile());
}
Controlling File Dialogs
Many times you'll want some control over the FileDialog. You may want to specify that it should start looking
in a particular directory, or that only text files should be shown. Java lets you do this. To start the FileDialog off
in a particular directory call the FileDialog's setDirectory(String dir) method where dir is the path to the
directory. That is
fd.setDirectory("/usr/tmp");
setFilenameFilter(FilenameFilter fnf).
Random Access Files
Random access files can be read from or written to or both from a particular byte position in the file. The
position in the file is indicated by a file pointer.
There are two constructors in this class:
public RandomAccessFile(String name, String mode) throws IOException
public RandomAccessFile(File file, String mode) throws IOException
public int read() throws IOException
public int read(byte[] input, int offset, int length)
throws IOException
public int read(byte[] input) throws IOException
public final void readFully(byte[] input) throws IOException
public final void readFully(byte[] input, int offset, int length)
throws IOException
public void write(int b) throws IOException
public void write(byte[] data) throws IOException
public void write(byte[] data, int offset, int length)
throws IOException
public final boolean readBoolean() throws IOException
public final byte readByte() throws IOException
public final int readUnsignedByte() throws IOException
public final short readShort() throws IOException
public final int readUnsignedShort() throws IOException
public final char readChar() throws IOException
public final int readInt() throws IOException
Contact us :- 9313565406, 65495934
85
public final long readLong() throws IOException
public final float readFloat() throws IOException
public final double readDouble() throws IOException
public final String readLine() throws IOException
public final String readUTF() throws IOException
public final void writeBoolean(boolean b) throws IOException
public final void writeByte(int b) throws IOException
public final void writeShort(int s) throws IOException
public final void writeChar(int c) throws IOException
public final void writeInt(int i) throws IOException
public final void writeLong(long l) throws IOException
public final void writeFloat(float f) throws IOException
public final void writeDouble(double d) throws IOException
public final void writeBytes(String s) throws IOException
public final void writeChars(String s) throws IOException
public final void writeUTF(String s) throws IOException
Finally, they're a few miscellaneous methods:
public final FileDescriptor getFD() throws IOException
public int skipBytes(int n) throws IOException
public void close() throws IOException
Filename Filters
java.io.FilenameFilter is an interface that declares single method,
import java.io.*;
public class JavaFilter implements FilenameFilter {
public boolean accept(File directory, String filename) {
if (filename.endsWith(".java")) return true;
return false;
}
}
Readers and Writers
The java.io.Reader and java.io.Writer classes are abstract superclasses for classes that read and write character
based data. The subclasses are notable for handling the conversion between different character sets.
The java.io.Reader class
The methods of the java.io.Reader class are deliberately similar to the methods of the java.io.InputStream
class. However rather than working with bytes, they work with chars.
public int read() throws IOException
You can also read many characters into an array of chars. These methods return the number of bytes
successfully read or -1 if the end of stream occurs.
public int read(char[] text) throws IOException
public abstract int read(char[] text, int offset, int length)
throws IOException
The java.io.Writer class
The methods of the java.io.Writer class are deliberately similar to the methods of the java.io.OutputStream
class. However rather than working with bytes, they work with chars.
The basic write() method writes a single two-byte character with a value between 0 and 65535. The value is
taken from the two low-order bytes of the argument c.
Contact us :- 9313565406, 65495934
86
public void write(int c) throws IOException
public void write(char[] text) throws IOException
public abstract void write(char[] text, int offset, int length)
throws IOException
public void write(String s) throws IOException
public void write(String s, int offset, int length) throws IOException
The InputStreamReader Class
The java.io.InputStreamReader class serves as a bridge between byte streams and character streams: It reads
bytes from the input stream and translates them into characters according to a specified character encoding.
public InputStreamReader(InputStream in)
public InputStreamReader(InputStream in, String encoding)
throws UnsupportedEncodingException
For example, to attach an InputStreamReader to System.in with the default encoding:
InputStreamReader isr = new InputStreamReader(System.in);
On the other hand if you wanted to read a file that had been encoded using UTF-8, you might do this:
FileInputStream fis = new FileInputStream("file.utf8.txt");
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
public String getEncoding()
The getEncoding() method returns a string containing the name of the encoding used by this reader.
The other methods just override methods from java.io.Reader, but behave identically from the perspective of
the programmer.
public int read() throws IOException
public int read(char[] text, int offset, int length)
throws IOException
public boolean ready() throws IOException
public void close() throws IOException
The OutputStreamWriter Class
The java.io.OutputStreamWriter class connects byte streams and character streams: It writes bytes onto the
underlying output stream after translating characters according to a specified character encoding.
public OutputStreamWriter(OutputStream out, String enc)
throws UnsupportedEncodingException
public OutputStreamWriter(OutputStream out)
Reading Files
The FileReader class reads text files using the platform's default character encoding and the buffer size. If you
need to change these values, construct an InputStreamReader on a FileInputStream instead.
public FileReader(String fileName) throws FileNotFoundException
public FileReader(File file) throws FileNotFoundException
public FileReader(FileDescriptor fd)
Only the constructors are declared in this class. For example,
FileReader fr = new FileReader("36.html");
Writing Text Files
Contact us :- 9313565406, 65495934
87
The java.io.FileWriter class writes text files using the platform's default character encoding and the buffer size.
If you need to change these values, construct an OutputStreamReader on a
FileOutputStream instead.
public FileWriter(String fileName) throws IOException
public FileWriter(String fileName, boolean append) throws IOException
public FileWriter(File file) throws IOException
public FileWriter(FileDescriptor fd)
Only the constructors are declared in this class. For example,
FileWriter fw = new FileWriter("36.html");
Buffering Reads for Better Performance
// Implement the Unix cat utility in Java
import java.io.*;
class Cat {
public static void main (String args[]) {
String thisLine;
//Loop across the arguments
for (int i=0; i < args.length; i++) {
//Open the file for reading
try {
BufferedReader br = new BufferedReader(new FileReader(args[i]));
while ((thisLine = br.readLine()) != null) {
System.out.println(thisLine);
} // end while
} // end try
catch (IOException ex) {
System.err.println("Error: " + ex.getMessage());
}
} // end for
} // end main}
Line Numbering
The java.io.LineNumberReader class is a subclass of java.io.BufferedReader that keeps track of which line
you're currently reading. It has all the methods of BufferedReader including readLine(). It also has two
constructors, getLineNumber(), and setLineNumber() methods:
public LineNumberReader(Reader in)
public LineNumberReader(Reader in, int size)
public void setLineNumber(int lineNumber)
public int getLineNumber()
The following example reads a text file, line by line, and prints it to System.out but prefixes each line with a
line number:
import java.io.*;
class Linecat {
Contact us :- 9313565406, 65495934
88
public static void main (String args[]) {
String thisLine;
//Loop across the arguments
for (int i=0; i < args.length; i++) {
//Open the file for reading
try {
FileReader fr = new FileReader(args[i]);
LineNumberReader br = new LineNumberReader(fr);
while ((thisLine = br.readLine()) != null) {
System.out.println(br.getLineNumber() + ": " + thisLine);
} // end while
} // end try
catch (IOException ex) {
System.err.println("Error: " + ex);
}
} // end for
} // end main
}
PrintWriters
Sun would like to deprecate PrintStream and use PrintWriter instead, but that would break too much existing
code.
public PrintWriter(Writer out)
public PrintWriter(Writer out, boolean autoFlush)
public PrintWriter(OutputStream out)
public PrintWriter(OutputStream out, boolean autoFlush)
public void flush()
public void close()
public boolean checkError()
protected void setError()
public void write(int c)
public void write(char[] text, int offset, int length)
public void write(char[] text)
public void write(String s,
public void write(String s)
public void print(boolean b)
public void print(char c)
public void print(int i)
public void print(long l)
public void print(float f)
public void print(double d)
public void print(char s[])
public void print(String s)
public void print(Object obj)
public void println()
public void println(boolean b)
public void println(char c)
Contact us :- 9313565406, 65495934
89
public void println(int i)
public void println(long l)
public void println(float f)
public void println(double d)
public void println(char[] text)
public void println(String s)
public void println(Object o)
Multitasking
The earliest computers did one thing at a time. A lab computer might calculate detonation waves for one of
the physicists.
Time sharing operating systems were invented to allow multiple people to use one then very expensive
computer at the same time. On a time sharing system many people could run programs at the same time. The
operating system is responsible for splitting the time among the different programs that are running. That way
you can finish integrating your differential equation while the physics department's nuclear modeling program
is still churning away. The physics department nuclear modeling program might take two weeks to run instead
of three days, but everyone with the shorter programs was happy (at least until the physicists figured out how
to hack the computer so that it only ran their program).
Threads vs. Processes
Both threads and processes are methods of parallelizing an application. However, processes are independent
execution units that contain their own state information, use their own address spaces, and only interact with
each other via interprocess communication mechanisms (generally managed by the operating system).
Applications are typically divided into processes during the design phase, and a master process explicitly
spawns sub-processes when it makes sense to logically separate significant application functionality.
Processes, in other words, are an architectural construct.
What is a Thread?
A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and
independently of everything else that might be happening. A thread is like a classic program that starts at point
A and executes until it reaches point B. It does not have an event loop. A thread runs independently of
anything else happening in the computer. Without threads an entire program can be held up by one CPU
intensive task or one infinite loop, intentional or otherwise. With threads the other tasks that don't get stuck in
the loop can continue processing without waiting for the stuck task to finish.
How Java Uses Threads
Java applications and applets are naturally threaded. The runtime environment starts execution of the
program with the main() method in one thread. Garbage collection takes place in another thread. Screen
updating occurs in a third thread. There may be other threads running as well, mostly related to the behavior
of the virtual machine. All of this happens invisibly to the programmer. Some of the time you're only
concerned with what happens in the primary thread which includes the main() method of a program. If this is
the case you may not need to worry about threading at all.
The Thread Classes
Java has two ways a program can implement threading. One is to create a subclass of java.lang.Thread.
However sometimes you'll want to thread an object that's already a subclass of another class. Then you use
the java.lang.Runnable interface.
The Thread class has three primary methods that are used to control a thread:
public
void start()
public
void run()
Contact us :- 9313565406, 65495934
90
public final void stop()
The start() method prepares a thread to be run; the run() method actually performs the work of the thread;
and the stop() method halts the thread. The thread dies when the run() method terminates or when the
thread's stop() method is invoked.
public abstract void run()
A simple thread
public class BytePrinter extends Thread {
public void run() {
for (int b = -128; b < 128; b++) {
System.out.println(b);
}
}
}
Invoking a thread
For example, the following program launches a single BytePrinter thread:
public class ThreadTest {
public static void main(String[] args) {
System.out.println("Constructing the thread...");
BytePrinter bp = new BytePrinter();
System.out.println("Starting the thread...");
bp.start();
System.out.println("The thread has been started.");
System.out.println("The main() method is finishing.");
return;
}
}
Here's some sample output:
$ java ThreadTest
Constructing the thread...
Starting the thread...
The thread has been started.
The main() method is finishing.
-128
-127
-126
-125
-124
-123
-122
-121
-120
...
Contact us :- 9313565406, 65495934
91
Multiple threads
The following program launches three BytePrinter threads:
public class ThreadsTest {
public static void main(String[] args) {
BytePrinter bp1 = new BytePrinter();
BytePrinter bp2 = new BytePrinter();
BytePrinter bp3 = new BytePrinter();
bp1.start();
bp2.start();
bp3.start();
}
}
The order of the output you see from this program is implementation dependent, and mostly unpredictable. It
may look something like this:
-128
-127
-126
...
125
126
127
-128
-127
-126
...
125
126
127
-128
-127
-126
...
125
126
127
In this case the three threads run sequentially, one after the other. However on a few systems you may see
something different
Multiple preemptive threads
However on a few systems you may see something like this:
-128
-127
-126
-125
-124
-123
-128
-127
-126
Contact us :- 9313565406, 65495934
92
-125
-128
-127
-126
-125
-124
-123
-122
-121
-120
-119
-124
-123
...
125
126
127
Naming Threads
You can give different threads in the same class names so you can tell them apart. The following constructor
allows you to do that:
public Thread(String name)
This is normally called from the constructor of a subclass, like this:
public class NamedBytePrinter extends Thread {
public NamedBytePrinter(String name) {
super(name);
}
public void run() {
for (int b = -128; b < 128; b++) {
System.out.println(this.getName() + ": " + b);
}
}
}
The getName() method of the Thread class returns this value.
The following program now distinguishes the output of different threads:
public class NamedThreadsTest {
public static void main(String[] args) {
NamedBytePrinter frank = new NamedBytePrinter("Frank");
NamedBytePrinter mary = new NamedBytePrinter("Mary");
NamedBytePrinter chris = new NamedBytePrinter("Chris");
frank.start();
mary.start();
chris.start();
}
}
Named Threads Output
For example,
Contact us :- 9313565406, 65495934
93
Frank: -128
Mary: -128
Mary: -127
Mary: -126
Mary: -125
Mary: -124
Mary: -123
Mary: -122
Mary: -121
Chris: -128
Chris: -127
Chris: -126
Chris: -125
Chris: -124
Chris: -123
Chris: -122
Chris: -121
Chris: -120
Mary: -120
Mary: -119
Chris: -119
Chris: -118
Frank: -127
Frank: -126
Frank: -125
...
Mary: 121
Mary: 122
Mary: 123
Chris: 127
Frank: 123
Frank: 124
Frank: 125
Mary: 124
Mary: 125
Frank: 126
Frank: 127
Mary: 126
Mary: 127
Again, the exact ordering and even whether the thread output is intermixed, can vary from system to system
and run to run.
Thread Priorities
Not all threads are created equal. Sometimes you want to give one thread more time than another. Threads
that interact with the user should get very high priorities. Threads that calculate in the background should get
low priorities.
Thread priorities are defined as integers between 1 and 10. Ten is the highest priority. One is the lowest. The
normal priority is five. Higher priority threads get more CPU time.
Warning: This is exactly opposite to the normal UNIX way of prioritizing processes where the higher the
priority number of a process, the less CPU time the process gets.
For your convenience java.lang.Thread defines three mnemonic constants, Thread.MAX_PRIORITY,
Thread.MIN_PRIORITY and Thread.NORM_PRIORITY which you can use in place of the numeric values.
You set a thread's priority with the setPriority(int priority) method. The following program sets Chris's priority
higher than Mary's whose priority is higher than Frank's. It is therefore likely that even though Chris starts last
and Frank starts first, Chris will finish before Mary who will finish before Frank.
public class MixedPriorityTest {
Contact us :- 9313565406, 65495934
94
public static void main(String[] args) {
NamedBytePrinter frank = new NamedBytePrinter("Frank");
NamedBytePrinter mary = new NamedBytePrinter("Mary");
NamedBytePrinter chris = new NamedBytePrinter("Chris");
frank.setPriority(Thread.MIN_PRIORITY);
mary.setPriority(Thread.NORM_PRIORITY);
chris.setPriority(Thread.MAX_PRIORITY);
frank.start();
mary.start();
chris.start();
}
}
Sleep
Sometimes the computer may run too fast for the human beings. If this is the case you need to slow it down.
You can make a particular Thread slow down by interspersing it with calls to the Thread.sleep(ms) method. ms
is the number of milliseconds you want the thread to wait before proceeding on. There are one thousand
milliseconds in a second.
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
}
To delay a program for a fixed amount of time you often do something like this:
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
}
Safely Stopping Threads
Stopping threads at arbitrary times can leave objects in inconsistent, half-updated states they could not
normally reach.
public class StoppableThread extends Thread {
private boolean stopRequested;
public void run() {
while (true) {
System.out.println("Hee");
System.out.println("Ha");
System.out.println("Ho");
System.out.println("");
if (stopRequested) {
cleanup();
Contact us :- 9313565406, 65495934
95
break;
}
}
}
public void requestStop() {
stopRequested = true;
}
private void cleanup() {
// ...
}
}
Synchronization: the problem. part 1
So far all the threads have run independently of each other. One thread did not need to know what another
thread was doing. Sometimes, however, threads need to share data. In this case it is important to ensure that
one thread doesn't change the data while the other thread is executing. The classic example is file access. If
one thread is writing to a file while another thread is reading the file, it's likely that the thread that's reading
the file will get corrupt data.
For example, consider the following toy problem:
public class Counter {
private int count = 0;
public void count() {
int limit = count + 100;
while (count++ != limit) System.out.println(count);
}
}
public class CounterThread extends Thread {
private Counter c;
public CounterThread(Counter c) {
this.c = c;
}
public void run() {
c.count();
}
}
public class CounterApp1 {
public static void main(String[] args) {
Counter c = new Counter();
CounterThread ct1 = new CounterThread(c);
ct1.start();
Contact us :- 9313565406, 65495934
96
}
}
public class CounterApp2 {
public static void main(String[] args) {
Counter c = new Counter();
CounterThread ct1 = new CounterThread(c);
CounterThread ct2 = new CounterThread(c);
ct1.start();
ct2.start();
}
}
public class CounterApp3 {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
CounterThread ct1 = new CounterThread(c1);
CounterThread ct2 = new CounterThread(c2);
ct1.start();
ct2.start();
}
}
Synchronization: the problem, part 2
The fact is there's no guarantee what the output will be. The Roaster DR3 VM gave me the following output
the first time I ran this program:
1
3
4
5
6
7
8
9
10
11
...
90
91
92
93
94
95
96
97
98
Contact us :- 9313565406, 65495934
97
99
100
101
102
Synchronization: the problem, part 3
The second time I ran it on the same VM it appeared to be caught in an infinite loop. The output looked like
this:
1
3
4
5
6
7
8
9
10
11
...
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
...
342
343
344
345
Synchronization: the problem, part 4
Sun's JDK for the Mac 1.0.2 behaved similarly. However it skipped 7 and stopped at 107:
1
2
3
4
5
6
8
9
10
Contact us :- 9313565406, 65495934
98
11
...
98
99
100
101
102
103
104
105
106
107
Synchronizing on Objects
Magic Feather example
Each object has a magic feather called a monitor. When you use the synchronized keyword on a method,
you're gaining the monitor of the current object or locking it. As long as a thread possesses the monitor or lock
of an object no other thread can get the lock for that object.
public class Counter {
private int count = 0;
public void count() {
int localCopy = this.count;
int limit = localCopy + 100;
while (localCopy++ != limit) System.out.println(localCopy);
this.count = localCopy;
}
}
You can fix this by synchronizing the lines of code that refer to the field:
public void count() {
int localCopy;
synchronized (this) {
localCopy = this.count;
}
int limit = localCopy + 100;
while (localCopy++ != limit) System.out.println(localCopy);
synchronized (this) {
this.count = localCopy;
}
}
Thread Groups
Threads are organized into thread groups. A thread group is simply a related collection of threads. For
instance, for security reasons all the threads an applet spawns are members of a particular thread group. The
applet is allowed to manipulate threads in its own group but not in others. Thus an applet can't turn off the
system's garbage collection thread, for example.
Thread groups are organized into a hierarchy of parents and children.
The following program prints all active threads by using the getThreadGroup() method of java.lang.Thread and
getParent() method of java.lang.ThreadGroup to walk up to the top level thread group; then using enumerate
to list all the threads in the main thread group and its children (which covers all thread groups).
Contact us :- 9313565406, 65495934
99
public class AllThreads {
public static void main(String[] args) {
ThreadGroup top = Thread.currentThread().getThreadGroup();
while(true) {
if (top.getParent() != null) top = top.getParent();
else break;
}
Thread[] theThreads = new Thread[top.activeCount()];
top.enumerate(theThreads);
for (int i = 0; i < theThreads.length; i++) {
System.out.println(theThreads[i]);
}
}
}
The exact list of threads varies from system to system, but it should look something like this:
Thread[clock handler,11,system]
Thread[idle thread,0,system]
Thread[Async Garbage Collector,1,system]
Thread[Finalizer thread,1,system]
Thread[main,1,main]
Thread[Thread-0,5,main]
Daemon Threads
Threads that work in the background to support the runtime environment are called daemon threads. For
example, the clock handler thread, the idle thread, the garbage collector thread, the screen updater thread,
and the garbage collector thread are all daemon threads. The virtual machine exits whenever all non-daemon
threads have completed.
public final void setDaemon(boolean isDaemon)
public final boolean isDaemon()
By default a thread you create is not a daemon thread. However you can use the setDaemon(true) method to
turn it into one.
Cooperative vs. Preemptive Threading
In cooperative models, once a thread is given control it continues to run until it explicitly yields control or it
blocks. In a preemptive model, the virtual machine is allowed to step in and hand control from one thread to
another at any time. Both models have their advantages and disadvantages.
Cooperating
Since you can't be sure whether you'll be working with a cooperative or preemptive model, it's important not
to assume preemption is available. CPU-intensive threads should yield control at periodic intervals. There are
four different ways a thread can give up control and allow other threads to run.
It can block.
It can call Thread.yield().
It can go to sleep.
It can be suspended.
When a program calls Thread.yield(), it's signifying that the current thread, the one which called Thread.yield(),
is willing to step aside in favor of another thread. The VM looks to see if any other threads of the same priority
are ready to run. If any are, it pauses the currently executing thread and passes control to the next thread in
line. If no other threads of the same or higher priority are ready to run, control returns to the thread that
Contact us :- 9313565406, 65495934
100
yielded. Thus Thread.yield() only signals a willingness to give up control. It does not guarantee that the thread
will actually stop. That depends completely on what other threads exist and what their status is.
Animation
Animation is one of the primary uses of the Runnable interface. To animate objects in Java, you create a thread
that calculates successive frames and then calls repaint() to paint the screen. You could just stick an infinite
loop in your paint() method, but that is quite dangerous, especially on non-preemptive systems like the Mac. It
also doesn't provide any support for timing.
import java.awt.*;
import java.applet.*;
public class Bounce extends Applet implements Runnable {
private Rectangle r;
private int deltaX = 1;
private int deltaY = 1;
public void init () {
r = new Rectangle( 30, 40, 20, 20);
Thread t = new Thread(this);
t.start();
}
public void paint (Graphics g) {
g.setColor(Color.red);
g.fillOval(r.x, r.y, r.width, r.height);
}
public void run() {
while (true) { // infinite loop
r.x += deltaX;
r.y += deltaY;
if (r.x >= size().width || r.x < 0) deltaX *= -1;
if (r.y >= size().height || r.y < 0) deltaY *= -1;
this.repaint();
}
}
}
Timing
True animation should provide a timing engine. This ball is rather fast on some platforms, rather slow on
others. You'd like its performance to be more uniform.
import java.awt.*;
import java.applet.*;
import java.util.*;
public class SleepyBounce extends Applet implements Runnable {
Contact us :- 9313565406, 65495934
101
private Rectangle r;
private int deltaX = 1;
private int deltaY = 1;
private int speed = 50;
public void init () {
r = new Rectangle(37, 17, 20, 20);
Thread t = new Thread(this);
t.start();
}
public void paint (Graphics g) {
g.setColor(Color.red);
g.fillOval(r.x, r.y, r.width, r.height);
}
public void run() {
while (true) { // infinite loop
long t1 = (new Date()).getTime();
r.x += deltaX;
r.y += deltaY;
if (r.x >= size().width || r.x < 0) deltaX *= -1;
if (r.y >= size().height || r.y < 0) deltaY *= -1;
this.repaint();
long t2 = (new Date()).getTime();
long sleepTime = speed - (t2 - t1);
if (sleepTime > 0) {
try {
Thread.sleep(sleepTime);
}
catch (InterruptedException ie) {
}
}
}
}
}
Flicker
You may or may not have noticed some flickering in the last applet. It's quite common for animation applets to
flicker. The problem has to do with a failure to sync between when the physical display wants to redraw and
when the applet wants to redraw. If they don't match up there's flicker.
import java.awt.*;
import java.applet.*;
import java.util.*;
public class ClipBounce extends Applet implements Runnable {
private Rectangle r;
private int deltaX = 1;
private int deltaY = 1;
private int speed = 30;
Contact us :- 9313565406, 65495934
102
public void init () {
r = new Rectangle(37, 17, 20, 20);
Thread t = new Thread(this);
t.start();
}
public void paint (Graphics g) {
g.setColor(Color.red);
g.clipRect(r.x, r.y, r.width, r.height);
g.fillOval(r.x, r.y, r.width, r.height);
}
public void run() {
while (true) { // infinite loop
long t1 = (new Date()).getTime();
r.x += deltaX;
r.y += deltaY;
if (r.x >= size().width || r.x < 0) deltaX *= -1;
if (r.y >= size().height || r.y < 0) deltaY *= -1;
this.repaint();
long t2 = (new Date()).getTime();
try {
Thread.sleep(speed - (t2 - t1));
}
catch (InterruptedException ie) {
}
}
}
}
Off Screen Buffers
The second and often more effective method to avoid flicker is to use offscreen images and the update()
method. By overriding the update() method you can do all your painting in an offscreen Image, and then just
copy the final Image onto the screen. Copying an image happens much more quickly and evenly than painting
individual elements so there's no visible flicker.
private Image offScreenImage;
private Dimension offScreenSize;
private Graphics offScreenGraphics;
public final synchronized void update (Graphics g) {
Dimension d = this.getSize();
if((this.offScreenImage == null)
|| (d.width != this.offScreenSize.width)
|| (d.height != this.offScreenSize.height)) {
this.offScreenImage = this.createImage(d.width, d.height);
this.offScreenSize = d;
this.offScreenGraphics = this.offScreenImage.getGraphics();
}
this.offScreenGraphics.clearRect(0, 0, d.width, d.height);
Contact us :- 9313565406, 65495934
103
this.paint(this.offScreenGraphics);
g.drawImage(this.offScreenImage, 0, 0, null);
}
Stopping Animations
It's a good idea to give the user a way to stop a thread from running. With simple animation threads like this,
the custom is that a mouse click stops the animation if it's running and restarts it if it isn't.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;
public class FlickBounce extends Applet
implements Runnable, MouseListener {
private Rectangle r;
private int deltaX = 1;
private int deltaY = 1;
private int speed = 30;
private boolean bouncing = false;
private Thread bounce;
public void init () {
r = new Rectangle(37, 17, 20, 20);
addMouseListener(this);
bounce = new Thread(this);
}
public void start() {
bounce.start();
bouncing = true;
}
private Image offScreenImage;
private Dimension offScreenSize;
private Graphics offScreenGraphics;
public final synchronized void update (Graphics g) {
Dimension d = this.getSize();
if((this.offScreenImage == null)
|| (d.width != this.offScreenSize.width)
|| (d.height != this.offScreenSize.height)) {
this.offScreenImage = this.createImage(d.width, d.height);
this.offScreenSize = d;
this.offScreenGraphics = this.offScreenImage.getGraphics();
}
offScreenGraphics.clearRect(0, 0, d.width, d.height);
this.paint(this.offScreenGraphics);
g.drawImage(this.offScreenImage, 0, 0, null);
}
public void paint (Graphics g) {
Contact us :- 9313565406, 65495934
104
g.setColor(Color.red);
g.fillOval(r.x, r.y, r.width, r.height);
}
public void run() {
while (true) { // infinite loop
long t1 = (new Date()).getTime();
r.x += deltaX;
r.y += deltaY;
if (r.x >= size().width || r.x < 0) deltaX *= -1;
if (r.y >= size().height || r.y < 0) deltaY *= -1;
this.repaint();
long t2 = (new Date()).getTime();
try {
Thread.sleep(speed - (t2 - t1));
}
catch (InterruptedException ie) {
}
}
}
public void mouseClicked(MouseEvent evt) {
if (bouncing) {
bounce.suspend();
bouncing = false;
}
else {
bounce.resume();
bouncing = true;
}
}
public void mousePressed(MouseEvent evt) {}
public void mouseReleased(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {}
}
The Classes in java.net
The Classes
ContentHandler
DatagramPacket
DatagramSocket
DatagramSocketImpl
HttpURLConnection
InetAddress
MulticastSocket
ServerSocket
Socket
SocketImpl
Contact us :- 9313565406, 65495934
105
URL
URLConnection
URLEncoder
URLStreamHandler
The Interfaces
ContentHandlerFactory
FileNameMap
SocketImplFactory
URLStreamHandlerFactory
Exceptions
BindException
ConnectException
MalformedURLException
NoRouteToHostException
ProtocolException
SocketException
UnknownHostException
UnknownServiceException
Internet Addresses
Every computer on the Internet is identified by a unique, four-byte IP address. This is typically written in dotted
quad format like 199.1.32.90 where each byte is an unsigned value between 0 and 255.
public static InetAddress getByName(String host)
throws UnknownHostException
public static InetAddress[] getAllByName(String host)
throws UnknownHostException
public static InetAddress getLocalHost()
throws UnknownHostException
public boolean isMulticastAddress()
public String getHostName()
public byte[] getAddress()
public String getHostAddress()
public int hashCode()
public boolean equals(Object obj)
public String toString()
Ports
As a general (but far from absolute) rule each computer only has one Internet address. However, computers
often need to communicate with more than one host at a time. For example, there may be multiple ftp
sessions, a few web connections, and a chat program all running at the same time.
Protocols
Loosely speaking, a protocol defines how two hosts talk to each other. For example, in radio communications a
protocol might say that when one participant is finished speaking, he or she says "Over" to tell the other end
that it's OK to start talking. In networking a protocol defines what is and is not acceptable for one participant in
a conversation to say to the other at a given moment in time.
For example the daytime protocol, specified in RFC 867, says that the client connects to the server on port 13.
The server then tells the client the current time in a human readable format and then closes the connection.
Contact us :- 9313565406, 65495934
106
On the other hand the time protocol, specified in RFC 868, specifies a binary representation for the time that's
legible to computers.
Network Address Translation (NAT)
There aren't enough IP addresses to go around
Use different addresses locally and remotely and remap on the fly using Network Address Translation
Routers
Proxy servers
Firewalls
Creating InetAddress objects
The InetAddress class is a little unusual in that it doesn't have any public constructors. Instead you pass the
host name or string format of the dotted quad address to the static
InetAddress.getByName() method like this:
try {
InetAddress utopia = InetAddress.getByName("utopia.poly.edu");
InetAddress duke = InetAddress.getByName("128.238.2.92");
}
catch (UnknownHostException ex) {
System.err.println(ex);
}
import java.net.*;
public class AppleAddresses {
public static void main (String args[]) {
try {
InetAddress[] addresses = InetAddress.getAllByName("www.apple.com");
for (int i = 0; i < addresses.length; i++) {
System.out.println(addresses[i]);
}
}
catch (UnknownHostException ex) {
System.out.println("Could not find www.apple.com");
}
}
}
This prints the following:
www.apple.com/17.254.3.28
www.apple.com/17.254.3.37
www.apple.com/17.254.3.61
www.apple.com/17.254.3.21
Finally the static InetAddress.getLocalHost() method returns an InetAddress object that contains the address of
the computer the program is running on.
try {
InetAddress me = InetAddress.getLocalHost();
}
catch (UnknownHostException e) {
System.err.println(e);
Contact us :- 9313565406, 65495934
107
}
Parsing InetAddressess
You can ask InetAddress object for its host name as a string, its IP address as a string, its IP address as a byte
array, and whether or not it's a multicast address. The necessary methods are:
public boolean isMulticastAddress()
public String getHostName()
public byte[] getAddress()
public String getHostAddress()
The following program prints out this information about the local host.
import java.net.*;
public class Local {
public static void main(String[] args) {
try {
InetAddress me = InetAddress.getLocalHost();
System.out.println("My name is " + me.getHostName());
System.out.println("My address is " + me.getHostAddress());
byte[] address = me.getAddress();
for (int i = 0; i < address.length; i++) {
System.out.print(address[i] + " ");
}
System.out.println();
}
catch (UnknownHostException e) {
System.err.println("Could not determine local address.");
System.err.println("Perhaps the network is down?");
} }}
My name is macfaq.dialup.cloud9.net
My address is 168.100.203.234
-88 100 -53 -22
URLs
A URL, short for "Uniform Resource Locator", is a way to unambiguously identify the location of a resource on
the Internet. Some typical URLs look like:
http://www.javasoft.com/
http://www.google.com/search?hl=en&lr=&ie=ISO-8859-1&q=Chumbawamba&btnG=Google+Search
file:///Macintosh%20HD/Java/Docs/JDK%201.1.1%20docs/api/java.net.InetAddress.html#_top_
http://www.macintouch.com:80/newsrecent.shtml
ftp://ftp.info.apple.com/pub/
mailto:[email protected]
telnet://utopia.poly.edu
Most URLs can be broken into about five pieces, not all of which are necessarily present in any given URL.
These are:
the protocol
the host
the port
the file
the fragment identifier (a.k.a. ref, section, or anchor)
Contact us :- 9313565406, 65495934
108
the query string
The java.net.URL class
file
ftp
gopher
http
mailto
appletresource
doc
netdoc
systemresource
verbatim
Constructing URL Objects
There are four constructors in the java.net.URL class. All can throw MalformedURLExceptions:
public URL(String u) throws MalformedURLException
public URL(String protocol, String host, String file)
throws MalformedURLException
public URL(String protocol, String host, int port, String file)
throws MalformedURLException
public URL(URL context, String u) throws MalformedURLException
Given a complete absolute URL like http://www.poly.edu/schedule/fall97/bgrad.html#cs, you construct a URL
object for that URL like this:
URL u = null;
try {
u = new URL("http://www.poly.edu/schedule/fall97/bgrad.html#cs");
}
catch (MalformedURLException ex) {
}
You can also construct the URL by passing its pieces to the constructor, like this:
URL u = null;
try {
u = new URL("http", "www.poly.edu", "/schedule/fall97/bgrad.html#cs");
}
catch (MalformedURLException ex) {
}
You don't normally need to specify a port for a URL. Most protocols have default ports. For instance, the http
port is 80; but sometimes this does change and in that case you can use the third constructor:
URL u = null;
try {
u = new URL("http", "www.poly.edu", 80, "/schedule/fall97/bgrad.html#cs");
}
catch (MalformedURLException ex) {
}
The fourth constructor above creates URLs relative to a given URL. For example,
try {
URL u1 = new URL("http://www.cafeaulait.org/course/week12/07.html");
URL u2 = new URL(u1, "08.html");
}
catch (MalformedURLException ex) {
}
Contact us :- 9313565406, 65495934
109
Parsing URLs
The java.net.URL class has five methods to split a URL into its component parts. These are:
public String getProtocol()
public String getHost()
public int getPort()
public String getFile()
public String getRef()
For example,
try {
URL u = new URL("http://www.poly.edu/schedule/fall97/bgrad.html#cs");
System.out.println("The protocol is " + u.getProtocol());
System.out.println("The host is " + u.getHost());
System.out.println("The port is " + u.getPort());
System.out.println("The file is " + u.getFile());
System.out.println("The anchor is " + u.getRef());
}
catch (MalformedURLException ex) {
}
Reading Data from a URL
public final InputStream openStream() throws IOException
The openStream() method opens a connection to the server specified in the URL and returns an InputStream
fed by the data from that connection. This allows you to download data from the server. Any headers that
come before the actual data or file requested are stripped off before, the stream is opened. You get only raw
data.
import java.net.*;
import java.io.*;
public class Webcat {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
try {
URL u = new URL(args[i]);
InputStream is = u.openStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String theLine;
while ((theLine = br.readLine()) != null) {
System.out.println(theLine);
}
}
catch (MalformedURLException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
}
Sockets
Before data is sent across the Internet from one host to another using TCP/IP, it is split into packets of varying
but finite size called datagrams. Datagrams range in size from a few dozen bytes to about 60,000 bytes.
Contact us :- 9313565406, 65495934
110
Anything larger than this, and often things smaller than this, needs to be split into smaller pieces before it can
be transmitted. The advantage is that if one packet is lost, it can be retransmitted without requiring redelivery
of all other packets. Furthermore if packets arrive out of order they can be reordered at the receiving end of
the connection.
There are four fundamental operations a socket performs. These are:
1. Connect to a remote machine
2. Send data
3. Receive data
4. Close the connection
The java.net.Socket class
The java.net.Socket class allows you to perform all four fundamental socket operations. You can connect to
remote machines; you can send data; you can receive data; you can close the connection.
public Socket(String host, int port)
throws UnknownHostException, IOException
public Socket(InetAddress address, int port) throws IOException
public Socket(String host, int port, InetAddress localAddress,
int localPort) throws IOException
public Socket(InetAddress address, int port, InetAddress localAddress,
int localPort) throws IOException
Sending and receiving data is accomplished with output and input streams. There are methods to get an input
stream for a socket and an output stream for the socket.
public InputStream getInputStream() throws IOException
public OutputStream getOutputStream() throws IOException
There's a method to close a socket.
public void close() throws IOException
There are also methods to set various socket options. Most of the time the defaults are fine.
public void setTcpNoDelay(boolean on) throws SocketException
public boolean getTcpNoDelay() throws SocketException
public void setSoLinger(boolean on, int val) throws SocketException
public int getSoLinger() throws SocketException
public void setSoTimeout(int timeout) throws SocketException
public int getSoTimeout() throws SocketException
public static void setSocketImplFactory(SocketImplFactory fac)
throws IOException
There are methods to return information about the socket:
public InetAddress getInetAddress()
public InetAddress getLocalAddress()
public int
getPort()
public int
getLocalPort()
Finally there's the usual toString() method:
public String toString()
Constructing Socket Objects
There are four public, non-deprecated constructors in the Socket class. (There are also two protected
constructors and two deprecated constructors I won't discuss.)
public Socket(String host, int port) throws UnknownHostException, IOException
public Socket(InetAddress address, int port) throws IOException
public Socket(String host, int port, InetAddress localAddr, int localPort)
Contact us :- 9313565406, 65495934
111
throws IOException
public Socket(InetAddress address, int port, InetAddress localAddr, int localPort)
throws IOException
Port Scanner
You cannot just connect to any port on any host. The remote host must actually be listening for connections on
that port. You can use the constructors to determine which ports on a host are listening for connections.
import java.net.*;
import java.io.IOException;
public class PortScanner {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
try {
InetAddress ia = InetAddress.getByName(args[i]);
scan(ia);
}
catch (UnknownHostException ex) {
System.err.println(args[i] + " is not a valid host name.");
}
}
}
public static void scan(InetAddress remote) {
// Do I need to synchronize remote?
// What happens if someone changes it while this method
// is running?
String hostname = remote.getHostName();
for (int port = 0; port < 65536; port++) {
try {
Socket s = new Socket(remote, port);
System.out.println("A server is listening on port " + port
+ " of " + hostname);
s.close();
}
catch (IOException ex) {
// The remote host is not listening on this port
}
}
}
public static void scan(String remote) throws UnknownHostException {
// Why throw the UnknownHostException? Why not catch it like I did
// in the main() method?
InetAddress ia = InetAddress.getByName(remote);
scan(ia);
Contact us :- 9313565406, 65495934
112
}
}
Reading Input from a Socket
Once a socket has connected you send data to the server via an output stream. You receive data from the
server via an input stream. Exactly what the data you send and receive means often depends on the protocol.
For example, the following code fragment connects to the daytime server on port 13 of metalab.unc.edu, and
displays the data it sends.
try {
Socket s = new Socket("metalab.unc.edu", 13);
InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String theTime = br.readLine();
System.out.println(theTime);
}
catch (IOException ex) {
return (new Date()).toString();
}
Writing Output to a Socket
The getOutputStream() method returns an OutputStream which writes data to the socket.
For example, the following program connects to the discard server on port 9 of metalab.unc.edu, and sends it
data read from System.in.
byte[] b = new byte[128];
try {
Socket s = new Socket("metalab.unc.edu", 9);
OutputStream out = s.getOutputStream();
while (true) {
int m = System.in.read(b, 0, b.length);
if (m == -1) break;
out.write(b, 0, m);
}
s.close();
}
catch (IOException ex) {
}
Reading and Writing to a Socket for HTTP
The following example sends a request to an http server using a socket's output stream; then it reads the
response using the socket's input stream. HTTP servers close the connection when they've sent the response.
import java.net.*;
import java.io.*;
public class Grabber {
public static void main(String[] args) {
int port = 80;
for (int i = 0; i < args.length; i++) {
Contact us :- 9313565406, 65495934
113
try {
URL u = new URL(args[i]);
if (u.getPort() != -1) port = u.getPort();
if (!(u.getProtocol().equalsIgnoreCase("http"))) {
System.err.println("Sorry. I only understand http.");
continue;
}
Socket s = new Socket(u.getHost(), port);
OutputStream theOutput = s.getOutputStream();
// no auto-flushing
PrintWriter pw = new PrintWriter(theOutput, false);
// native line endings are uncertain so add them manually
pw.print("GET " + u.getFile() + " HTTP/1.0\r\n");
pw.print("Accept: text/plain, text/html, text/*\r\n");
pw.print("\r\n");
pw.flush();
InputStream in = s.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
int c;
while ((c = br.read()) != -1) {
System.out.print((char) c);
}
}
catch (MalformedURLException ex) {
System.err.println(args[i] + " is not a valid URL");
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
}
Reading and Writing to a Socket for Echo
The echo protocol simply echoes back anything its sent. The following echo client reads data from an input
stream, then passes it out to an output stream connected to a socket, connected to a network echo server. A
second thread reads the input coming back from the server. The main() method reads some file names from
the command line and passes them into the output stream.
import java.net.*;
import java.io.*;
import java.util.*;
public class Echo {
InetAddress server;
int port = 7;
InputStream theInput;
public static void main(String[] args) {
if (args.length == 0) {
System.err.println("Usage: java Echo file1 file2...");
System.exit(1);
Contact us :- 9313565406, 65495934
114
}
Vector v = new Vector();
for (int i = 0; i < args.length; i++) {
try {
FileInputStream fis = new FileInputStream(args[i]);
v.addElement(fis);
}
catch (IOException ex) {
}
}
InputStream in = new SequenceInputStream(v.elements());
try {
Echo d = new Echo("metalab.unc.edu", in);
d.start();
}
catch (IOException ex) {
System.err.println(ex);
}
}
public Echo() throws UnknownHostException {
this (InetAddress.getLocalHost(), System.in);
}
public Echo(String name) throws UnknownHostException {
this(InetAddress.getByName(name), System.in);
}
public Echo(String name, InputStream is) throws UnknownHostException {
this(InetAddress.getByName(name), is);
}
public Echo(InetAddress server) {
this(server, System.in);
}
public Echo(InetAddress server, InputStream is) {
this.server = server;
theInput = is;
}
public void start() {
try {
Socket s = new Socket(server, port);
CopyThread toServer = new CopyThread("toServer",
theInput, s.getOutputStream());
CopyThread fromServer = new CopyThread("fromServer",
s.getInputStream(), System.out);
toServer.start();
fromServer.start();
}
catch (IOException ex) {
System.err.println(ex);
Contact us :- 9313565406, 65495934
115
}
}
}
class CopyThread extends Thread {
InputStream in;
OutputStream out;
public CopyThread(String name, InputStream in, OutputStream out) {
super(name);
this.in = in;
this.out = out;
}
public void run() {
byte[] b = new byte[128];
try {
while (true) {
int m = in.read(b, 0, b.length);
if (m == -1) {
System.out.println(getName() + " done!");
break;
}
out.write(b, 0, m);
}
}
catch (IOException ex) {
}
}
}
Server Sockets
There are two ends to each connection: the client that is the host that initiates the connection, and the server,
that is the host that responds to the connection. Clients and servers are connected by sockets.
The java.net.ServerSocket Class
The java.net.ServerSocket class represents a server socket. It is constructed on a particular port. Then it calls
accept() to listen for incoming connections. accept() blocks until a connection is detected. Then accept()
returns a java.net.Socket object you use to perform the actual communication with the client.
There are three constructors that let you specify the port to bind to, the queue length for incoming
connections, and the IP address to bind to:
public ServerSocket(int port) throws IOException
public ServerSocket(int port, int backlog) throws IOException
public ServerSocket(int port, int backlog, InetAddress bindAddr)
throws IOException
The accept() and close() methods provide the basic functionality of a server socket.
public Socket accept() throws IOException
public void close() throws IOException
On a server with multiple IP addresses, the getInetAddress() method tells you which one this server socket is
listening to. The getLocalPort() method tells you which port you're listening to.
Contact us :- 9313565406, 65495934
116
public InetAddress getInetAddress()
public int getLocalPort()
There are three methods to set and get various options. The defaults are generally fine.
public void setSoTimeout(int timeout) throws SocketException
public int getSoTimeout() throws IOException
public static void setSocketFactory(SocketImplFactory fac)
throws IOException
Finally, there's the usual toString() method:
public String toString()
The java.net.ServerSocket Constructors
The java.net.ServerSocket class has three constructors that let you specify the port to bind to, the queue
length for incoming connections, and the IP address to bind to:
public ServerSocket(int port) throws IOException
public ServerSocket(int port, int backlog) throws IOException
public ServerSocket(int port, int backlog, InetAddress bindAddr)
throws IOException
Normally you only specify the port you want to listen on, like this:
try {
ServerSocket ss = new ServerSocket(80);
}
catch (IOException ex) {
System.err.println(ex);
}
When you create a ServerSocket object, it attempts to bind to the port on the local host given by the port
argument. If another server socket is already listening to the port, then a java.net.BindException, a subclass of
java.io.IOException, is thrown. No more than one process or thread can listen to a particular port at a time.
This includes non-Java processes or threads. For example, if there's already an HTTP server running on port 80,
you won't be able to bind to port 80.
On Unix systems (but not Windows or the Mac) your program must be running as root to bind to a port
between 1 and 1023.
0 is a special port number. It tells Java to pick an available port. You can then find out what port it's picked with
the getLocalPort() method. This is useful if the client and the server have already established a separate
channel of communication over which the chosen port number can be communicated.
For example, the ftp protocol uses two sockets. The initial connection is made by the client to the server to
send commands. One of the commands sent tells the server the name of the port on which the client is
listening. The server then connects to the client on this port to send data.
try {
ServerSocket ftpdata = new ServerSocket(0);
int port = ftpdata.getLocalPort();
}
catch (IOException ex) {
System.err.println(ex);
}
Adjusting the queue length
public ServerSocket(int port, int backlog) throws IOException
The operating system stores incoming connections for each port in a first-in, first-out queue until they can be
accepted. The default queue length varies from operating system to operating system. However, it tends to be
between 5 and 50. Once the queue fills up further connections are refused until space opens up in the queue.
If you think you aren't going to be processing connections very quickly you may wish to expand the queue
when you construct the server socket. For example,
try {
Contact us :- 9313565406, 65495934
117
ServerSocket httpd = new ServerSocket(80, 50);
}
catch (IOException ex) {
System.err.println(ex);
}
Choosing a local address
Many hosts have more than one IP address. This is especially common at web server farms where a single
machine is shared by multiple sites. By default, a server socket binds to all available IP addresses. That is it
accepts connections addressed to any of the local IP addresses on a given port. However you can modify that
behavior with this constructor:
public ServerSocket(int port, int backlog, InetAddress bindAddr)
throws IOException
You must also specify the queue length in this constructor.
try {
InetAddress ia = InetAddress.getByName("199.1.32.90");
ServerSocket ss = new ServerSocket(80, 50, ia);
}
catch (IOException ex) {
System.err.println(ex);
}
How would you bind to some but not all IP addresses on the server?
Reading Data with a ServerSocket
The port scanner pretty much exhausts what you can do with just the constructors. Almost all ServerSocket
objects you create will use their accept() method to connect to a client.
public Socket accept() throws IOException
There are no getInputStream() or getOutputStream() methods for ServerSocket. Instead you use accept() to
return a Socket object, and then call its getInputStream() or getOutputStream() methods.
For example,
try {
ServerSocket ss = new ServerSocket(2345);
Socket s = ss.accept();
PrintWriter pw = new PrintWriter(s.getOutputStream());
pw.println("Hello There!");
pw.println("Goodbye now.);
s.close();
}
catch (IOException ex) {
System.err.println(ex);
}
Notice in this example, I closed the Socket s, not the ServerSocket ss. ss is still bound to port 2345. You get a
new socket for each connection but it's easy to reuse the server socket. For example, the next code fragment
repeatedly accepts connections:
try {
ServerSocket ss = new ServerSocket(2345);
while (true) {
Socket s = ss.accept();
PrintWriter pw = new PrintWriter(s.getOutputStream());
pw.println("Hello There!");
pw.println("Goodbye now.);
s.close();
}
}
catch (IOException ex) {
System.err.println(ex);
}
Contact us :- 9313565406, 65495934
118
Writing Data to a Client
The following simple program repeatedly answers client requests by sending back the client's address and
port. Then it closes the connection.
import java.net.*;
import java.io.*;
public class HelloServer {
public final static int defaultPort = 2345;
public static void main(String[] args) {
int port = defaultPort;
try {
port = Integer.parseInt(args[0]);
}
catch (Exception ex) {
}
if (port <= 0 || port >= 65536) port = defaultPort;
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
try {
Socket s = ss.accept();
PrintWriter pw = new PrintWriter(s.getOutputStream());
pw.println("Hello " + s.getInetAddress() + " on port "
+ s.getPort());
pw.println("This is " + s.getLocalAddress() + " on port "
+ s.getLocalPort());
pw.flush();
s.close();
}
catch (IOException ex) {
}
}
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
Here's some sample output. note how the port from which the connection comes changes each time.
% telnet utopia.poly.edu 2345
Trying 128.238.3.21...
Connected to utopia.poly.edu.
Escape character is '^]'.
Hello fddisunsite.oit.unc.edu/152.2.254.81 on port 51597
This is utopia.poly.edu/128.238.3.21 on port 2345
Connection closed by foreign host.
% !!
telnet utopia.poly.edu 2345
Trying 128.238.3.21...
Connected to utopia.poly.edu.
Contact us :- 9313565406, 65495934
119
Escape character is '^]'.
Hello fddisunsite.oit.unc.edu/152.2.254.81 on port 51618
This is utopia.poly.edu/128.238.3.21 on port 2345
Connection closed by foreign host.
Interacting with a Client
More commonly, a server needs to both read a client request and write a response. The following program
reads whatever the client sends and then sends it back to the client. In short this is an echo server.
import java.net.*;
import java.io.*;
public class EchoServer {
public final static int defaultPort = 2346;
public static void main(String[] args) {
int port = defaultPort;
try {
port = Integer.parseInt(args[0]);
}
catch (Exception ex) {
}
if (port <= 0 || port >= 65536) port = defaultPort;
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
try {
Socket s = ss.accept();
OutputStream os = s.getOutputStream();
InputStream is = s.getInputStream();
while (true) {
int n = is.read();
if (n == -1) break;
os.write(n);
os.flush();
}
}
catch (IOException ex) {
}
}
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
Here's a sample session:
% telnet utopia.poly.edu 2346
Trying 128.238.3.21...
Connected to utopia.poly.edu.
Escape character is '^]'.
test
Contact us :- 9313565406, 65495934
120
test
credit
credit
this is a test 1 2 3 12 3
this is a test 1 2 3 12 3
^]
telnet> close
Connection closed.
%
Adding Threading to a Server
The last two programs could only handle one client at a time. That wasn't so much of a problem for
HelloServer because it had only a very brief interaction with each client. However the EchoServer might hang
on to a connection indefinitely. In this case, it's better to make your server multi-threaded. There should be a
loop which continually accepts new connections. However, rather than handling the connection directly the
Socket should be passed to a Thread object that handles the connection.
The following example is a threaded echo program.
import java.net.*;
import java.io.*;
public class ThreadedEchoServer extends Thread {
public final static int defaultPort = 2347;
Socket theConnection;
public static void main(String[] args) {
int port = defaultPort;
try {
port = Integer.parseInt(args[0]);
}
catch (Exception ex) {
}
if (port <= 0 || port >= 65536) port = defaultPort;
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
try {
Socket s = ss.accept();
ThreadedEchoServer tes = new ThreadedEchoServer(s);
tes.start();
}
catch (IOException ex) {
}
}
}
catch (IOException ex) {
System.err.println(ex);
}
}
public ThreadedEchoServer(Socket s) {
theConnection = s;
}
Contact us :- 9313565406, 65495934
121
public void run() {
try {
OutputStream os = theConnection.getOutputStream();
InputStream is = theConnection.getInputStream();
while (true) {
int n = is.read();
if (n == -1) break;
os.write(n);
os.flush();
}
}
catch (IOException ex) {
}
}
}
Note that explicit yields are not required because all the different threads will tend to block on calls to read()
and accept().
Adding a Thread Pool to a Server
Multi-threading is a good thing but it's still not a perfect solution. For example, let's take a look at the accept
loop of the ThreadedEchoServer:
while (true) {
try {
Socket s = ss.accept();
ThreadedEchoServer tes = new ThreadedEchoServer(s);
tes.start();
}
catch (IOException ex) {
}
Every time you pass through this loop, a new thread gets created. Every time a connection is finished the
thread is disposed of. Spawning a new thread for each connection takes a non-trivial amount of time,
especially on a heavily loaded server. It would be better not to spawn so many threads.
An alternative approach is to create a pool of threads when the server launches, store incoming connections in
a queue, and have the threads in the pool progressively remove connections from the queue and process
them. This is particularly simple since the operating system does in fact store the incoming connections in a
queue. The main change you need to make to implement this is to call accept() in the run() method rather than
in the main() method. The program below demonstrates.
import java.net.*;
import java.io.*;
public class PoolEchoServer extends Thread {
public final static int defaultPort = 2347;
ServerSocket theServer;
static int numberOfThreads = 10;
public static void main(String[] args) {
int port = defaultPort;
try {
port = Integer.parseInt(args[0]);
}
catch (Exception ex) {
}
Contact us :- 9313565406, 65495934
122
if (port <= 0 || port >= 65536) port = defaultPort;
try {
ServerSocket ss = new ServerSocket(port);
for (int i = 0; i < numberOfThreads; i++) {
PoolEchoServer pes = new PoolEchoServer(ss);
pes.start();
}
}
catch (IOException ex) {
System.err.println(ex);
}
}
public PoolEchoServer(ServerSocket ss) {
theServer = ss;
}
public void run() {
while (true) {
try {
Socket s = theServer.accept();
OutputStream out = s.getOutputStream();
InputStream in = s.getInputStream();
while (true) {
int n = in.read();
if (n == -1) break;
out.write(n);
out.flush();
} // end while
} // end try
catch (IOException ex) {
}
} // end while
} // end run
Contact us :- 9313565406, 65495934
123
Project
PAYROLL SOLUTION
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class login_window extends JFrame implements ActionListener
{
String u=null,p=null,str1=null,str2=null;
JTextField t1 = new JTextField(20);
JPasswordField t2 = new JPasswordField(20);
JButton b1 = new JButton ("LOGIN");
JButton b2 = new JButton ("EXIT");
JLabel l4 = new JLabel(" WRONG PASSWORD!");
JLabel l5 = new JLabel(" WRONG USERNAME!");
JLabel l6 = new JLabel(" BOTH ARE WRONG!");
public login_window()
{
Container content=getContentPane();
setTitle("LOGIN WINDOW");
ImageIcon i1=new ImageIcon ("img\\holes.jpg");
JLabel l=new JLabel (i1);
JLabel l1 = new JLabel(" LOGIN WINDOW");
JLabel l2 = new JLabel(" USERNAME");
JLabel l3 = new JLabel(" PASSWORD");
setLayout(null);
setBounds(400,250,475,220);
l.setIcon(i1);
l.setBounds(0,0,500,500);
l4.setVisible(false);
Contact us :- 9313565406, 65495934
124
l5.setVisible(false);
l6.setVisible(false);
l1.setBounds(180,15,100,15);
l1.setBackground(Color.WHITE);
l1.setOpaque(true);
l4.setBounds(165,50,130,15);
l4.setBackground(Color.WHITE);
l4.setOpaque(true);
l5.setBounds(165,50,130,15);
l5.setBackground(Color.WHITE);
l5.setOpaque(true);
l6.setBounds(165,50,130,15);
l6.setBackground(Color.WHITE);
l6.setOpaque(true);
l2.setBounds(90,70,80,15);
l2.setBackground(Color.WHITE);
l2.setOpaque(true);
l3.setBounds(90,110,80,15);
l3.setBackground(Color.WHITE);
l3.setOpaque(true);
t1.setBounds(258,67,110,25);
t2.setBounds(258,107,110,25);
t2.setEchoChar((char) 0);
b1.setBounds(85,150,90,25);
b2.setBounds(275,150,90,25);
content.add(l1);
content.add(l2);
content.add(l3);
content.add(l4);
content.add(l5);
content.add(l6);
content.add(t1);
content.add(t2);
t2.setEchoChar('?');
content.add(b1);
content.add(b2);
content.add (l);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==b1)
{
l4.setVisible(false);
l5.setVisible(false);
l6.setVisible(false);
u=t1.getText();
p=t2.getText();
str1="root";
str2="password";
if (u.equals(str1)&&(p.equals(str2)))
{
main_window mw =new main_window();
dispose();
}
else
{
if (u.equals(str1))
{
l4.setVisible(true);
}
Contact us :- 9313565406, 65495934
125
else if (p.equals(str2))
{
l5.setVisible(true);
}
else
{
l6.setVisible(true);
}
}
}
if(e.getSource()==b2)
{
dispose();
}
}
public static void main (String args[])
{
JFrame f=new login_window();
f.setVisible(true);
}
}
import java.awt.Color;
import java.awt.Container;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class main_window extends JFrame implements ActionListener {
Contact us :- 9313565406, 65495934
126
JMenuBar mb=new JMenuBar();
JMenu FILE = new JMenu("File");
JMenu QUERY = new JMenu("Query");
JMenu REPORT = new JMenu("Report");
JMenu SALARY = new JMenu("Salary Statement");
JMenu RESET =new JMenu("Reset Database");
JMenu EXIT = new JMenu("Exit");
JMenu sub= new JMenu("EMPLOYEE PROCESSING");
JMenu sub1=new JMenu("EMPLOYEE ATTENDANCE");
JMenuItem item1 =new JMenuItem ("EMPLOYEE REPORT");
JMenuItem item2 =new JMenuItem ("ATTENDANCE REPORT");
JMenuItem item3 =new JMenuItem ("EMPLOYEE DETAILS");
JMenuItem item4 =new JMenuItem ("EMPLOYEE ATTENDANCE");
JMenuItem item5 =new JMenuItem ("YES");
JMenuItem item6 =new JMenuItem ("NO");
JMenuItem item7 =new JMenuItem ("ADD");
JMenuItem item8 =new JMenuItem ("DELETE");
JMenuItem item9 =new JMenuItem ("MODIFY");
JMenuItem item10 =new JMenuItem ("ADD");
JMenuItem item11=new JMenuItem ("DELETE");
JMenuItem item12=new JMenuItem ("MODIFY");
JMenuItem item13=new JMenuItem ("VIEW SALARY SLIP");
JMenuItem item14 =new JMenuItem ("YES");
JMenuItem item15 =new JMenuItem ("NO");
public main_window()
{
Container content1=getContentPane();
setTitle("MAIN WINDOW");
setJMenuBar(mb);
mb.add(FILE);
sub.add(item7);
sub.add(item8);
sub.add(item9);
FILE.add(sub);
FILE.addSeparator();
sub1.add(item10);
sub1.add(item11);
sub1.add(item12);
FILE.add(sub1);
mb.add(QUERY);
QUERY.add(item3);
QUERY.addSeparator();
QUERY.add(item4);
mb.add(REPORT);
REPORT.add(item1);
REPORT.addSeparator();
REPORT.add(item2);
mb.add(SALARY);
SALARY.add(item13);
mb.add(RESET);
RESET.add(item14);
RESET.add(item15);
mb.add(EXIT);
EXIT.add(item5);
EXIT.addSeparator();
EXIT.add(item6);
FILE.setMnemonic(KeyEvent.VK_F);
QUERY.setMnemonic(KeyEvent.VK_Q);
Contact us :- 9313565406, 65495934
127
REPORT.setMnemonic(KeyEvent.VK_R);
SALARY.setMnemonic(KeyEvent.VK_S);
RESET.setMnemonic(KeyEvent.VK_R);
EXIT.setMnemonic(KeyEvent.VK_E);
item1.setMnemonic(KeyEvent.VK_E);
item2.setMnemonic(KeyEvent.VK_A);
item3.setMnemonic(KeyEvent.VK_E);
item4.setMnemonic(KeyEvent.VK_A);
item5.setMnemonic(KeyEvent.VK_Y);
item6.setMnemonic(KeyEvent.VK_N);
ImageIcon im1=new ImageIcon ("img\\money.jpg");
ImageIcon im4=new ImageIcon ("img\\tag.jpg");
JLabel lb1=new JLabel (im1);
JLabel lb2=new JLabel (im4);
lb1.setIcon(im1);
lb2.setIcon(im4);
setLayout(null);
setBounds(-8,0,1298,770);
lb1.setBounds(0,0,1280,780);
lb2.setBounds(470,30,295,70);
content1.setBackground(Color.white);
content1.add (lb2);
content1.add (lb1);
setVisible(true);
item1.addActionListener(this);
item2.addActionListener(this);
item3.addActionListener(this);
item4.addActionListener(this);
item5.addActionListener(this);
item6.addActionListener(this);
item7.addActionListener(this);
item8.addActionListener(this);
item9.addActionListener(this);
item10.addActionListener(this);
item11.addActionListener(this);
item12.addActionListener(this);
item13.addActionListener(this);
item14.addActionListener(this);
item15.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==item7)
{
emp_add ea = new emp_add();
}
if (e.getSource()==item8)
{
emp_delete ed = new emp_delete();
}
if (e.getSource()==item9)
{
emp_modify em = new emp_modify();
}
if (e.getSource()==item10)
{
att_add aa = new att_add();
Contact us :- 9313565406, 65495934
128
}
if (e.getSource()==item11)
{
att_delete ad = new att_delete();
}
if (e.getSource()==item12)
{
att_modify am = new att_modify();
}
if (e.getSource()==item3)
{
emp_q eq = new emp_q();
}
if (e.getSource()==item4)
{
att_q aq = new att_q();
}
if (e.getSource()==item1)
{
List_Employee le = new List_Employee();
}
if (e.getSource()==item2)
{
List_Attendence la = new List_Attendence();
}
if(e.getSource()==item5)
{
System.exit(0);
}
if (e.getSource()==item13)
{
salary s = new salary();
}
if (e.getSource()==item14)
{
data_info di = new data_info();
}
}
}
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
Contact us :- 9313565406, 65495934
129
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.Statement;
import java.sql.*;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.*;
public class emp_add extends JFrame implements ActionListener
{
String ename , sex,address,city,designation ,department,dob,doj,phone;
double gross , basic , net;
int empno,pf , gis , cca , hra , da ,it;
Connection conn1;
JFrame f = new JFrame();
JTextField t1=new JTextField(20);
JTextField t2=new JTextField(20);
JTextField t3=new JTextField(20);
JTextField t4=new JTextField(20);
JTextField t5=new JTextField(20);
JTextField t6=new JTextField(20);
JTextField t7=new JTextField(20);
JTextField t8=new JTextField(20);
JTextField t9=new JTextField(20);
JTextField t10=new JTextField(20);
JTextField t11=new JTextField(20);
JTextField t12=new JTextField(20);
JTextField t13=new JTextField(20);
JTextField t14=new JTextField(20);
JTextField t15=new JTextField(20);
JTextField t16=new JTextField(20);
JTextField t17=new JTextField(20);
JTextField t18=new JTextField(20);
JTextField t19=new JTextField(20);
JTextField t20=new JTextField(20);
ImageIcon im1=new ImageIcon ("img\\add.jpg");
JButton b1 = new JButton (im1);
ImageIcon im2=new ImageIcon ("img\\reset.jpg");
JButton b2 = new JButton (im2);
ImageIcon im3=new ImageIcon ("img\\calculator.jpg");
JButton b3 = new JButton (im3);
ImageIcon im4=new ImageIcon ("img\\back.jpg");
JButton b4 = new JButton (im4);
public emp_add()
{
Container content2=f.getContentPane();
f.setTitle("ADD EMPLOYEE DETAILS");
f.setLayout(null);
content2.setBackground(Color.LIGHT_GRAY);
JLabel l1 = new JLabel("ADD EMPLOYEE DETAILS");
JLabel l2 = new JLabel(": : : : : : : : : EMPLOYEE DETAILS : : : : : : : : : :");
JLabel l3 = new JLabel("EMPLOYEE NO.");
JLabel l4 = new JLabel("EMPLOYEE NAME");
JLabel l5 = new JLabel("ADDRESS");
JLabel l6 = new JLabel("CITY");
JLabel l7 = new JLabel("DATE OF BIRTH");
JLabel l8 = new JLabel("DESIGNATION");
JLabel l9 = new JLabel("SEX");
Contact us :- 9313565406, 65495934
130
JLabel l10 = new JLabel("PHONE NUMBER");
JLabel l11 = new JLabel("DATE OF JOIN");
JLabel l12 = new JLabel("DEPARTMENT");
JLabel l13 = new JLabel("BASIC SALARY");
JLabel l14 = new JLabel("PROVIDENT FUND(PF)");
JLabel l15 = new JLabel("CCA");
JLabel l16 = new JLabel("DEARLY ALLOWANCE(DA)");
JLabel l17 = new JLabel("GIS");
JLabel l18 = new JLabel("HOUSE RENT (HRA)");
JLabel l19 = new JLabel("GROSS SALARY");
JLabel l20 = new JLabel("INCOME TAX(IT)");
JLabel l21 = new JLabel("NET SALARY");
JLabel l22 = new JLabel(": : : : : : : : : SALARY DETAILS : : : : : : : : :");
f.setBounds(0,0,1280,750);
t1.setText("0");
t2.setText("----EMPTY----");
t3.setText("----EMPTY----");
t4.setText("----EMPTY----");
t5.setText("--/--/--");
t6.setText("----EMPTY----");
t7.setText("EMPTY");
t8.setText("0");
t9.setText("--/--/--");
t10.setText("----EMPTY----");
t11.setText("0");
t12.setText("0");
t13.setText("0");
t14.setText("0");
t15.setText("0");
t16.setText("0");
t17.setText("0");
t18.setText("0");
t19.setText("0");
t20.setText(" PERFORM OPERATION");
l1.setBounds(590,5,150,25);
l2.setBounds(30,20,250,25);
l3.setBounds(30,50,150,25);
l4.setBounds(30,100,150,25);
l5.setBounds(30,150,150,25);
l6.setBounds(30,200,150,25);
l7.setBounds(30,250,150,25);
l8.setBounds(30,300,150,25);
l9.setBounds(460,100,150,25);
l10.setBounds(460,200,150,25);
l11.setBounds(460,250,150,25);
l12.setBounds(460,300,150,25);
l13.setBounds(30,375,180,25);
l14.setBounds(30,415,180,25);
Contact us :- 9313565406, 65495934
131
l15.setBounds(30,455,180,25);
l16.setBounds(30,495,150,25);
l17.setBounds(520,425,180,25);
l18.setBounds(520,475,180,25);
l19.setBounds(30,535,50,25);
l20.setBounds(30,575,180,25);
l21.setBounds(30,615,180,25);
l22.setBounds(30,336,300,25);
b1.setBounds(900,100,67,67);
b2.setBounds(900,250,67,67);
b3.setBounds(900,400,67,67);
b4.setBounds(900,550,67,67);
t1.setBounds(200,50,60,25);
t2.setBounds(200,100,200,25);
t3.setBounds(200,150,600,25);//address
t4.setBounds(200,200,200,25);
t5.setBounds(200,250,200,25);
t6.setBounds(200,300,200,25);
t7.setBounds(600,100,45,25);//sex
t8.setBounds(600,200,200,25);//below sex
t9.setBounds(600,250,200,25);
t10.setBounds(600,300,200,25);
t11.setBounds(300,375,200,25);
t12.setBounds(300,415,200,25);
t13.setBounds(300,455,200,25);
t14.setBounds(300,495,200,25);
t15.setBounds(700,425,100,25);
t16.setBounds(700,475,100,25);
t17.setBounds(300,535,200,25);
t18.setBounds(300,575,200,25);
t19.setBounds(300,615,200,25);
t20.setBounds(820,10,150,25);
ImageIcon im9=new ImageIcon ("img\\main2.jpg");
content2.setBackground(Color.white);
JLabel lb9=new JLabel (im9);
lb9.setIcon(im9);
lb9.setBounds(0,0,1280,780);
ImageIcon im10=new ImageIcon ("img\\tag.jpg");
JLabel lb10=new JLabel (im10);
lb10.setIcon(im10);
lb10.setBounds(470,30,295,70);
content2.add(t1);
content2.add(t2);
content2.add(t3);
content2.add(t4);
content2.add(t5);
content2.add(t6);
content2.add(t7);
content2.add(t8);
content2.add(t9);
content2.add(t10);
content2.add(t11);
content2.add(t12);
Contact us :- 9313565406, 65495934
132
content2.add(t13);
content2.add(t14);
content2.add(t15);
content2.add(t16);
content2.add(t17);
content2.add(t18);
content2.add(t19);
content2.add(t20);
content2.add(l1);
content2.add(l2);
content2.add(l3);
content2.add(l4);
content2.add(l5);
content2.add(l6);
content2.add(l7);
content2.add(l8);
content2.add(l9);
content2.add(l10);
content2.add(l11);
content2.add(l12);
content2.add(l13);
content2.add(l14);
content2.add(l15);
content2.add(l16);
content2.add(l17);
content2.add(l18);
content2.add(l19);
content2.add(l20);
content2.add(l21);
content2.add(l22);
content2.add(b1);
content2.add(b2);
content2.add(b3);
content2.add(b4);
content2.add (lb10);
content2.add (lb9);
f.setVisible(true);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==b1)
{
empno=Integer.parseInt(t1.getText());
ename=t2.getText();
address=t3.getText();
city=t4.getText();
dob=t5.getText();
designation=t6.getText();
sex=t7.getText();
phone=t8.getText();
doj=t9.getText();
department = t10.getText();
basic=Double.parseDouble(t11.getText());
pf=Integer.parseInt(t12.getText());
cca=Integer.parseInt(t13.getText());
da=Integer.parseInt(t14.getText());
gis=Integer.parseInt(t15.getText());
hra=Integer.parseInt(t16.getText());
gross=Double.parseDouble(t17.getText());
Contact us :- 9313565406, 65495934
133
it=Integer.parseInt(t18.getText());
net=Double.parseDouble(t19.getText());
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
conn1=DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll","root","1234");
java.sql.Statement st1= conn1.createStatement();
st1.executeUpdate("insert into emp_details values('" + empno + "','" + ename + "' ,'" + sex+"','" +
address + "','" + phone + "','" + city + "','" + dob + "','" + doj + "','" + designation + "','" + department + "','" + basic +
"','" + pf + "','" + gis + "','" + cca + "','" + hra + "','" + da + "','" + gross + "','" + it + "','" + net + "')");
t20.setText(" RECORD INSERTED!");
conn1.close();
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
if (e.getSource()==b2)
{
t1.setText("0");
t2.setText("----EMPTY----");
t3.setText("----EMPTY----");
t4.setText("----EMPTY----");
t5.setText("--/--/--");
t6.setText("----EMPTY----");
t7.setText("EMPTY");
t8.setText("0");
t9.setText("--/--/--");
t10.setText("----EMPTY----");
t11.setText("0");
t12.setText("0");
t13.setText("0");
t14.setText("0");
t15.setText("0");
t16.setText("0");
t17.setText("0");
t18.setText("0");
t19.setText("0");
t20.setText(" PERFORM OPERATION");
}
if (e.getSource()==b4)
{
f.dispose();
}
if(e.getSource()==b3)
{
t20.setText(" SALARY CALCULATED!");
basic = Integer.parseInt(t11.getText());
pf=(int) (0.05*basic);
Contact us :- 9313565406, 65495934
134
gis=(int) (0.06*basic);
cca=1500;
t12.setText(String.valueOf(pf));
t13.setText(String.valueOf(cca));
t15.setText(String.valueOf(gis));
if(basic<15000)
{
hra=3500;
}
else if(basic<25000)
{
hra=3750;
}
else
hra=4250;
t16.setText(String.valueOf(hra));
if(basic<15000)
{
da=1500;
}
else if(basic<30000)
{
da=2000;
}
else
da=2200;
t14.setText(String.valueOf(da));
gross=basic+cca+hra+da;
t17.setText(String.valueOf(gross));
if (gross>30000)
{
it=(int) (0.06*gross);
}
else if(gross>25000)
{
it=(int) (0.04*gross);
}
else if (gross>20000)
{
it=(int) (0.02*gross);
}
else
it=(int) (0.01*gross);
t18.setText(String.valueOf(it));
net=gross-pf-gis-it;
t19.setText(String.valueOf(net));
}
}
}
Contact us :- 9313565406, 65495934
135
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.Statement;
import java.sql.*;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.*;
public class emp_delete extends JFrame implements ActionListener {
String ename , sex,address,city,designation ,department,dob,doj,phone;
double gross , basic , net;
int empno,pf , gis , cca , hra , da ,it;
Connection conn1;
JFrame f = new JFrame();
JTextField t1=new JTextField(20);
JTextField t2=new JTextField(20);
JTextField t3=new JTextField(20);
JTextField t4=new JTextField(20);
JTextField t5=new JTextField(20);
JTextField t6=new JTextField(20);
JTextField t7=new JTextField(20);
JTextField t8=new JTextField(20);
JTextField t9=new JTextField(20);
JTextField t10=new JTextField(20);
JTextField t11=new JTextField(20);
JTextField t12=new JTextField(20);
JTextField t13=new JTextField(20);
JTextField t14=new JTextField(20);
JTextField t15=new JTextField(20);
JTextField t16=new JTextField(20);
JTextField t17=new JTextField(20);
JTextField t18=new JTextField(20);
JTextField t19=new JTextField(20);
JTextField t20=new JTextField(20);
ImageIcon im1=new ImageIcon ("img\\delete.jpg");
JButton b1 = new JButton (im1);
Contact us :- 9313565406, 65495934
136
ImageIcon im2=new ImageIcon ("img\\reset.jpg");
JButton b2 = new JButton (im2);
ImageIcon im3=new ImageIcon ("img\\search.jpg");
JButton b3 = new JButton (im3);
ImageIcon im4=new ImageIcon ("img\\back.jpg");
JButton b4 = new JButton (im4);
public emp_delete()
{
Container content2=f.getContentPane();
f.setTitle("DELETE EMPLOYEE DETAILS");
f.setLayout(null);
content2.setBackground(Color.LIGHT_GRAY);
JLabel l1 = new JLabel("DELETE EMPLOYEE DETAILS");
JLabel l2 = new JLabel(": : : : : : : : : EMPLOYEE DETAILS : : : : : : : : : :");
JLabel l3 = new JLabel("EMPLOYEE NO.");
JLabel l4 = new JLabel("EMPLOYEE NAME");
JLabel l5 = new JLabel("ADDRESS");
JLabel l6 = new JLabel("CITY");
JLabel l7 = new JLabel("DATE OF BIRTH");
JLabel l8 = new JLabel("DESIGNATION");
JLabel l9 = new JLabel("SEX");
JLabel l10 = new JLabel("PHONE NUMBER");
JLabel l11 = new JLabel("DATE OF JOIN");
JLabel l12 = new JLabel("DEPARTMENT");
JLabel l13 = new JLabel("BASIC SALARY");
JLabel l14 = new JLabel("PROVIDENT FUND(PF)");
JLabel l15 = new JLabel("CCA");
JLabel l16 = new JLabel("DEARLY ALLOWANCE(DA)");
JLabel l17 = new JLabel("GIS");
JLabel l18 = new JLabel("HOUSE RENT (HRA)");
JLabel l19 = new JLabel("GROSS SALARY");
JLabel l20 = new JLabel("INCOME TAX(IT)");
JLabel l21 = new JLabel("NET SALARY");
JLabel l22 = new JLabel(": : : : : : : : : SALARY DETAILS : : : : : : : : :");
f.setBounds(0,0,1280,750);
t1.setText("0");
t2.setText("----EMPTY----");
t3.setText("----EMPTY----");
t4.setText("----EMPTY----");
t5.setText("--/--/--");
t6.setText("----EMPTY----");
t7.setText("EMPTY");
t8.setText("0");
t9.setText("--/--/--");
t10.setText("----EMPTY----");
t11.setText("0");
t12.setText("0");
t13.setText("0");
t14.setText("0");
t15.setText("0");
t16.setText("0");
t17.setText("0");
t18.setText("0");
t19.setText("0");
t20.setText(" PERFORM OPERATION");
l1.setBounds(590,5,300,25);
l2.setBounds(30,20,250,25);
l3.setBounds(30,50,150,25);
l4.setBounds(30,100,150,25);
l5.setBounds(30,150,150,25);
l6.setBounds(30,200,150,25);
l7.setBounds(30,250,150,25);
Contact us :- 9313565406, 65495934
137
l8.setBounds(30,300,150,25);
l9.setBounds(460,100,150,25);
l10.setBounds(460,200,150,25);
l11.setBounds(460,250,150,25);
l12.setBounds(460,300,150,25);
l13.setBounds(30,375,180,25);
l14.setBounds(30,415,180,25);
l15.setBounds(30,455,180,25);
l16.setBounds(30,495,150,25);
l17.setBounds(520,425,180,25);
l18.setBounds(520,475,180,25);
l19.setBounds(30,535,180,25);
l20.setBounds(30,575,180,25);
l21.setBounds(30,615,180,25);
l22.setBounds(30,336,300,25);
b1.setBounds(900,100,67,67);
b2.setBounds(900,250,67,67);
b3.setBounds(900,400,67,67);
b4.setBounds(900,550,67,67);
t1.setBounds(200,50,60,25);
t2.setBounds(200,100,200,25);
t3.setBounds(200,150,600,25);//address
t4.setBounds(200,200,200,25);
t5.setBounds(200,250,200,25);
t6.setBounds(200,300,200,25);
t7.setBounds(600,100,45,25);//sex
t8.setBounds(600,200,200,25);//below sex
t9.setBounds(600,250,200,25);
t10.setBounds(600,300,200,25);
t11.setBounds(300,375,200,25);
t12.setBounds(300,415,200,25);
t13.setBounds(300,455,200,25);
t14.setBounds(300,495,200,25);
t15.setBounds(700,425,100,25);
t16.setBounds(700,475,100,25);
t17.setBounds(300,535,200,25);
t18.setBounds(300,575,200,25);
t19.setBounds(300,615,200,25);
t20.setBounds(820,10,150,25);
t2.enable(false);
t3.enable(false);
t4.enable(false);
t5.enable(false);
t6.enable(false);
t7.enable(false);
t8.enable(false);
t9.enable(false);
t10.enable(false);
t11.enable(false);
t12.enable(false);
t13.enable(false);
t14.enable(false);
t15.enable(false);
t16.enable(false);
t17.enable(false);
t18.enable(false);
t19.enable(false);
t20.enable(false);
ImageIcon im9=new ImageIcon ("img\\main2.jpg");
JLabel lb9=new JLabel (im9);
lb9.setIcon(im9);
lb9.setBounds(0,0,1280,780);
ImageIcon im10=new ImageIcon ("img\\tag.jpg");
JLabel lb10=new JLabel (im10);
Contact us :- 9313565406, 65495934
138
lb10.setIcon(im10);
lb10.setBounds(470,30,295,70);
content2.add(t1);
content2.add(t2);
content2.add(t3);
content2.add(t4);
content2.add(t5);
content2.add(t6);
content2.add(t7);
content2.add(t8);
content2.add(t9);
content2.add(t10);
content2.add(t11);
content2.add(t12);
content2.add(t13);
content2.add(t14);
content2.add(t15);
content2.add(t16);
content2.add(t17);
content2.add(t18);
content2.add(t19);
content2.add(t20);
content2.add(l1);
content2.add(l2);
content2.add(l3);
content2.add(l4);
content2.add(l5);
content2.add(l6);
content2.add(l7);
content2.add(l8);
content2.add(l9);
content2.add(l10);
content2.add(l11);
content2.add(l12);
content2.add(l13);
content2.add(l14);
content2.add(l15);
content2.add(l16);
content2.add(l17);
content2.add(l18);
content2.add(l19);
content2.add(l20);
content2.add(l21);
content2.add(l22);
content2.add(b1);
content2.add(b2);
content2.add(b3);
content2.add(b4);
content2.add(lb10);
content2.add(lb9);
f.setVisible(true);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==b2)
{
t1.setText("0");
t2.setText("----EMPTY----");
Contact us :- 9313565406, 65495934
139
t3.setText("----EMPTY----");
t4.setText("----EMPTY----");
t5.setText("--/--/--");
t6.setText("----EMPTY----");
t7.setText("EMPTY");
t8.setText("0");
t9.setText("--/--/--");
t10.setText("----EMPTY----");
t11.setText("0");
t12.setText("0");
t13.setText("0");
t14.setText("0");
t15.setText("0");
t16.setText("0");
t17.setText("0");
t18.setText("0");
t19.setText("0");
t20.setText(" PERFORM OPERATION");
t2.enable(false);
t3.enable(false);
t4.enable(false);
t5.enable(false);
t6.enable(false);
t7.enable(false);
t8.enable(false);
t9.enable(false);
t10.enable(false);
t11.enable(false);
t12.enable(false);
t13.enable(false);
t14.enable(false);
t15.enable(false);
t16.enable(false);
t17.enable(false);
t18.enable(false);
t19.enable(false);
t20.enable(false);
}
if (e.getSource()==b4)
{
f.dispose();
}
if (e.getSource()==b3)
{
t2.enable(true);
t3.enable(true);
t4.enable(true);
t5.enable(true);
t6.enable(true);
t7.enable(true);
t8.enable(true);
t9.enable(true);
t10.enable(true);
t11.enable(true);
t12.enable(true);
t13.enable(true);
t14.enable(true);
t15.enable(true);
t16.enable(true);
t17.enable(true);
t18.enable(true);
t19.enable(true);
Contact us :- 9313565406, 65495934
140
t20.enable(true);
empno=Integer.parseInt(t1.getText());
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll","root","1234");
java.sql.Statement st=conn.createStatement();
ResultSet sear= st.executeQuery("select * from emp_details where empno= '"+
empno +" ' " );
if(sear.next())
{
empno=sear.getInt("empno");
ename=sear.getString("ename");
sex=sear.getString("sex");
address=sear.getString("address");
phone=sear.getString("phone");
city=sear.getString("city");
dob=sear.getString("dob");
doj=sear.getString("doj");
designation=sear.getString("designation");
department=sear.getString("department");
basic=sear.getDouble("basic");
pf=sear.getInt("pf");
gis=sear.getInt("gis");
cca=sear.getInt("cca");
hra=sear.getInt("hra");
da=sear.getInt("da");
gross=sear.getDouble("gross");
it=sear.getInt("it");
net=sear.getDouble("net");
t1.setText(String.valueOf(empno));
t2.setText(ename);
t3.setText(address);
t4.setText(city);
t5.setText(dob);
t6.setText(designation);
t7.setText(sex);
t8.setText(String.valueOf(phone));
t9.setText(doj);
t10.setText(department);
t11.setText(String.valueOf(basic));
t12.setText(String.valueOf(pf));
t13.setText(String.valueOf(cca));
t14.setText(String.valueOf(da));
t15.setText(String.valueOf(gis));
t16.setText(String.valueOf(hra));
t17.setText(String.valueOf(gross));
t18.setText(String.valueOf(it));
t19.setText(String.valueOf(net));
t20.setText("RECORD SEARCHED!");
}
else
{
t20.setText("NO RECORD!");
t1.setText("0");
t2.setText("----EMPTY----");
Contact us :- 9313565406, 65495934
141
t3.setText("----EMPTY----");
t4.setText("----EMPTY----");
t5.setText("--/--/--");
t6.setText("----EMPTY----");
t7.setText("EMPTY");
t8.setText("0");
t9.setText("--/--/--");
t10.setText("----EMPTY----");
t11.setText("0");
t12.setText("0");
t13.setText("0");
t14.setText("0");
t15.setText("0");
t16.setText("0");
t17.setText("0");
t18.setText("0");
t19.setText("0");
}
conn.close();
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
if(e.getSource()==b1)
{
empno=Integer.parseInt(t1.getText());
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll","root","1234");
java.sql.Statement st=conn.createStatement();
int del= st.executeUpdate("delete from emp_details where empno= '"+ empno +" ' " );
if(del==1)
t20.setText(" RECORD DELETED!");
else
{
t20.setText(" NO RECORD!");
t1.setText("0");
t2.setText("----EMPTY----");
t3.setText("----EMPTY----");
t4.setText("----EMPTY----");
t5.setText("--/--/--");
t6.setText("----EMPTY----");
t7.setText("EMPTY");
t8.setText("0");
t9.setText("--/--/--");
Contact us :- 9313565406, 65495934
142
t10.setText("----EMPTY----");
t11.setText("0");
t12.setText("0");
t13.setText("0");
t14.setText("0");
t15.setText("0");
t16.setText("0");
t17.setText("0");
t18.setText("0");
t19.setText("0");
}
conn.close();
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
}
}
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.Statement;
import java.sql.*;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.*;
public class emp_modify extends JFrame implements ActionListener {
Contact us :- 9313565406, 65495934
143
String ename , sex,address,city,designation ,department,dob,doj,phone;
double gross , basic , net;
int empno,pf , gis , cca , hra , da ,it;
Connection conn1;
JFrame f = new JFrame();
JTextField t1=new JTextField(20);
JTextField t2=new JTextField(20);
JTextField t3=new JTextField(20);
JTextField t4=new JTextField(20);
JTextField t5=new JTextField(20);
JTextField t6=new JTextField(20);
JTextField t7=new JTextField(20);
JTextField t8=new JTextField(20);
JTextField t9=new JTextField(20);
JTextField t10=new JTextField(20);
JTextField t11=new JTextField(20);
JTextField t12=new JTextField(20);
JTextField t13=new JTextField(20);
JTextField t14=new JTextField(20);
JTextField t15=new JTextField(20);
JTextField t16=new JTextField(20);
JTextField t17=new JTextField(20);
JTextField t18=new JTextField(20);
JTextField t19=new JTextField(20);
JTextField t20=new JTextField(20);
ImageIcon im1=new ImageIcon ("img\\save.jpg");
JButton b1 = new JButton (im1);
ImageIcon im2=new ImageIcon ("img\\reset.jpg");
JButton b2 = new JButton (im2);
ImageIcon im3=new ImageIcon ("img\\search.jpg");
JButton b3 = new JButton (im3);
ImageIcon im4=new ImageIcon ("img\\back.jpg");
JButton b4 = new JButton (im4);
ImageIcon im5=new ImageIcon ("img\\calculator.jpg");
JButton b5 = new JButton (im5);
public emp_modify()
{
Container content2=f.getContentPane();
f.setTitle("DELETE EMPLOYEE DETAILS");
f.setLayout(null);
content2.setBackground(Color.LIGHT_GRAY);
JLabel l1 = new JLabel("MODIFY EMPLOYEE DETAILS");
JLabel l2 = new JLabel(": : : : : : : : : EMPLOYEE DETAILS : : : : : : : : : :");
JLabel l3 = new JLabel("EMPLOYEE NO.");
JLabel l4 = new JLabel("EMPLOYEE NAME");
JLabel l5 = new JLabel("ADDRESS");
JLabel l6 = new JLabel("CITY");
JLabel l7 = new JLabel("DATE OF BIRTH");
JLabel l8 = new JLabel("DESIGNATION");
JLabel l9 = new JLabel("SEX");
JLabel l10 = new JLabel("PHONE NUMBER");
JLabel l11 = new JLabel("DATE OF JOIN");
JLabel l12 = new JLabel("DEPARTMENT");
JLabel l13 = new JLabel("BASIC SALARY");
JLabel l14 = new JLabel("PROVIDENT FUND(PF)");
JLabel l15 = new JLabel("CCA");
JLabel l16 = new JLabel("DEARLY ALLOWANCE(DA)");
JLabel l17 = new JLabel("GIS");
JLabel l18 = new JLabel("HOUSE RENT (HRA)");
JLabel l19 = new JLabel("GROSS SALARY");
JLabel l20 = new JLabel("INCOME TAX(IT)");
JLabel l21 = new JLabel("NET SALARY");
Contact us :- 9313565406, 65495934
144
JLabel l22 = new JLabel(": : : : : : : : : SALARY DETAILS : : : : : : : : :");
f.setBounds(0,0,1280,750);
t1.setText("0");
t2.setText("----EMPTY----");
t3.setText("----EMPTY----");
t4.setText("----EMPTY----");
t5.setText("--/--/--");
t6.setText("----EMPTY----");
t7.setText("EMPTY");
t8.setText("0");
t9.setText("--/--/--");
t10.setText("----EMPTY----");
t11.setText("0");
t12.setText("0");
t13.setText("0");
t14.setText("0");
t15.setText("0");
t16.setText("0");
t17.setText("0");
t18.setText("0");
t19.setText("0");
t20.setText(" PERFORM OPERATION");
l1.setBounds(590,5,300,25);
l2.setBounds(30,20,250,25);
l3.setBounds(30,50,150,25);
l4.setBounds(30,100,150,25);
l5.setBounds(30,150,150,25);
l6.setBounds(30,200,150,25);
l7.setBounds(30,250,150,25);
l8.setBounds(30,300,150,25);
l9.setBounds(460,100,150,25);
l10.setBounds(460,200,150,25);
l11.setBounds(460,250,150,25);
l12.setBounds(460,300,150,25);
l13.setBounds(30,375,180,25);
l14.setBounds(30,415,180,25);
l15.setBounds(30,455,180,25);
l16.setBounds(30,495,150,25);
l17.setBounds(520,425,180,25);
l18.setBounds(520,475,180,25);
l19.setBounds(30,535,180,25);
l20.setBounds(30,575,180,25);
l21.setBounds(30,615,180,25);
l22.setBounds(30,336,300,25);
b1.setBounds(900,100,67,67);
b2.setBounds(900,200,67,67);
b3.setBounds(900,300,67,67);
b4.setBounds(900,400,67,67);
b5.setBounds(900,500,67,67);
t1.setBounds(200,50,60,25);
t2.setBounds(200,100,200,25);
t3.setBounds(200,150,600,25);//address
t4.setBounds(200,200,200,25);
t5.setBounds(200,250,200,25);
t6.setBounds(200,300,200,25);
t7.setBounds(600,100,45,25);//sex
t8.setBounds(600,200,200,25);//below sex
t9.setBounds(600,250,200,25);
t10.setBounds(600,300,200,25);
t11.setBounds(300,375,200,25);
t12.setBounds(300,415,200,25);
t13.setBounds(300,455,200,25);
t14.setBounds(300,495,200,25);
Contact us :- 9313565406, 65495934
145
t15.setBounds(700,425,100,25);
t16.setBounds(700,475,100,25);
t17.setBounds(300,535,200,25);
t18.setBounds(300,575,200,25);
t19.setBounds(300,615,200,25);
t20.setBounds(820,10,150,25);
t2.enable(false);
t3.enable(false);
t4.enable(false);
t5.enable(false);
t6.enable(false);
t7.enable(false);
t8.enable(false);
t9.enable(false);
t10.enable(false);
t11.enable(false);
t12.enable(false);
t13.enable(false);
t14.enable(false);
t15.enable(false);
t16.enable(false);
t17.enable(false);
t18.enable(false);
t19.enable(false);
t20.enable(false);
ImageIcon im9=new ImageIcon ("img\\main2.jpg");
JLabel lb9=new JLabel (im9);
lb9.setIcon(im9);
lb9.setBounds(0,0,1280,780);
ImageIcon im10=new ImageIcon ("img\\tag.jpg");
JLabel lb10=new JLabel (im10);
lb10.setIcon(im10);
lb10.setBounds(470,30,295,70);
content2.add(t1);
content2.add(t2);
content2.add(t3);
content2.add(t4);
content2.add(t5);
content2.add(t6);
content2.add(t7);
content2.add(t8);
content2.add(t9);
content2.add(t10);
content2.add(t11);
content2.add(t12);
content2.add(t13);
content2.add(t14);
content2.add(t15);
content2.add(t16);
content2.add(t17);
content2.add(t18);
content2.add(t19);
content2.add(t20);
content2.add(l1);
content2.add(l2);
content2.add(l3);
content2.add(l4);
content2.add(l5);
content2.add(l6);
content2.add(l7);
content2.add(l8);
content2.add(l9);
Contact us :- 9313565406, 65495934
146
content2.add(l10);
content2.add(l11);
content2.add(l12);
content2.add(l13);
content2.add(l14);
content2.add(l15);
content2.add(l16);
content2.add(l17);
content2.add(l18);
content2.add(l19);
content2.add(l20);
content2.add(l21);
content2.add(l22);
content2.add(b1);
content2.add(b2);
content2.add(b3);
content2.add(b4);
content2.add(b5);
content2.add(lb10);
content2.add(lb9);
f.setVisible(true);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==b2)
{
t1.setText("0");
t2.setText("----EMPTY----");
t3.setText("----EMPTY----");
t4.setText("----EMPTY----");
t5.setText("--/--/--");
t6.setText("----EMPTY----");
t7.setText("EMPTY");
t8.setText("0");
t9.setText("--/--/--");
t10.setText("----EMPTY----");
t11.setText("0");
t12.setText("0");
t13.setText("0");
t14.setText("0");
t15.setText("0");
t16.setText("0");
t17.setText("0");
t18.setText("0");
t19.setText("0");
t20.setText("PERFORM OPERATION");
t2.enable(false);
t3.enable(false);
t4.enable(false);
t5.enable(false);
t6.enable(false);
t7.enable(false);
t8.enable(false);
t9.enable(false);
t10.enable(false);
t11.enable(false);
t12.enable(false);
t13.enable(false);
t14.enable(false);
Contact us :- 9313565406, 65495934
147
t15.enable(false);
t16.enable(false);
t17.enable(false);
t18.enable(false);
t19.enable(false);
t20.enable(false);
}
if (e.getSource()==b4)
{
f.dispose();
}
if (e.getSource()==b1)
{
empno=Integer.parseInt(t1.getText());
ename=t2.getText();
address=t3.getText();
city=t4.getText();
dob=t5.getText();
designation=t6.getText();
sex=t7.getText();
phone=t8.getText();
doj=t9.getText();
department = t10.getText();
basic=Double.parseDouble(t11.getText());
pf=Integer.parseInt(t12.getText());
cca=Integer.parseInt(t13.getText());
da=Integer.parseInt(t14.getText());
gis=Integer.parseInt(t15.getText());
hra=Integer.parseInt(t16.getText());
gross=Double.parseDouble(t17.getText());
it=Integer.parseInt(t18.getText());
net=Double.parseDouble(t19.getText());
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
conn1=DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll","root","1234");
java.sql.Statement st=conn1.createStatement();
int del= st.executeUpdate("delete from emp_details where empno= '"+
empno +" ' " );
java.sql.Statement st1=conn1.createStatement();
st1.executeUpdate("insert into emp_details values('" + empno + "','" +
ename + "' ,'" + sex+"','" + address + "','" + phone + "','" + city + "','" + dob + "','" + doj + "','" + designation + "','" +
department + "','" + basic + "','" + pf + "','" + gis + "','" + cca + "','" + hra + "','" + da + "','" + gross + "','" + it + "','" +
net + "')");
conn1.close();
t20.setText("SAVED SUCCESSFULLY!");
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
Contact us :- 9313565406, 65495934
148
if(e.getSource()==b5)
{
t20.setText(" SALARY CALCULATED!");
basic = Integer.parseInt(t11.getText());
pf=(int) (0.05*basic);
gis=(int) (0.06*basic);
cca=1500;
t12.setText(String.valueOf(pf));
t13.setText(String.valueOf(cca));
t15.setText(String.valueOf(gis));
if(basic<15000)
{
hra=3500;
}
else if(basic<25000)
{
hra=3750;
}
else
hra=4250;
t16.setText(String.valueOf(hra));
if(basic<15000)
{
da=1500;
}
else if(basic<30000)
{
da=2000;
}
else
da=2200;
t14.setText(String.valueOf(da));
gross=basic+cca+hra+da;
t17.setText(String.valueOf(gross));
if (gross>30000)
{
it=(int) (0.06*gross);
}
else if(gross>25000)
{
it=(int) (0.04*gross);
}
else if (gross>20000)
{
it=(int) (0.02*gross);
}
else
it=(int) (0.01*gross);
t18.setText(String.valueOf(it));
net=gross-pf-gis-it;
t19.setText(String.valueOf(net));
}
if (e.getSource()==b3)
Contact us :- 9313565406, 65495934
149
{
t2.enable(true);
t3.enable(true);
t4.enable(true);
t5.enable(true);
t6.enable(true);
t7.enable(true);
t8.enable(true);
t9.enable(true);
t10.enable(true);
t11.enable(true);
t12.enable(true);
t13.enable(true);
t14.enable(true);
t15.enable(true);
t16.enable(true);
t17.enable(true);
t18.enable(true);
t19.enable(true);
t20.enable(true);
empno=Integer.parseInt(t1.getText());
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
conn1=DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll","root","1234");
java.sql.Statement st=conn1.createStatement();
ResultSet sear= st.executeQuery("select * from emp_details where
empno= '"+ empno +" ' " );
if(sear.next())
{
empno=sear.getInt("empno");
ename=sear.getString("ename");
sex=sear.getString("sex");
address=sear.getString("address");
phone=sear.getString("phone");
city=sear.getString("city");
dob=sear.getString("dob");
doj=sear.getString("doj");
designation=sear.getString("designation");
department=sear.getString("department");
basic=sear.getDouble("basic");
pf=sear.getInt("pf");
gis=sear.getInt("gis");
cca=sear.getInt("cca");
hra=sear.getInt("hra");
da=sear.getInt("da");
gross=sear.getDouble("gross");
it=sear.getInt("it");
net=sear.getDouble("net");
t1.setText(String.valueOf(empno));
t2.setText(ename);
t3.setText(address);
t4.setText(city);
t5.setText(dob);
t6.setText(designation);
t7.setText(sex);
Contact us :- 9313565406, 65495934
150
t8.setText(String.valueOf(phone));
t9.setText(doj);
t10.setText(department);
t11.setText(String.valueOf(basic));
t12.setText(String.valueOf(pf));
t13.setText(String.valueOf(cca));
t14.setText(String.valueOf(da));
t15.setText(String.valueOf(gis));
t16.setText(String.valueOf(hra));
t17.setText(String.valueOf(gross));
t18.setText(String.valueOf(it));
t19.setText(String.valueOf(net));
t20.enable(true);
t20.setText("RECORD SEARCHED!");
}
else
{
t20.setText("NO RECORD!");
t1.setText("0");
t2.setText("----EMPTY----");
t3.setText("----EMPTY----");
t4.setText("----EMPTY----");
t5.setText("--/--/--");
t6.setText("----EMPTY----");
t7.setText("EMPTY");
t8.setText("0");
t9.setText("--/--/--");
t10.setText("----EMPTY----");
t11.setText("0");
t12.setText("0");
t13.setText("0");
t14.setText("0");
t15.setText("0");
t16.setText("0");
t17.setText("0");
t18.setText("0");
t19.setText("0");
}
conn1.close();
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
}
}
Contact us :- 9313565406, 65495934
151
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class att_add extends JFrame implements ActionListener {
int empno ,for_month,year,cls,pls,mls,lwp;
Connection conn1;
JFrame f = new JFrame();
JTextField t1=new JTextField(20);
JTextField t2=new JTextField(20);
JTextField t3=new JTextField(20);
JTextField t4=new JTextField(20);
JTextField t5=new JTextField(20);
JTextField t6=new JTextField(20);
JTextField t7=new JTextField(20);
JTextField t8=new JTextField(20);
ImageIcon im1=new ImageIcon ("img\\add.jpg");
JButton b1 = new JButton (im1);
ImageIcon im2=new ImageIcon ("img\\reset.jpg");
JButton b2 = new JButton (im2);
ImageIcon im3=new ImageIcon ("img\\back.jpg");
JButton b3 = new JButton (im3);
public att_add()
{
Container content2=f.getContentPane();
f.setTitle("ADD ATTENDENCE DETAILS");
f.setLayout(null);
content2.setBackground(Color.LIGHT_GRAY);
JLabel l1 = new JLabel("ADD ATTENDENCE DETAILS");
JLabel l2 = new JLabel("EMPLOYEE NUMBER");
JLabel l3 = new JLabel("FOR MONTH(MONTH NUMBER)");
JLabel l4 = new JLabel("YEAR");
JLabel l5 = new JLabel("CASUAL LEAVES(CLS)");
Contact us :- 9313565406, 65495934
152
JLabel l6 = new JLabel("PAY LEAVES(PLS)");
JLabel l7 = new JLabel("MEDICAL LEAVES(MLS)");
JLabel l8 = new JLabel("LEAVE WITHOUT PAY(LWP)");
f.setBounds(0,0,1280,750);
t1.setText("0");
t2.setText("0");
t3.setText("0");
t4.setText("0");
t5.setText("0");
t6.setText("0");
t7.setText("0");
t8.setText("PERFORM OPERATION");
l1.setBounds(590,5,300,25);
l2.setBounds(30,50,250,25);
l3.setBounds(30,130,250,25);
l4.setBounds(30,210,250,25);
l5.setBounds(30,290,250,25);
l6.setBounds(30,370,250,25);
l7.setBounds(30,450,250,25);
l8.setBounds(30,530,250,25);
t1.setBounds(320,50,200,25);
t2.setBounds(320,130,200,25);
t3.setBounds(320,210,200,25);
t4.setBounds(320,290,200,25);
t5.setBounds(320,370,200,25);
t6.setBounds(320,450,200,25);
t7.setBounds(320,530,200,25);
t8.setBounds(820,10,150,25);
b1.setBounds(900,100,67,67);
b2.setBounds(900,250,67,67);
b3.setBounds(900,400,67,67);
ImageIcon im9=new ImageIcon ("img\\main2.jpg");
JLabel lb9=new JLabel (im9);
lb9.setIcon(im9);
lb9.setBounds(0,0,1280,780);
ImageIcon im10=new ImageIcon ("img\\tag.jpg");
JLabel lb10=new JLabel (im10);
lb10.setIcon(im10);
lb10.setBounds(530,30,295,70);
content2.add(t1);
content2.add(t2);
content2.add(t3);
content2.add(t4);
content2.add(t5);
content2.add(t6);
content2.add(t7);
content2.add(t8);
content2.add(l1);
content2.add(l2);
content2.add(l3);
content2.add(l4);
content2.add(l5);
content2.add(l6);
content2.add(l7);
content2.add(l8);
content2.add(b1);
content2.add(b2);
content2.add(b3);
content2.add(lb10);
content2.add(lb9);
f.setVisible(true);
Contact us :- 9313565406, 65495934
153
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==b3)
{
f.dispose();
}
if(e.getSource()==b2)
{
t1.setText("0");
t2.setText("0");
t3.setText("0");
t4.setText("0");
t5.setText("0");
t6.setText("0");
t7.setText("0");
t8.setText("PERFORM OPERATION");
}
if(e.getSource()==b1)
{
empno=Integer.parseInt(t1.getText());
for_month=Integer.parseInt(t2.getText());
year=Integer.parseInt(t3.getText());
cls=Integer.parseInt(t4.getText());
pls=Integer.parseInt(t5.getText());
mls=Integer.parseInt(t6.getText());
lwp=Integer.parseInt(t7.getText());
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
conn1=DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll","root","1234");
java.sql.Statement st1= conn1.createStatement();
st1.executeUpdate("insert into att_details values('" + empno + "','" + for_month + "' ,'" +
year+"','" + cls + "','" + pls + "','" + mls + "','" + lwp + "')");
t8.setText(" RECORD INSERTED!");
conn1.close();
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
}
Contact us :- 9313565406, 65495934
154
}
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class att_delete extends JFrame implements ActionListener {
int empno ,for_month,year,cls,pls,mls,lwp;
Connection conn1;
JFrame f = new JFrame();
JTextField t1=new JTextField(20);
JTextField t2=new JTextField(20);
JTextField t3=new JTextField(20);
JTextField t4=new JTextField(20);
JTextField t5=new JTextField(20);
JTextField t6=new JTextField(20);
JTextField t7=new JTextField(20);
JTextField t8=new JTextField(20);
ImageIcon im1=new ImageIcon ("img\\delete.jpg");
JButton b1 = new JButton (im1);
ImageIcon im2=new ImageIcon ("img\\reset.jpg");
JButton b2 = new JButton (im2);
ImageIcon im3=new ImageIcon ("img\\search.jpg");
JButton b3 = new JButton (im3);
ImageIcon im4=new ImageIcon ("img\\back.jpg");
JButton b4 = new JButton (im4);
public att_delete()
{
Container content2=f.getContentPane();
f.setTitle("DELETE ATTENDENCE DETAILS");
Contact us :- 9313565406, 65495934
155
f.setLayout(null);
content2.setBackground(Color.LIGHT_GRAY);
JLabel l1 = new JLabel("DELETE ATTENDENCE DETAILS");
JLabel l2 = new JLabel("EMPLOYEE NUMBER");
JLabel l3 = new JLabel("FOR MONTH(MONTH NUMBER)");
JLabel l4 = new JLabel("YEAR");
JLabel l5 = new JLabel("CASUAL LEAVES(CLS)");
JLabel l6 = new JLabel("PAY LEAVES(PLS)");
JLabel l7 = new JLabel("MEDICAL LEAVES(MLS)");
JLabel l8 = new JLabel("LEAVE WITHOUT PAY(LWP)");
f.setBounds(0,0,1280,750);
ImageIcon im9=new ImageIcon ("img\\main2.jpg");
JLabel lb9=new JLabel (im9);
lb9.setIcon(im9);
lb9.setBounds(0,0,1280,780);
ImageIcon im10=new ImageIcon ("img\\tag.jpg");
JLabel lb10=new JLabel (im10);
lb10.setIcon(im10);
lb10.setBounds(530,30,295,70);
t1.setText("0");
t2.setText("0");
t3.setText("0");
t4.setText("0");
t5.setText("0");
t6.setText("0");
t7.setText("0");
t8.setText("PERFORM OPERATION");
t2.enable(false);
t3.enable(false);
t4.enable(false);
t5.enable(false);
t6.enable(false);
t7.enable(false);
t8.enable(false);
l1.setBounds(590,5,300,25);
l2.setBounds(30,50,250,25);
l3.setBounds(30,130,250,25);
l4.setBounds(30,210,250,25);
l5.setBounds(30,290,250,25);
l6.setBounds(30,370,250,25);
l7.setBounds(30,450,250,25);
l8.setBounds(30,530,250,25);
t1.setBounds(320,50,200,25);
t2.setBounds(320,130,200,25);
t3.setBounds(320,210,200,25);
t4.setBounds(320,290,200,25);
t5.setBounds(320,370,200,25);
t6.setBounds(320,450,200,25);
t7.setBounds(320,530,200,25);
t8.setBounds(820,10,150,25);
b1.setBounds(900,100,67,67);
b2.setBounds(900,250,67,67);
b3.setBounds(900,400,67,67);
b4.setBounds(900,550,67,67);
content2.add(t1);
content2.add(t2);
content2.add(t3);
content2.add(t4);
content2.add(t5);
content2.add(t6);
Contact us :- 9313565406, 65495934
156
content2.add(t7);
content2.add(t8);
content2.add(l1);
content2.add(l2);
content2.add(l3);
content2.add(l4);
content2.add(l5);
content2.add(l6);
content2.add(l7);
content2.add(l8);
content2.add(b1);
content2.add(b2);
content2.add(b3);
content2.add(b4);
content2.add(lb10);
content2.add(lb9);
f.setVisible(true);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==b4)
{
f.dispose();
}
if(e.getSource()==b2)
{
t1.setText("0");
t2.setText("0");
t3.setText("0");
t4.setText("0");
t5.setText("0");
t6.setText("0");
t7.setText("0");
t8.setText("PERFORM OPERATION");
t2.enable(false);
t3.enable(false);
t4.enable(false);
t5.enable(false);
t6.enable(false);
t7.enable(false);
t8.enable(false);
}
if (e.getSource()==b3)
{
t2.enable(true);
t3.enable(true);
t4.enable(true);
t5.enable(true);
t6.enable(true);
t7.enable(true);
t8.enable(true);
empno=Integer.parseInt(t1.getText());
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll","root","1234");
java.sql.Statement st=conn.createStatement();
Contact us :- 9313565406, 65495934
157
ResultSet sear= st.executeQuery("select * from att_details where empno=
'"+ empno +" ' " );
if(sear.next())
{
empno=sear.getInt("empno");
for_month=sear.getInt("for_month");
year=sear.getInt("year");
cls=sear.getInt("cls");
pls=sear.getInt("pls");
mls=sear.getInt("mls");
lwp=sear.getInt("lwp");
t1.setText(String.valueOf(empno));
t2.setText(String.valueOf(for_month));
t3.setText(String.valueOf(year));
t4.setText(String.valueOf(cls));
t5.setText(String.valueOf(pls));
t6.setText(String.valueOf(mls));
t7.setText(String.valueOf(lwp));
t8.setText("RECORD SEARCHED!");
}
else
{
t8.setText("NO RECORD!");
t1.setText("0");
t2.setText("0");
t3.setText("0");
t4.setText("0");
t5.setText("0");
t6.setText("0");
t7.setText("0");
}
conn.close();
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
if(e.getSource()==b1)
{
empno=Integer.parseInt(t1.getText());
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll","root","1234");
java.sql.Statement st=conn.createStatement();
int del= st.executeUpdate("delete from att_details where empno= '"+ empno +" ' " );
Contact us :- 9313565406, 65495934
158
if(del==1)
t8.setText(" RECORD DELETED!");
else
{
t8.setText(" NO RECORD!");
t1.setText("0");
t2.setText("0");
t3.setText("0");
t4.setText("0");
t5.setText("0");
t6.setText("0");
t7.setText("0");
}
conn.close();
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
}
}
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
Contact us :- 9313565406, 65495934
159
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class att_modify extends JFrame implements ActionListener {
int empno ,for_month,year,cls,pls,mls,lwp;
Connection conn1;
JFrame f = new JFrame();
JTextField t1=new JTextField(20);
JTextField t2=new JTextField(20);
JTextField t3=new JTextField(20);
JTextField t4=new JTextField(20);
JTextField t5=new JTextField(20);
JTextField t6=new JTextField(20);
JTextField t7=new JTextField(20);
JTextField t8=new JTextField(20);
ImageIcon im1=new ImageIcon ("img\\save.jpg");
JButton b1 = new JButton (im1);
ImageIcon im2=new ImageIcon ("img\\reset.jpg");
JButton b2 = new JButton (im2);
ImageIcon im3=new ImageIcon ("img\\search.jpg");
JButton b3 = new JButton (im3);
ImageIcon im4=new ImageIcon ("img\\back.jpg");
JButton b4 = new JButton (im4);
public att_modify()
{
Container content2=f.getContentPane();
f.setTitle("MODIFY ATTENDENCE DETAILS");
f.setLayout(null);
content2.setBackground(Color.LIGHT_GRAY);
JLabel l1 = new JLabel("MODIFY ATTENDENCE DETAILS");
JLabel l2 = new JLabel("EMPLOYEE NUMBER");
JLabel l3 = new JLabel("FOR MONTH(MONTH NUMBER)");
JLabel l4 = new JLabel("YEAR");
JLabel l5 = new JLabel("CASUAL LEAVES(CLS)");
JLabel l6 = new JLabel("PAY LEAVES(PLS)");
JLabel l7 = new JLabel("MEDICAL LEAVES(MLS)");
JLabel l8 = new JLabel("LEAVE WITHOUT PAY(LWP)");
f.setBounds(0,0,1280,750);
t1.setText("0");
t2.setText("0");
t3.setText("0");
t4.setText("0");
t5.setText("0");
t6.setText("0");
t7.setText("0");
t8.setText("PERFORM OPERATION");
t2.enable(false);
t3.enable(false);
t4.enable(false);
t5.enable(false);
t6.enable(false);
t7.enable(false);
t8.enable(false);
Contact us :- 9313565406, 65495934
160
l1.setBounds(590,5,300,25);
l2.setBounds(30,50,250,25);
l3.setBounds(30,130,250,25);
l4.setBounds(30,210,250,25);
l5.setBounds(30,290,250,25);
l6.setBounds(30,370,250,25);
l7.setBounds(30,450,250,25);
l8.setBounds(30,530,250,25);
t1.setBounds(320,50,200,25);
t2.setBounds(320,130,200,25);
t3.setBounds(320,210,200,25);
t4.setBounds(320,290,200,25);
t5.setBounds(320,370,200,25);
t6.setBounds(320,450,200,25);
t7.setBounds(320,530,200,25);
t8.setBounds(820,10,150,25);
b1.setBounds(900,100,67,67);
b2.setBounds(900,250,67,67);
b3.setBounds(900,400,67,67);
b4.setBounds(900,550,67,67);
ImageIcon im9=new ImageIcon ("img\\main2.jpg");
JLabel lb9=new JLabel (im9);
lb9.setIcon(im9);
lb9.setBounds(0,0,1280,780);
ImageIcon im10=new ImageIcon ("img\\tag.jpg");
JLabel lb10=new JLabel (im10);
lb10.setIcon(im10);
lb10.setBounds(530,30,295,70);
content2.add(t1);
content2.add(t2);
content2.add(t3);
content2.add(t4);
content2.add(t5);
content2.add(t6);
content2.add(t7);
content2.add(t8);
content2.add(l1);
content2.add(l2);
content2.add(l3);
content2.add(l4);
content2.add(l5);
content2.add(l6);
content2.add(l7);
content2.add(l8);
content2.add(b1);
content2.add(b2);
content2.add(b3);
content2.add(b4);
content2.add(lb10);
content2.add(lb9);
f.setVisible(true);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==b4)
{
f.dispose();
Contact us :- 9313565406, 65495934
161
}
if(e.getSource()==b2)
{
t1.setText("0");
t2.setText("0");
t3.setText("0");
t4.setText("0");
t5.setText("0");
t6.setText("0");
t7.setText("0");
t8.setText("PERFORM OPERATION");
t2.enable(false);
t3.enable(false);
t4.enable(false);
t5.enable(false);
t6.enable(false);
t7.enable(false);
t8.enable(false);
}
if(e.getSource()==b1)
{
empno=Integer.parseInt(t1.getText());
for_month=Integer.parseInt(t2.getText());
year=Integer.parseInt(t3.getText());
cls=Integer.parseInt(t4.getText());
pls=Integer.parseInt(t5.getText());
mls=Integer.parseInt(t6.getText());
lwp=Integer.parseInt(t7.getText());
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
conn1=DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll","root","1234");
java.sql.Statement st=conn1.createStatement();
int del= st.executeUpdate("delete from att_details where empno= '"+
empno +" ' " );
java.sql.Statement st1=conn1.createStatement();
st1.executeUpdate("insert into att_details values('" + empno + "','" +
for_month + "' ,'" + year+"','" + cls + "','" + pls + "','" + mls + "','" + lwp + "')");
conn1.close();
t8.setText("SAVED SUCCESSFULLY!");
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
if (e.getSource()==b3)
{
t2.enable(true);
t3.enable(true);
t4.enable(true);
t5.enable(true);
t6.enable(true);
t7.enable(true);
t8.enable(true);
empno=Integer.parseInt(t1.getText());
try
Contact us :- 9313565406, 65495934
162
{
Class.forName("com.mysql.jdbc.Driver");
Connection
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll","root","1234");
java.sql.Statement st=conn.createStatement();
ResultSet sear= st.executeQuery("select * from att_details where empno=
'"+ empno +" ' " );
if(sear.next())
{
empno=sear.getInt("empno");
for_month=sear.getInt("for_month");
year=sear.getInt("year");
cls=sear.getInt("cls");
pls=sear.getInt("pls");
mls=sear.getInt("mls");
lwp=sear.getInt("lwp");
t1.setText(String.valueOf(empno));
t2.setText(String.valueOf(for_month));
t3.setText(String.valueOf(year));
t4.setText(String.valueOf(cls));
t5.setText(String.valueOf(pls));
t6.setText(String.valueOf(mls));
t7.setText(String.valueOf(lwp));
t8.setText("RECORD SEARCHED!");
}
else
{
t8.setText("NO RECORD!");
t1.setText("0");
t2.setText("0");
t3.setText("0");
t4.setText("0");
t5.setText("0");
t6.setText("0");
t7.setText("0");
}
conn.close();
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
}
}
Contact us :- 9313565406, 65495934
163
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.Statement;
import java.sql.*;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.*;
public class emp_q extends JFrame implements ActionListener {
String ename , sex,address,city,designation ,department,dob,doj,phone;
double gross , basic , net;
int empno,pf , gis , cca , hra , da ,it;
Connection conn1;
JFrame f = new JFrame();
JTextField t1=new JTextField(20);
JTextField t2=new JTextField(20);
JTextField t3=new JTextField(20);
JTextField t4=new JTextField(20);
JTextField t5=new JTextField(20);
JTextField t6=new JTextField(20);
JTextField t7=new JTextField(20);
JTextField t8=new JTextField(20);
JTextField t9=new JTextField(20);
JTextField t10=new JTextField(20);
JTextField t11=new JTextField(20);
JTextField t12=new JTextField(20);
JTextField t13=new JTextField(20);
JTextField t14=new JTextField(20);
JTextField t15=new JTextField(20);
JTextField t16=new JTextField(20);
JTextField t17=new JTextField(20);
JTextField t18=new JTextField(20);
JTextField t19=new JTextField(20);
JTextField t20=new JTextField(20);
Contact us :- 9313565406, 65495934
164
ImageIcon im3=new ImageIcon ("img\\search.jpg");
JButton b3 = new JButton (im3);
ImageIcon im4=new ImageIcon ("img\\exit.jpg");
JButton b4 = new JButton (im4);
public emp_q()
{
Container content2=f.getContentPane();
f.setTitle("EMPLOYEE DETAILS");
f.setLayout(null);
content2.setBackground(Color.LIGHT_GRAY);
JLabel l1 = new JLabel("EMPLOYEE DETAILS");
JLabel l2 = new JLabel(": : : : : : : : : EMPLOYEE DETAILS : : : : : : : : : :");
JLabel l3 = new JLabel("EMPLOYEE NO.");
JLabel l4 = new JLabel("EMPLOYEE NAME");
JLabel l5 = new JLabel("ADDRESS");
JLabel l6 = new JLabel("CITY");
JLabel l7 = new JLabel("DATE OF BIRTH");
JLabel l8 = new JLabel("DESIGNATION");
JLabel l9 = new JLabel("SEX");
JLabel l10 = new JLabel("PHONE NUMBER");
JLabel l11 = new JLabel("DATE OF JOIN");
JLabel l12 = new JLabel("DEPARTMENT");
JLabel l13 = new JLabel("BASIC SALARY");
JLabel l14 = new JLabel("PROVIDENT FUND(PF)");
JLabel l15 = new JLabel("CCA");
JLabel l16 = new JLabel("DEARLY ALLOWANCE(DA)");
JLabel l17 = new JLabel("GIS");
JLabel l18 = new JLabel("HOUSE RENT (HRA)");
JLabel l19 = new JLabel("GROSS SALARY");
JLabel l20 = new JLabel("INCOME TAX(IT)");
JLabel l21 = new JLabel("NET SALARY");
JLabel l22 = new JLabel(": : : : : : : : : SALARY DETAILS : : : : : : : : :");
f.setBounds(0,0,1280,750);
t1.setText("0");
t2.setText("----EMPTY----");
t3.setText("----EMPTY----");
t4.setText("----EMPTY----");
t5.setText("--/--/--");
t6.setText("----EMPTY----");
t7.setText("EMPTY");
t8.setText("0");
t9.setText("--/--/--");
t10.setText("----EMPTY----");
t11.setText("0");
t12.setText("0");
t13.setText("0");
t14.setText("0");
t15.setText("0");
t16.setText("0");
t17.setText("0");
t18.setText("0");
t19.setText("0");
t20.setText(" PERFORM OPERATION");
l1.setBounds(590,5,300,25);
l2.setBounds(30,20,250,25);
l3.setBounds(30,50,150,25);
l4.setBounds(30,100,150,25);
l5.setBounds(30,150,150,25);
l6.setBounds(30,200,150,25);
l7.setBounds(30,250,150,25);
l8.setBounds(30,300,150,25);
Contact us :- 9313565406, 65495934
165
l9.setBounds(460,100,150,25);
l10.setBounds(460,200,150,25);
l11.setBounds(460,250,150,25);
l12.setBounds(460,300,150,25);
l13.setBounds(30,375,180,25);
l14.setBounds(30,415,180,25);
l15.setBounds(30,455,180,25);
l16.setBounds(30,495,150,25);
l17.setBounds(520,425,180,25);
l18.setBounds(520,475,180,25);
l19.setBounds(30,535,180,25);
l20.setBounds(30,575,180,25);
l21.setBounds(30,615,180,25);
l22.setBounds(30,336,300,25);
b3.setBounds(900,200,67,67);
b4.setBounds(900,400,67,67);
t1.setBounds(200,50,60,25);
t2.setBounds(200,100,200,25);
t3.setBounds(200,150,600,25);//address
t4.setBounds(200,200,200,25);
t5.setBounds(200,250,200,25);
t6.setBounds(200,300,200,25);
t7.setBounds(600,100,45,25);//sex
t8.setBounds(600,200,200,25);//below sex
t9.setBounds(600,250,200,25);
t10.setBounds(600,300,200,25);
t11.setBounds(300,375,200,25);
t12.setBounds(300,415,200,25);
t13.setBounds(300,455,200,25);
t14.setBounds(300,495,200,25);
t15.setBounds(700,425,100,25);
t16.setBounds(700,475,100,25);
t17.setBounds(300,535,200,25);
t18.setBounds(300,575,200,25);
t19.setBounds(300,615,200,25);
t20.setBounds(820,10,150,25);
t2.enable(false);
t3.enable(false);
t4.enable(false);
t5.enable(false);
t6.enable(false);
t7.enable(false);
t8.enable(false);
t9.enable(false);
t10.enable(false);
t11.enable(false);
t12.enable(false);
t13.enable(false);
t14.enable(false);
t15.enable(false);
t16.enable(false);
t17.enable(false);
t18.enable(false);
t19.enable(false);
t20.enable(false);
ImageIcon im9=new ImageIcon ("img\\main2.jpg");
JLabel lb9=new JLabel (im9);
lb9.setIcon(im9);
lb9.setBounds(0,0,1280,780);
ImageIcon im10=new ImageIcon ("img\\tag.jpg");
JLabel lb10=new JLabel (im10);
lb10.setIcon(im10);
lb10.setBounds(530,30,295,70);
Contact us :- 9313565406, 65495934
166
content2.add(t1);
content2.add(t2);
content2.add(t3);
content2.add(t4);
content2.add(t5);
content2.add(t6);
content2.add(t7);
content2.add(t8);
content2.add(t9);
content2.add(t10);
content2.add(t11);
content2.add(t12);
content2.add(t13);
content2.add(t14);
content2.add(t15);
content2.add(t16);
content2.add(t17);
content2.add(t18);
content2.add(t19);
content2.add(t20);
content2.add(l1);
content2.add(l2);
content2.add(l3);
content2.add(l4);
content2.add(l5);
content2.add(l6);
content2.add(l7);
content2.add(l8);
content2.add(l9);
content2.add(l10);
content2.add(l11);
content2.add(l12);
content2.add(l13);
content2.add(l14);
content2.add(l15);
content2.add(l16);
content2.add(l17);
content2.add(l18);
content2.add(l19);
content2.add(l20);
content2.add(l21);
content2.add(l22);
content2.add(b3);
content2.add(b4);
content2.add(lb10);
content2.add(lb9);
f.setVisible(true);
b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==b4)
{
f.dispose();
}
if (e.getSource()==b3)
Contact us :- 9313565406, 65495934
167
{
t20.enable(true);
empno=Integer.parseInt(t1.getText());
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll","root","1234");
java.sql.Statement st=conn.createStatement();
ResultSet sear= st.executeQuery("select * from emp_details where empno= '"+
empno +" ' " );
if(sear.next())
{
t2.enable(true);
t3.enable(true);
t4.enable(true);
t5.enable(true);
t6.enable(true);
t7.enable(true);
t8.enable(true);
t9.enable(true);
t10.enable(true);
t11.enable(true);
t12.enable(true);
t13.enable(true);
t14.enable(true);
t15.enable(true);
t16.enable(true);
t17.enable(true);
t18.enable(true);
t19.enable(true);
empno=sear.getInt("empno");
ename=sear.getString("ename");
sex=sear.getString("sex");
address=sear.getString("address");
phone=sear.getString("phone");
city=sear.getString("city");
dob=sear.getString("dob");
doj=sear.getString("doj");
designation=sear.getString("designation");
department=sear.getString("department");
basic=sear.getDouble("basic");
pf=sear.getInt("pf");
gis=sear.getInt("gis");
cca=sear.getInt("cca");
hra=sear.getInt("hra");
da=sear.getInt("da");
gross=sear.getDouble("gross");
it=sear.getInt("it");
net=sear.getDouble("net");
t1.setText(String.valueOf(empno));
t2.setText(ename);
t3.setText(address);
t4.setText(city);
t5.setText(dob);
t6.setText(designation);
t7.setText(sex);
Contact us :- 9313565406, 65495934
168
t8.setText(String.valueOf(phone));
t9.setText(doj);
t10.setText(department);
t11.setText(String.valueOf(basic));
t12.setText(String.valueOf(pf));
t13.setText(String.valueOf(cca));
t14.setText(String.valueOf(da));
t15.setText(String.valueOf(gis));
t16.setText(String.valueOf(hra));
t17.setText(String.valueOf(gross));
t18.setText(String.valueOf(it));
t19.setText(String.valueOf(net));
t20.setText("RECORD SEARCHED!");
}
else
{
t20.setText("NO RECORD!");
t1.setText("0");
t2.setText("----EMPTY----");
t3.setText("----EMPTY----");
t4.setText("----EMPTY----");
t5.setText("--/--/--");
t6.setText("----EMPTY----");
t7.setText("EMPTY");
t8.setText("0");
t9.setText("--/--/--");
t10.setText("----EMPTY----");
t11.setText("0");
t12.setText("0");
t13.setText("0");
t14.setText("0");
t15.setText("0");
t16.setText("0");
t17.setText("0");
t18.setText("0");
t19.setText("0");
}
conn.close();
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
}
}
Delete att details
Contact us :- 9313565406, 65495934
169
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class att_q extends JFrame implements ActionListener {
int empno ,for_month,year,cls,pls,mls,lwp;
Connection conn1;
JFrame f = new JFrame();
JTextField t1=new JTextField(20);
JTextField t2=new JTextField(20);
JTextField t3=new JTextField(20);
JTextField t4=new JTextField(20);
JTextField t5=new JTextField(20);
JTextField t6=new JTextField(20);
JTextField t7=new JTextField(20);
JTextField t8=new JTextField(20);
ImageIcon im3=new ImageIcon ("img\\search.jpg");
JButton b3 = new JButton (im3);
ImageIcon im4=new ImageIcon ("img\\exit.jpg");
JButton b4 = new JButton (im4);
public att_q()
{
Container content2=f.getContentPane();
f.setTitle("DELETE ATTENDENCE DETAILS");
f.setLayout(null);
content2.setBackground(Color.LIGHT_GRAY);
JLabel l1 = new JLabel("DELETE ATTENDENCE DETAILS");
JLabel l2 = new JLabel("EMPLOYEE NUMBER");
JLabel l3 = new JLabel("FOR MONTH(MONTH NUMBER)");
JLabel l4 = new JLabel("YEAR");
JLabel l5 = new JLabel("CASUAL LEAVES(CLS)");
JLabel l6 = new JLabel("PAY LEAVES(PLS)");
JLabel l7 = new JLabel("MEDICAL LEAVES(MLS)");
JLabel l8 = new JLabel("LEAVE WITHOUT PAY(LWP)");
f.setBounds(0,0,1280,750);
t1.setText("0");
t2.setText("0");
t3.setText("0");
t4.setText("0");
t5.setText("0");
t6.setText("0");
t7.setText("0");
t8.setText("PERFORM OPERATION");
t2.enable(false);
t3.enable(false);
t4.enable(false);
t5.enable(false);
t6.enable(false);
t7.enable(false);
Contact us :- 9313565406, 65495934
170
t8.enable(false);
l1.setBounds(590,5,300,25);
l2.setBounds(30,50,250,25);
l3.setBounds(30,130,250,25);
l4.setBounds(30,210,250,25);
l5.setBounds(30,290,250,25);
l6.setBounds(30,370,250,25);
l7.setBounds(30,450,250,25);
l8.setBounds(30,530,250,25);
t1.setBounds(320,50,200,25);
t2.setBounds(320,130,200,25);
t3.setBounds(320,210,200,25);
t4.setBounds(320,290,200,25);
t5.setBounds(320,370,200,25);
t6.setBounds(320,450,200,25);
t7.setBounds(320,530,200,25);
t8.setBounds(820,10,150,25);
b3.setBounds(900,400,67,67);
b4.setBounds(900,550,67,67);
ImageIcon im9=new ImageIcon ("img\\main2.jpg");
JLabel lb9=new JLabel (im9);
lb9.setIcon(im9);
lb9.setBounds(0,0,1280,780);
ImageIcon im10=new ImageIcon ("img\\tag.jpg");
JLabel lb10=new JLabel (im10);
lb10.setIcon(im10);
lb10.setBounds(530,30,295,70);
content2.add(t1);
content2.add(t2);
content2.add(t3);
content2.add(t4);
content2.add(t5);
content2.add(t6);
content2.add(t7);
content2.add(t8);
content2.add(l1);
content2.add(l2);
content2.add(l3);
content2.add(l4);
content2.add(l5);
content2.add(l6);
content2.add(l7);
content2.add(l8);
content2.add(b3);
content2.add(b4);
content2.add(lb10);
content2.add(lb9);
f.setVisible(true);
b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==b4)
{
f.dispose();
}
Contact us :- 9313565406, 65495934
171
if (e.getSource()==b3)
{
t8.enable(true);
empno=Integer.parseInt(t1.getText());
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll","root","1234");
java.sql.Statement st=conn.createStatement();
ResultSet sear= st.executeQuery("select * from att_details
where empno= '"+ empno +" ' " );
if(sear.next())
{
t2.enable(true);
t3.enable(true);
t4.enable(true);
t5.enable(true);
t6.enable(true);
t7.enable(true);
empno=sear.getInt("empno");
for_month=sear.getInt("for_month");
year=sear.getInt("year");
cls=sear.getInt("cls");
pls=sear.getInt("pls");
mls=sear.getInt("mls");
lwp=sear.getInt("lwp");
t1.setText(String.valueOf(empno));
t2.setText(String.valueOf(for_month));
t3.setText(String.valueOf(year));
t4.setText(String.valueOf(cls));
t5.setText(String.valueOf(pls));
t6.setText(String.valueOf(mls));
t7.setText(String.valueOf(lwp));
t8.setText("RECORD SEARCHED!");
}
else
{
t8.setText("NO RECORD!");
t1.setText("0");
t2.setText("0");
t3.setText("0");
t4.setText("0");
t5.setText("0");
t6.setText("0");
t7.setText("0");
}
conn.close();
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
Contact us :- 9313565406, 65495934
172
}
}
}
}
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class List_Employee extends JFrame implements ActionListener
{
Font a;
JTable t;
JFrame f=new JFrame("List_Employee");
ImageIcon im1=new ImageIcon ("img\\ok.jpg");
JButton b1 = new JButton (im1);
Contact us :- 9313565406, 65495934
173
public List_Employee()
{
int i=0,cnt=0,j;
Container content=f.getContentPane();
f.setBounds(0,0,1283,750);
content.setBackground(Color.cyan);
b1.setBounds(640,500,67,67);
a=new Font("Dialog Input",Font.PLAIN,14);
ImageIcon im10=new ImageIcon ("img\\tag.jpg");
JLabel lb10=new JLabel (im10);
lb10.setIcon(im10);
lb10.setBounds(530,375,295,70);
String
colh[]={"Empno","Ename","Sex","Address","Phone","City","Dob","Doj","Designation","Department","Basic","PF","GIS","CC
A","HRA","DA","Gross","IT","Net"};
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll","root","1234");
Statement st=con.createStatement();
ResultSet res=st.executeQuery("Select * from emp_details");
while(res.next())
{
cnt+=1;
}
Statement st1=con.createStatement();
ResultSet res1=st1.executeQuery("Select * from emp_details");
Object data[][]=new Object[20][20];
while(res1.next())
{
data[i][0]=res1.getInt("empno");
data[i][1]=res1.getString("ename");
data[i][2]=res1.getString("sex");
data[i][3]=res1.getString("address");
data[i][4]=res1.getString("phone");
data[i][5]=res1.getString("city");
data[i][6]=res1.getString("dob");
data[i][7]=res1.getString("doj");
data[i][8]=res1.getString("designation");
data[i][9]=res1.getString("department");
data[i][10]=res1.getDouble("basic");
data[i][11]=res1.getInt("pf");
data[i][12]=res1.getInt("gis");
data[i][13]=res1.getInt("cca");
data[i][14]=res1.getInt("hra");
data[i][15]=res1.getInt("da");
data[i][16]=res1.getDouble("gross");
data[i][17]=res1.getInt("it");
data[i][18]=res1.getDouble("net");
i++;
}
t=new JTable(data,colh);
Contact us :- 9313565406, 65495934
174
JScrollPane jp=new JScrollPane(t);
//t.setBackground(Color.red);
//jp.setBounds(0,100,1280,650);
t.setFont(a);
content.add(lb10);
content.add(b1);
content.add(jp);
f.setVisible(true);
con.close();
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==b1)
{
f.dispose();
}
}
}
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
Contact us :- 9313565406, 65495934
175
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class List_Attendence extends JFrame implements ActionListener
{
Font a;
JTable t;
JFrame f=new JFrame("List_Attendence");
ImageIcon im1=new ImageIcon ("img\\ok.jpg");
JButton b1 = new JButton (im1);
public List_Attendence()
{
int i=0,cnt=0,j;
Container content=f.getContentPane();
f.setBounds(0,0,1283,750);
//content.setBackground(Color.cyan);
ImageIcon im10=new ImageIcon ("img\\tag.jpg");
JLabel lb10=new JLabel (im10);
lb10.setIcon(im10);
lb10.setBounds(530,375,295,70);
a=new Font("Dialog Input",Font.PLAIN,14);
String colh[]={"Empno","For_month","Year","CLS","PLS","MLS","LWP"};
b1.setBounds(640,500,67,67);
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll","root","1234");
Statement st=con.createStatement();
ResultSet res=st.executeQuery("Select * from att_details");
while(res.next())
{
cnt+=1;
}
Statement st1=con.createStatement();
ResultSet res1=st1.executeQuery("Select * from att_details");
Object data[][]=new Object[20][20];
while(res1.next())
{
data[i][0]=res1.getInt("empno");
data[i][1]=res1.getInt("for_month");
data[i][2]=res1.getInt("year");
data[i][3]=res1.getInt("cls");
data[i][4]=res1.getInt("pls");
data[i][5]=res1.getInt("mls");
data[i][6]=res1.getInt("lwp");
Contact us :- 9313565406, 65495934
176
i++;
}
t=new JTable(data,colh);
JScrollPane jp=new JScrollPane(t);
//t.setBackground(Color.red);
//jp.setBounds(0,100,1280,650);
t.setFont(a);
content.add(lb10);
content.add(b1);
content.add(jp);
f.setVisible(true);
con.close();
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==b1)
{
f.dispose();
}
}
}
import java.awt.Color;
import java.awt.Container;
Contact us :- 9313565406, 65495934
177
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.*;;
public class salary extends JFrame implements ActionListener {
String ename , sex,address,city,designation ,department,dob,doj,phone;
Connection conn;
double gross , basic , net;
int empno,pf , gis , cca , hra , da ,it;
Font a=new Font("Dialog Input",Font.BOLD,18);
JTextField t1 = new JTextField(20);
JLabel l2 = new JLabel("EMPLOYEE DETAILS");
JLabel l3 = new JLabel("EMPLOYEE NO.");
JLabel l4 = new JLabel("EMPLOYEE NAME");
JLabel l5 = new JLabel("ADDRESS");
JLabel l6 = new JLabel("CITY");
JLabel l7 = new JLabel("DATE OF BIRTH");
JLabel l8 = new JLabel("DESIGNATION");
JLabel l9 = new JLabel("SEX");
JLabel l10 = new JLabel("PHONE NUMBER");
JLabel l11 = new JLabel("DATE OF JOIN");
JLabel l12 = new JLabel("DEPARTMENT");
JLabel l13 = new JLabel("BASIC SALARY");
JLabel l14 = new JLabel("PROVIDENT FUND(PF)");
JLabel l15 = new JLabel("CCA");
JLabel l16 = new JLabel("DEARLY ALLOWANCE(DA)");
JLabel l17 = new JLabel("GIS");
JLabel l18 = new JLabel("HOUSE RENT (HRA)");
JLabel l19 = new JLabel("GROSS SALARY");
JLabel l20 = new JLabel("INCOME TAX(IT)");
JLabel l21 = new JLabel("NET SALARY");
JLabel l22 = new JLabel("SALARY DETAILS");
JLabel l23 = new JLabel();
JLabel l24 = new JLabel();
JLabel l25 = new JLabel();
JLabel l26 = new JLabel();
JLabel l27 = new JLabel();
JLabel l28 = new JLabel();
JLabel l29 = new JLabel();
JLabel l30 = new JLabel();
JLabel l31 = new JLabel();
JLabel l32 = new JLabel();
JLabel l33 = new JLabel();
JLabel l34 = new JLabel();
JLabel l35 = new JLabel();
JLabel l36 = new JLabel();
JLabel l37 = new JLabel();
JLabel l38 = new JLabel();
JLabel l39 = new JLabel();
JLabel l40 = new JLabel();
JLabel l41 = new JLabel();
JLabel l43 = new JLabel("PAY-SLIP");
JLabel l42 = new JLabel(" ENTER EMPLOYEE NO. ");
ImageIcon im3=new ImageIcon ("img\\search.jpg");
JButton b3 = new JButton (im3);
ImageIcon im1=new ImageIcon ("img\\ok.jpg");
JButton b1 = new JButton (im1);
JFrame f = new JFrame("SALARY STATEMENT");
public salary()
{
Contact us :- 9313565406, 65495934
178
Container content = f.getContentPane();
f.setBounds(0, 0, 1280, 750);
f.setLayout(null);
content.setBackground(Color.white);
ImageIcon im10=new ImageIcon ("img\\tag.jpg");
JLabel lb10=new JLabel (im10);
lb10.setIcon(im10);
lb10.setBounds(485,40,295,70);
l43.setFont(a);
t1.setText("0");
b1.setBounds(950,147,58,56);
b3.setBounds(700,147,58,56);
t1.setBounds(500,165,100,25);
l2.setBounds(30,200,250,25);
l2.setFont(a);
l3.setBounds(30,230,150,25);
l23.setBounds(250,230,150,25);
l4.setBounds(30,260,150,25);
l24.setBounds(250,260,150,25);
l5.setBounds(30,290,150,25);
l25.setBounds(250,290,150,25);
l6.setBounds(30,320,150,25);
l26.setBounds(250,320,150,25);
l7.setBounds(30,350,150,25);
l27.setBounds(250,350,150,25);
l8.setBounds(30,380,150,25);
l28.setBounds(250,380,150,25);
l9.setBounds(620,260,150,25);
l29.setBounds(830,260,150,25);
l10.setBounds(620,290,150,25);
l30.setBounds(830,290,150,25);
l11.setBounds(620,320,150,25);
l31.setBounds(830,320,150,25);
l12.setBounds(620,350,150,25);
l32.setBounds(830,350,150,25);
l13.setBounds(30,440,180,25);
l33.setBounds(250,440,150,25);
l14.setBounds(30,470,180,25);
l34.setBounds(250,470,150,25);
l15.setBounds(30,500,180,25);
l35.setBounds(250,500,150,25);
l16.setBounds(30,530,150,25);
l36.setBounds(250,530,150,25);
l17.setBounds(620,530,180,25);
l37.setBounds(830,530,150,25);
l18.setBounds(620,560,180,25);
l38.setBounds(830,560,150,25);
l19.setBounds(30,560,180,25);
l39.setBounds(250,560,150,25);
l20.setBounds(30,590,180,25);
l40.setBounds(250,590,150,25);
l21.setBounds(30,620,180,25);
l41.setBounds(250,620,150,25);
l22.setBounds(30,410,180,25);
l42.setBounds(250,165,180,25);
l43.setBounds(600,20,180,25);
l22.setFont(a);
content.add(t1);
content.add(l2);
content.add(l3);
content.add(l4);
content.add(l5);
Contact us :- 9313565406, 65495934
179
content.add(l6);
content.add(l7);
content.add(l8);
content.add(l9);
content.add(l10);
content.add(l11);
content.add(l12);
content.add(l13);
content.add(l14);
content.add(l15);
content.add(l16);
content.add(l17);
content.add(l18);
content.add(l19);
content.add(l20);
content.add(l21);
content.add(l22);
content.add(l23);
content.add(l24);
content.add(l25);
content.add(l26);
content.add(l27);
content.add(l28);
content.add(l29);
content.add(l30);
content.add(l31);
content.add(l32);
content.add(l33);
content.add(l34);
content.add(l35);
content.add(l36);
content.add(l37);
content.add(l38);
content.add(l39);
content.add(l40);
content.add(l41);
content.add(l42);
content.add(l43);
content.add(b3);
content.add(b1);
content.add(lb10);
b3.addActionListener(this);
b1.addActionListener(this);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==b1)
{
f.dispose();
}
if (e.getSource()==b3)
{
empno=Integer.parseInt(t1.getText());
try
Class.forName("com.mysql.jdbc.Driver");
Connection
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll","root","1234");
java.sql.Statement st=conn.createStatement();
ResultSet sear= st.executeQuery("select * from emp_details where empno= '"+
empno +" ' " );
if(sear.next())
{
Contact us :- 9313565406, 65495934
180
empno=sear.getInt("empno");
ename=sear.getString("ename");
sex=sear.getString("sex");
address=sear.getString("address");
phone=sear.getString("phone");
city=sear.getString("city");
dob=sear.getString("dob");
doj=sear.getString("doj");
designation=sear.getString("designation");
department=sear.getString("department");
basic=sear.getDouble("basic");
pf=sear.getInt("pf");
gis=sear.getInt("gis");
cca=sear.getInt("cca");
hra=sear.getInt("hra");
da=sear.getInt("da");
gross=sear.getDouble("gross");
it=sear.getInt("it");
net=sear.getDouble("net");
l23.setText(String.valueOf(empno));
l24.setText(ename);
l25.setText(address);
l26.setText(city);
l27.setText(dob);
l28.setText(designation);
l29.setText(sex);
l30.setText(String.valueOf(phone));
l31.setText(doj);
l32.setText(department);
l33.setText(String.valueOf(basic));
l34.setText(String.valueOf(pf));
l35.setText(String.valueOf(cca));
l36.setText(String.valueOf(da));
l37.setText(String.valueOf(gis));
l38.setText(String.valueOf(hra));
l39.setText(String.valueOf(gross));
l40.setText(String.valueOf(it));
l41.setText(String.valueOf(net));
conn.close();
}
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
}
}
Contact us :- 9313565406, 65495934
181