Java

25
Advanced JAVA: OOP and Networking Dr. Hong Li*, Dr. Ali Setoodehnia *New York City College of Technology Kean University April 11, 2003

Transcript of Java

Page 1: Java

Advanced JAVA: OOP and Networking

Dr. Hong Li*, Dr. Ali Setoodehnia*New York City College of

TechnologyKean University

April 11, 2003

Page 2: Java

2

AGENDA:

1.Introduction to Java2.Introduction to Java

Applets3.OOP, methods4.Java Networking

Page 3: Java

3

Introduction to Java

Java is fully object-oriented languageJava has rich collection of existing

classes in java class libraries ( also known as Java APIs

Two pieces to learn “JAVA” Learning java language itself so that you

can program your own classes Learning how to use the classes in

extensive Java class libraries

Page 4: Java

4

Java is case sensitive public class name identical to the file

name file name: name.javastatic main method will be automatic

executedstandard output object: system.outcompile: javac name.java ; this creates

name.classexecute: java name

Page 5: Java

5

A simple program: welcome.java

public class Welcome { public static void main( String args[] ) { System.out.print( "Welcome to " ); System.out.println( "Java Programming!“); }}

Welcome toJava Programming!

Page 6: Java

6

Introduction to Java Applet

What is Applet? A program written in the Java to run

within a web browser. Java applets begin execution with a series of

init(), start(), and paint() methods. ;stop(), and destroy() methods are available.

Every Java applet should extend either class Japplet or class Applet.

Compile: javac graph.java ; creates graph.class

Page 7: Java

7

Insert a applet tag in HTML

<html> <head> <title>Simple Graph (1.1)</title> </head> <body> <h1>Simple Graph(1.1)</h1> <hr> <applet code=graph.class width=300 height=120 > </applet> <hr> <a href=“graph.java">Click here to view source</a>. </body></html>

Page 8: Java

8

GraphApplet.java

import java.awt.Graphics; public class GraphApplet extends java.applet.Applet { double f(double x) { return (Math.cos(x/5) + Math.sin(x/7) + 2) *

getSize().height / 4; } public void paint(Graphics g) { for (int x = 0 ; x < getSize().width ; x++) {

g.drawLine(x, (int)f(x), x + 1, (int)f(x + 1)); } } public String getAppletInfo() { return "Draws a sin graph."; }

An Example of Applet

Page 9: Java

9

FUNDEMENTAL OFOBJECT-ORIENTED

PROGRAMMING

What is an object? An object is a computer structure An object is an abstract concept Objects normally contain both data

and related procedure

A class contains data method

Page 10: Java

10

Creating object

The syntax for creating an object is as: objectName = new className(); myCircle = new circle();

After an object is created, it can access data and methods by using the dot notation: Object.data: circle.radius Object.method: circle.findarea()

Page 11: Java

11

Instance Variables and class Variables

Instance variables belong to each instance of the class;

Example: Circle myCircle = new Circule(); Circule yourCircle=new Circle;

The data in myCircle is independent of yourCircle, and are in different memory locations.

The instances of a class can share data, using class variable.

Class variables (static ) store values for the variables in a common memory location.

To declare a class variable static double weight; // class variable

Page 12: Java

12

Instance Method and Class Methods(static methods)

Instance methods belong to instances and can be applied after the instances are created.

They are called by: objectName.methodName(); Java supports class methods as well as class

variables. Class method can be called without creating an

instance of the class. To define a class method static returnValueType staticMethod(); Class method are called by one of the following

syntax: className.methodName(); objectName.methodName();

Page 13: Java

13

STRING class: java.lang.String

To creat a string explicitly use:String newString = new String(s);

String Comparisons; // = = , or s1.comparTo(s2) can be used.

String Concatination: you can use concat() method or +string s3 = s1.concat(s2); orString myString = message + “and” + “xyz”;

Substring()

Page 14: Java

14

StringBuffer class This is an alternative to the string class.

It is more flexible than String. This has many method for manipulations.

public StringBuffer(); public StringBuffer(int length); public StringBuffer(String str); add(); insert(); append();capacity(); reverse(); length();setLength(); charAt();

setCharAt()

Page 15: Java

15

StringTokenizer Class

The java.utit.StringTokenizer class is used to break string into pieces.

The StringTokenizer provides three constructos:

public StringTokenizer(String s, String delim, boolean returenTokens);

public StringTokenizer(String s, String delim); public StringTokenizer(String s); How does this class recognize the words? set the delimiter, this breaks a

string into pices known as tokens.

Page 16: Java

16

StringTokenizer Continue

Some of the instance methods are: public boolean

hasMoreToken(); public String nextToken();

public String nextToken(String delim);

public int countToken();

Page 17: Java

17

JAVA-Networking

Manipulating URL Establishing a simple ClientEstablishing a simple serverClient/Server Interaction with Socket Connection

Page 18: Java

18

Manipulating URL

Java is using a URL as an argument to the ShowDocument method of class AppletContext , this will open the URL

import java.net.*; // .net library URL url; //declare url as URL url = new URL(location);// create URL object AppletContext Browser = getAppletContext(); browser.showDocument(url); // cause browser to

// display the url Example: View HTML file View Code

Page 19: Java

19

Socket-based communication

Socket is an abstraction that facilitates communication between a server and a clientJava treats socket communications much as it treats I/O operationsThus, a program can read from a socket or write to a socket as simply as it can read from a file or writing to a file.Java support stream socket and datagram socketStream socket use TCP(Transmission Control Protocol)Datagram sockets use UDP(user datagram Protocol)

Page 20: Java

20

Client/Server

Server run

Waiting for connection

Read input

Send output

Read ..

..

close

Client connect

Send output

Read input

Close connection

Page 21: Java

21

Client-Server relationship

Server must be running when a client startsServer wait for a connection request from a clientAfter the sever accepts the connection, communication between the server and the client is conducted the same as for I/O streamsClient close the connectionServer can serve multiple clients

Page 22: Java

22

To establish a simple server

1. Create a ServerSocket object ServerSocket server_socket = new ServerSocket(port, queuelength); the port identifies the TCP service on the socket. Port number between 0 and 1023 are reserved for privileged processes. For instance, email server run on 25, web server usually 802. The server waits for connection from client Socket conn = server_socket.accept();

Page 23: Java

23

To establish server-continued

3. Get the OutputStream and InputStream objects that enable the server to communicate with the client ObjectInputStream in = new ObjectInputStream(conn.getInputStream()); ObjectOutputStream out = new ObjectOutputStream(conn.getOutputStream());4. Processing phase: Server and client communicate via the InputStream (in) and OutputStream (out) objects5. When the transmission is complete, the server closes the connection by invoking the close method on the Socket. View code run server

Page 24: Java

24

To establish a simple client

1. Create a Socket to connect to the server socket conn = new Socket(serverAddress, port);

2. Socket methods getInputStream and getoutputStream are used to get references to the Socket associated InputStream and OutputStream.

3. Processing phase: Client and server communicate via the InputStream and OutputStream objects.

4. When transmission is complete, the client closes the connection by invoking the close method on the Socket

view code run client run client

Page 25: Java

25

Development Tools

Use JDK (“SDK”) 1.2 (current version is 1.2.2), also known as “Java 2.”Use a Programmer’s editor, not Notepad. Programmer’s File Editor (PFE)

See [ Development Tools ] web page for download and setup help.To download Java runtime environmenthttp://java.sun.com/j2se/1.3/jre/install-windows.html