What is Java - Projects Org
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-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 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 object-oriented 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 byte-code. 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
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);
}
}
}
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 > < >= > >>> |
|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.
[pic]
Java language supports few special escape sequences for String and char literals as well. They are:
[pic]
|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 | Description | Size/Format |
| byte | Byte-length integer | 8-bit two's complement |
| short | Short integer | 16-bit two's complement |
| int | Integer | 32-bit two's complement |
| long | Long integer | 64-bit two's complement |
| float | Single-precision floating point | 32-bit IEEE |
| double | Double-precision floating point | 64-bit IEEE |
| char | A single character | 16-bit Unicode character |
| boolean | A boolean value (true or false) | 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.
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 |
|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
}
| |
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.
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();
}
}
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 |while |
|for |do while |
|switch case |break |
|continue | |
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 {
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]);
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.
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;
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 = 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;
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);
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) {
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
The Classes
• ContentHandler
• DatagramPacket
• DatagramSocket
• DatagramSocketImpl
• HttpURLConnection
• InetAddress
• MulticastSocket
• ServerSocket
• Socket
• SocketImpl
• 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.
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 .*;
public class AppleAddresses {
public static void main (String args[]) {
try {
InetAddress[] addresses = InetAddress.getAllByName("");
for (int i = 0; i < addresses.length; i++) {
System.out.println(addresses[i]);
}
}
catch (UnknownHostException ex) {
System.out.println("Could not find ");
}
}
}
This prints the following:
17.254.3.28
17.254.3.37
17.254.3.61
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);
}
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 .*;
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.
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:
mailto:elharo@metalab.unc.edu
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)
• the query string
The .URL class
• file
• ftp
• gopher
• http
• mailto
• appletresource
• doc
• netdoc
• systemresource
• verbatim
Constructing URL Objects
There are four constructors in the .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 , you construct a URL object for that URL like this:
URL u = null;
try {
u = new URL("");
}
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", "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", "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("");
URL u2 = new URL(u1, "08.html");
}
catch (MalformedURLException ex) {
}
Parsing URLs
The .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("");
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 .*;
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. 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 .Socket class
The .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)
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 .*;
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);
}
}
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 .*;
import java.io.*;
public class Grabber {
public static void main(String[] args) {
int port = 80;
for (int i = 0; i < args.length; i++) {
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 .*;
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);
}
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);
}
}
}
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 .ServerSocket Class
The .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 .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.
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 .ServerSocket Constructors
The .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 .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 {
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);
}
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 .*;
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 = 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.
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 .*;
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 = 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
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 .*;
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 = 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;
}
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 .*;
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) {
}
if (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
Project
PAYROLL SOLUTION
[pic]
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);
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);
}
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);
}
}
[pic]
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 {
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);
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();
}
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();
}
}
}
[pic]
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_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");
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);
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);
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());
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);
gis=(int) (0.06*basic);
cca=1500;
t12.setText(String.valueOf(pf));
t13.setText(String.valueOf(cca));
t15.setText(String.valueOf(gis));
if(basic ................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
- intro to computer science cs10061 11744
- what is java projects org
- enter title here 14 pt type size 10 words max uppercase
- java tutorial oocities
- data formats college of computing
- using the java fits utilities
- why java programming named java
- life long learning journey new page
- using the java fits utilities iucaa
- the florida state university
Related searches
- it is what is meaning
- java projects with source code
- good java projects for beginners
- java projects for students
- easy java projects for beginners
- free java projects for students
- java projects for intermediates
- what is good and what is evil
- what is org design
- what is an org chart
- small java projects for beginners
- java projects for beginners