Beruflich Dokumente
Kultur Dokumente
Object-Oriented Programming
for the Internet
What is Java?
4 A way to make Web pages?
4 A language like C++, Smalltalk?
4 Computing Platform
– Java Programming Language
– Java (Virtual) Machine (JVM)
– Java API (Application Programmers’ Interface)
• MFC
Overview
4 Introducing Java
– Key features of the language
4 Principles of Object Oriented Programming
– What is OOP? Why is it important?
– Basic principles and advantages
4 The Unified Modelling Language
– UML Class Diagrams
Some History
4 Developed and maintained by Sun Microsystems
– Originally called Oak
– Aimed at producing an operating environment for
networked devices and embedded systems
– …but has been much more successful
4 Design objectives for the language
– Simple, object-oriented,
– Distributed, multi-threaded, and platform neutral
– Robust, secure, scaleable
The Virtual Machine
4 Java is both compiled and interpreted
– Source code is compiled into Java bytecode
– Which is then interpreted by the Java Virtual Machine (JVM)
– Therefore bytecode is machine code for the JVM
4 Java bytecode can run on any JVM, on any platform
– …including mobile phones and other hand-held devices
4 Networking and distribution are core features
– In other languages these are additional APIs
– Makes Java very good for building networked applications, server
side components, etc.
Features of the JVM
4 The Garbage Collector
– Java manages memory for you, the developer has no control over
the allocation of memory (unlike in C/C++).
– This is much simpler and more robust (no chance of memory leaks
or corruption)
– Runs in the background and cleans up memory while application is
running
4 The Just In Time compiler (JIT)
– Also known as “Hot Spot”
– Continually optimises running code to improve performance
– Can approach the speed of C++ even though its interpreted
Features of the JVM
4 Security
– Java offers very fine control over what an application is allowed to
do
– E.g. Read/write files, open sockets to remote machines, discover
information about the users environment, etc
– Used in Java Applets to create a “sandbox”. Stops a rogue applet
attacking your machine.
– Makes Java very safe, an important feature in distributed systems
4 Class Loading
– Loading of bytecode into the virtual machine for execution
– Code can be read from a local disk, over a network, or the Internet
– Allows downloading of applications and applets on the fly
– …and even ‘mobile code’
Versions of Java
4 Java Language vs Java Platform
– Current version of the language is 1.4.1
– Core language plus additional APIs is called the Java 2 platform
– Three versions of the Java 2 Platform, targetted at different uses
4 Java 2 Micro Edition (J2ME)
– Very small Java environment for smart cards, pages, phones, and
set-top boxes
– Subset of the standard Java libraries aimed at limited size and
processing power
4 Java 2 Standard Edition (J2SE)
– The basic platform, which this course will cover
4 Java 2 Enterprise Edition (J2EE)
– For business applications, web services, mission-critical systems
– Transaction processing, databases, distribution, replication
The Java APIs
4 Sun are constantly adding new features and APIs
4 The Core Java API is now very large
– Often difficult to keep up with every change
4 Separate set of extension APIs for specific purposes
– E.g. Telephony, Web applications, Game programming
Java Language
4 C++ -- +++ 4 Architecture Neutral
– Object Oriented 4 Internationalization
– no multiple inheritance – Unicode, 2 byte char
– no operator 4 Garbage Collection
overloading
– No pointer
4 Standardization
– sizeof( int )
4 Secure
4 Packages
4 Thread-safe
4 Network Oriented
4 Exception Handling
– Class loading
Java Virtual Machine
4 The engine that actually executes a Java
program
4 key to many of Java’s features
– portability (Write once, run anywhere)
– efficiency
– security (Sandbox)
4 virtual processor, virtual memory…
4 Used in JDK, JRE, browsers
Java API
4 package java.awt 4 package java.rmi.registry
4 package java.awt.datatransfer 4 package java.rmi.server
4 package java.awt.event 4 package java.security
4 package java.awt.image 4 package java.security.acl
4 package java.beans 4 package java.security.interfaces
4 package java.io 4 package java.sql
4 package java.lang 4 package java.text
4 package java.lang.reflect 4 package java.util
4 package java.math 4 package java.util.zip
4 package java.net
4 package java.rmi
4 package java.rmi.dgc
Application & Applets
4 Application
– standalone programs
– HotJava browser
4 Applet
– a Java program to be included in HTML pages
and executed in a Java-compatible browser.
How Applet Run?
Compile
Java Source Code
Network
Web Browser
Before You go on
4 JDK(Java Development Kit)
4 Java-compatible browser
4 References
– Java Tutorial HTML format
– Java API Documentation
Application 1
class Example{
public static void main (String args[ ]) {
System.out.printIn(“Hello World”);
}
}
public : class의
static: main
JAVA
Println: console I/O method
main(String args[]): mechanism through which the runtime
system passes information to your application
Each String in the array is called a command-line argument
Hello World Application
/**
* The HelloWorldApp class implements an application
that
* simply displays "Hello World!" to the standard output.
*/
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); //Display the
string.
}
}
Compiling
4 JDK:
– UNIX:
• javac HelloWorld.java
– DOS shell (Windows 95/NT):
• javac HelloWorld.java
4 Other Visual Development Tools:
– Maybe, you can find “Compile” button, or etc.
4 Output: HelloWorld.class
Running
4 Run the program using the Java interpreter.
4 JDK
– java HelloWorldApp
4 Other Visual Development Tools:
– Maybe, you can find “Compile” button, or etc.
Variables and Data Types
4 Primitive Type
– char
• 2byte, UNICODE
– boolean
• true or false
4 Reference Type
4 C data types Not supported
– pointer, struct, union
APPLET
4 The “Hello World” Applet
Create a Java Source File
create a file named HelloWorld.java
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawString(“Hello world !” , 50, 25);
}
}
Class java.awt.Graphics
4 Various devices, as well as onto off-screen
images.
4 Component.getGraphics( )
– origin
– clip
– color
– font.
– XOR
repaint( )
4 Another Thread for AWT
4 repaint( )
– may not be called
– final state
4 update( Graphics g)
4 paint( Graphics g)
HW.html(Calling an Applet)
<HTML>
<HEAD>
<TITLE>
A Simple Program
</TITLE>
</HEAD>
<BODY>
<APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25>
</APPLET>
</BODY>
</HTML>
The Life Cycle of an Applet
public class Simple extends Applet {
...
public void init() { . . . }
public void start() { . . . }
public void stop() { . . . }
public void destroy() { . . . }
...
}
Run the Applet
include compiled java file in the HTML file with Browser
support java and with appletviewer of the JDK
in UNIX : appletviewer “html file”
in DOS shell (WIN95/NT)
: appletviewer “html file”
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawString(“Hello world !” , 50, 25);
}
}
여기서 (X,Y) 좌표는 html 문서에서 정의 해준 영역에서의 논리적 좌표 .
Here is the output of my program:
<APPELT CODE=“HelloWorld.class” WIDTH=150 HEIGHT=25>
</APPLET>
</BODY>
</HTML>
Sample Source
Class Count {
public static void main(String args [])
throws java.io.IOException
{
int count = 0;
4 Note
System .out.println(“Input has “ + count + “ chars.”);
+ , This operation automatically coerces the value count to a String.
Arithmetic Operators (2/2)
Operator Use Description
+ + op Indicates a positive value
- - op Arithmetically negates op
Operator Use Description
++ op ++ Increments op by 1; evaluates to value before incrementing
++ ++ op Increments op by 1; evaluates to value after incrementing
-- op -- Description op by 1; evaluates to value before decrementing
-- -- op Description op by 1; evaluates to value after decrementing
Relational and Conditional Operators
Operator Use Returns True if
> op1 > op2 op1 is greater than op2
>= op1 >= op2op1 is greater than or equal to op2
< op1 < op2 op1 is less than to op2
<= op1 <= op2op1 is less than or equal to op2
== op1 == op2op1 and op2 are equal
!= op1 != op2op1 and op2 are not equal
&& op1 && op2op1 and op2 are both true
|| op1 | | op2 either op1 or op2 is true
! ! Op op is false
Bitwise Operators
class classname {
type instance-variable1;
type instance-variable2;
//…
type methodname1(parameter-list) {
// }
• class Box
class Box {
double width;
double height;
double depth;
}
Box
Box mybox = new Box()
mybox
class Box {
double width;
double height;
double depth;
}
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width*mybox.height*mybox.depth;
System.out.println(“volume is “ + vol);
}
}
class Box {
double width;
double height;
double depth;
}
class BoxDemo {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
vol = mybox1.width*mybox1.height*mybox1.depth;
System.out.println(“volume is “ + vol);
vol = mybox2.width*mybox2.height*mybox2.depth;
System.out.println(“volume is “ + vol);
}
}
(1) Box mybox; //
(2) Box mybox = new Box(); //Box.
b1 Width
Height
Depth
b2
Box
class Box {
double width;
double height;
double depth;
void volume() {
System.out.print(“Volume is “);
System.out.println(width * height * depth);
}
}
class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 10;
mybox2.height = 20;
mybox2.depth = 15;
mybox1.volume();
mybox2.volume();
}
}
class Box {
double width;
double height;
double depth;
//.
double volume() {
return width * height * depth;
}
}
class BoxDemo4 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 3;
mybox2.height = 9;
mybox2.depth = 6;
vol = mybox1.volume();
System.out.println(“volume is “ + vol);
vol = mybox2.volume();
System.out.println(“volume is “ + vol);
}
}
int square() //10
{
return 10* 10;
}
int square(int i) // {
return i * i ;
}
int x , y;
x = square(5); //x = 25
x = square(9); //x = 81
y = 2;
x = square(y); //x = 4
4 setDim()
4 class Box {
double width;
double height;
double depth;
//
double volume() {
return width * height * depth;
}
void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
}
class BoxDemo5 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
vol = mybox1.volume();
System.out.println(“volume is “ + vol);
vol = mybox2.volume();
System.out.println(“volume is “ + vol);
}
}
(Constructors)
class Box {
double width;
double height;
double depth;
Box() { // System.out.println(“Constructing
Box”);
width = 10;
height = 10;
depth = 10;
}
double volume() {
return width * height * depth;
}
}
.
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) { //
width = 10;
height = 10;
depth = 10;
}
double volume() {
return width * height * depth;
}
}
this keyword
4 Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
4 (Hiding)
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
finalize()
System.out.println(“Stack in mystack1:”);
for(int i=0;i<10; i++)
System.out.println(mystack1.pop());
System.out.println(“Stack in mystack2:”);
for(int i=0;i<10; i++)
System.out.println(mystack2.pop());
}
}
Class OverloadDemo { // Page. 216-7
void test() {
System.out.println(“No parameters”);
}
void test(int a) {
System.out.println(“a: ” + a);
}
void test(int a, int b) {
System.out.println(“a and b: ” + a + “ “ + b);
}
double test(double a) {
System.out.println(“double a: ” + a);
return a*a;
}
}
• test( )
Class Box { // Page. 221-2
double width;
double height;
double depth;
class CallByValue {
public static void main (String args[]) {
Test ob = new Test();
int a = 15, b = 20;
ob.meth(a, b);
System.out.println(“a and b after call: “ + a + “ “ + b);
}
}
//. (Call-By-Reference) Page. 227-8
class Test {
int a, b;
Test(int I, int j) { •Result
a = I; ob.a and ob.b before call: 15 20
b = j;
}
ob.a and ob.b after call: 30 10
void meth(Test o) {
o.a *=2;
o.b /=2;
}
}
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
ob2 = ob1.incrByTen();
System.out.println(“ob1.a: “ + ob1.a);
System.out.println(“ob2.a: “ + ob2.a);
ob2 = ob2.incrByTen();
System.out.println(“ob2.a after second increase: “ + ob2.a);
}
}
(Recursion)
4 Java.
class AccessTest {
public static void main(String args[]) {
Test ob = new Test();
ob.a = 10;
ob.b = 20;
// ob.c = 100; // error !!!
ob.setc(100); // OK
System.out.println(“a, b, and c: “ + ob.a + “ “ + ob.b + “ “ + ob.getc());
}
}
class UseStatic { // Page. 238-9
static int a = 3;
static int b; Result
static void meth(int x) {
Static block initialized
System.out.println(“x = “ + x); x = 42
System.out.println(“a = “ + a); a=3
System.out.println(“b = “ + b); b = 12
}
static {
System.out.println(“Static block initialized.”);
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}
– Static
– classname.method()
System.out.println(“length of a1 is “ + a1.length);
System.out.println(“length of a2 is “ + a2.length);
System.out.println(“length of a3 is “ + a3.length);
}
} Result
length of a1 is 10
length of a1 is 8
length of a1 is 4
String
FixedStack(int size) {
stck = new int[size];
tos = -1;
}
DynStack(int size) {
stck = new int[size];
tos = -1;
}
}
}
class IFTest2 {
public void main (String args[]) {
DynStack mystack1 = new DynStack(5);
DynStack mystack2 = new DynStack(8);
}
}
class IFTest3 {
public static void main(String args[]) {
IntStack mystack; //
DynStack ds = new DynStack(5);
FixedStack fs = new FixedStack(8);
mystack = ds; //
for (int i=0; i<12; i++) mystack.push(i);
mystack = fs; //
for (int i=0; i<8; i++) mystack.push(i);
mystack = ds;
System.out.println(“Values in dynamic stack:”);
for (int i=0; i<12; i++) System.out.println(mystack.pop());
mystack = fs;
System.out.println(“Values in fixed stack:”);
for (int i=0; i<8; i++) System.out.println(mystack.pop());
}
}
4 Interface extends interface
interface A {
void meth1();
void meth2();
}
interface B extends A {
void meth3();
}
Inheritance
8
4 class A { //p. 252
int i, j;
void showij() {
System.out.println(“I and j: ” +1 “ ” +j):
}
}
class B extends A {
int k;
void showk() {
System.out.println(“k: ” +k);
}
class subclass-name extends superclass-name {
//
}
class A { //p.255
int i; //
private int j; //.
void setij( int x, int y) {
i = x;
j = y;
}
}
class B extends A { // A
int total;
void sum() {
total = i + j;//
}
}
P.256-7
class Box { Box() {
width = -1;
double width; height = -1;
double height; depth = -1;
}
double depth; Box(double len) {
Box(Box ob) { width = height = depth = len;
width = ob.width; }
height = ob.heoght; double volume() {
return width * height * depth;
depth = ob.depth; }
} }
Box(double w, double h, double d) {
class BoxWeight extends Box {
width = w; double weight;
height = h; BoxWeight(double w, double h, double d,
depth = d; double m) {
} width = w;
height = h;
depth = d;
weight = m;
}
}
super
4 Super
4 class A { //p.265-6
int i;
}
class B extends A {
int i
B(int a, int b) {
super.i = a; //
i = b; //
}
void show() {
System.out.println("i in superclass: " +super.i);
System.out.println("i in subclass: " + i);
}
}
class A{ //p.271-2
A() {
class A System.out.println(“Inside A’s constructor.”);
}
}
class B extends A{
B() {
System.out.println(“Inside B’s constructor.”);
class B }
}
class C extends B{
C() {
System.out.println(“Inside C’s constructor.”);
class C }
}
class Callingcons {
public static void main(String arg[]) {
C c = new C();
}
}
class A{ //p.272-3
int i,j;
A() {int a, int b) {
i = a;
j=b
}
void show() {
System.out.println(“i and j: “ +i + “ “+j);
}
}
class B extends A{
int k
B() {int a, int b, int c) {
super(a,b);
k = c;
}
void show() {
System.out.println(“k: “ + k);
}
}
class Override {
public static void main(String arg[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // B show() .
}
}
class Figure { //p279-80
double dim1;
double dim2;
Figure(double a, doube b) {
dim1 = a;
dim2 = b;
}
double area() {
System.out.println(" Area for Figure is undefined.");
return 0;
}
}
class Rectangle extends Figure {
Rectangle(double a, doube b) {
super(a,b);
}
double area() {
System.out.println(" Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
figure(double a, doube b) {
super(a,b);
}
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
(cont’d)
t.setName("My Thread"); //
System.out.println("After name change: "+t);
try {
for (int n=5; n>0; n--) {
System.out.println(n);
Thread.sleep(1000); //1
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
}
}
/* : Runnable Interface Implementation */
NewThread() {
t = new Thread(tgOb, this, name);
System.out.println(”Child thread: "+t);
t.start(); //
}
try {
for (int i=5; i>0; i--) {
System.out.println("main thread: "+i);
Thread.sleep(1000); //
}
} catch (InterruptedException e) {
System.out.println("main thread interrupted");
}
}
}
*
class NewThread extends Thread { //
NewThread() {
super("Demo Thread");
System.out.println("Child thread: "+this);
start();
}
public void run() {
try {
for (int i=5; i>0; i--) {
System.out.println("Child thread: "+i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
/*: isAlive() join()
class DemoJoin {
public static void main(String args[]) {
NewThread ob1 = new NewThread("one");
NewThread ob2 = new NewThread("two");
NewThread ob3 = new NewThread("three");
System.out.println("Thread One is alive: " + ob1.t.isAlive());
System.out.println("Thread Two is alive: " + ob2.t.isAlive());
System.out.println("Thread Three is alive: " + ob3.t.isAlive());
try {
System.out.println("Waiting for threads to finish.");
ob1.t.join(); // ob1
ob2.t.join(); // ob2
ob3.t.join(); // ob3
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Thread One is alive: " + ob1.t.isAlive());
System.out.println("Thread Two is alive: " + ob2.t.isAlive());
System.out.println("Thread Three is alive: " + ob3.t.isAlive());
try {
Thread.sleep(1000);
ob1.t.suspend(); // ob1
System.out.println("Suspending thread One.");
Thread.sleep(1000);
ob1.t.resume(); // ob1
System.out.println("Resuming thread One.");
ob2.t.suspend(); // ob2
System.out.println("Suspending thread Two.");
Thread.sleep(1000);
ob2.t.resume(); // ob2 t
System.out.println("Resuming thread Two.");
} catch (InterruptedException e) {
System.out.println("Main Thread Interrupted.");
}
// }
}
class Callme {
void call(String msg) {
System.out.print("["+msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e){
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch (InterruptedException e){
System.out.println("Interrupted");
}
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
Producer (Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) q.put(i++);
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "consumer").start();
}
try {
Thread.sleep(100); //
}
catch (Exception e) {
System.out.println("A interrupted");
}
void last() {
System.out.println("Inside A.last");
}
}
class B {
synchronized void bar(A a) {
String name = Thread.currentThread().getName();
try {
Thread.sleep(1000); //
} catch (Exception e) {
System.out.println("B interrupted");
}
Deadlock() {
Thread.currentThread().setName("MainThread");
Thread t = new Thread(this, "RacingThread");
t.start();
a.foo(b);
System.out.println("Back in main thread");
}
12
•read()
import java.io.*; /page.394
class UseRead() {
public static void main(String args[])
throw IOException
{
char c;
System.out.println(“Enter characters, ‘q’ to quit.”);
Result
do {
Enter characters, ‘q’ to quit.
c = (char) System.in.read();
123abcq
System.out.println(c);
1
} while(c !=‘q’); 2
} 3
a
} b
c
q
import java.io.*; //page.395
class ShowFile {
public static void main(String args[])
throws IOException
{
int I;
do {
I = System.in.read();
System.out.print((char) I);
} while(I != -1);
}
}
Show File
: java ShowFile < TEST.TXT
readline
4 final String readLine() throws IOException
import java.io.*; //page.396
class ReadLine {
public static void main(String args[])
throws IOException
{
DataInputStream inData = new DataInputStream(System.in);
String str;
System.out.println("Enter lines if text.");
System.out.println("Enter ’stop' to quit.");
do {
str = inData.readLine();
System.out.println(str);
} while(!str.equals("stop")); Stop
}
}
4 print(), println()
– PrintStream
– PrintStream OutputStream
• write()
class WriteDemo { //page.389
public static void main(String args[])
int b;
b = ‘A’; Result
System.out.write(b); A
System.out.write(‘\n’);
}
}
4 FileInputStream, FileoutputStream
4 FileInputStream(String fileName) throw FileNotFoundException
4 FileOuputStream (String fileName) throw IOEception
File Name
4 void close() throws IOException
4 int read() throws IOException
(Command Line Argument)
import java.io.*; //page. 400
class ShowFile {
public static void main(String args[]) {
Command Line Argument
throws IOException
{
int i; Java ShowFile TEST.TXT
FileInputStream fin;
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println(“File Not Found”);
return;
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println(“Usage: ShowFile File”);
return;
}
do {
i = fin.read();
if(i != -1)System.out.print((char) i);
} while(i != -1);
fin.close();
}
}
import java.io.*; //page. 400
class Copyfile {
public static void main(String args[]) {
throws IOException
{
int i;
FileInputStream fin;
FileOutputStream fout;
try {
fin = new FileInputStream(args[0]);
fout = new FileOutStream(args[1]);
} catch(FileNotFoundException e) {
System.out.println(“Error Opening Output File”);
return;
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println(“Usage: CopyFile Form To”);
return;
}
try { write()
do {
i = fin.read();
if(i != -1)fout.write(i);
} while(i != -1);
} catch(IOException e) {
System.out.println(“File Error”);
}
fin.close();
fout.close();
}
}
import java.awt.*; //page.403
import java.applet.*;
public class SimpleApplet extends Applet {
public void paint(Graphic g) {
g.drawString(“A Simple Applet”, 20, 20);
}
System.out.println(s1);
System.out.println(s2);
}
}
4 length()
4 prototype : int length()
– Usage * Output
• char chars[] = { 'a', 'b', 'c' }; 3
• String s = new String(chars);
• System.out.println(s.length());
– Example :
• char chars[] = { 'a', 'b', 'c' };
• String s1 = new String(chars);
• String s2 = "abc"; // use string literal
• System.out.println("abc".length()); // 3
* Output
a very long line that would have wrapped around. But string concatenation prevent this.
Continued...
4
• int age = 9;
• String s = "He is " + age + " years old.";
• System.out.println(s); // : He is 9 years old.
Example : substring()
// Substring replacement.
class StringReplace { if(i != -1) {
public static void main(String args[]) { result = org.substring(0, i);
String org = "This is a test. This is, too."; result = result + sub;
String search = "is"; result = result + org.substring(i + search.length());
String sub = "was";
org = result;
String result = "";
}
int i;
} while(i != -1);
do { // replace all matching substrings
}
System.out.println(org);
}
i = org.indexOf(search);
* Output
This is a test. This is, too.
Thwas is a test. This is, too.
Thwas was a test. This is, too.
Thwas was a test. Thwas is, too.
Thwas was a test. Thwas was, too.
Continued...
Example : trim()
// Using trim() to process commands.
import java.io.*; if(str.equals("Illinois"))
class UseTrim { System.out.println("Capital is Springfield.");
public static void main(String args[]) else if(str.equals("Missouri"))
throws IOException System.out.println("Capital is Jefferson City.");
{ else if(str.equals("California"))
// create a DataInputStream using System.in System.out.println("Capital is Sacramento.");
DataInputStream inData = else if(str.equals("Washington"))
new DataInputStream(System.in);
String str; System.out.println("Capital is Olympia.");
System.out.println("Enter 'stop' to quit."); // ...
System.out.println("Enter State: "); } while(!str.equals("stop"));
do { }
str = inData.readLine(); }
str = str.trim(); // remove whitespace
valueOf()
static String value Of (double num)
static String valueOf (long num)
static String valueOf (Object ob)
static String valueOf (char chars[])
static String valueOf (char chars[], int startIndex, int numChars)
toLowerCase() :
toUpperCase() :
Example
// Demonstrate toUpperCase() and toLowerCase().
class ChangeCase { * Output
public static void main(String args[]) Original: This is a test.
{ UpperCase: THIS IS A TEST.
String s = "This is a test."; Lowercase: this is a test.
System.out.println("Original: " + s);
String upper = s.toUpperCase();
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}
StringBuffer
constructor
StringBuffer() //
StringBuffer(int size) //
StringBuffer(String str) // lenght() & capacity()
length() :
capaticy() :
Continued...
append() : StringBuffer.
prototype
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
insert() :
prototype
StringBuffer insert(int index, String str)
StringBuffer insert(int index, Char ch)
StringBuffer insert(int index, Object obj)
reverse()
prototype : StringBuffer reverse()
Continued...
Example : append()
// Demonstrate append().
* Output
class appendDemo {
a = 42!
public static void main(String args[]) {
String s;
int a = 42;
StringBuffer sb = new StringBuffer(40);
s = sb.append("a = ").append(a).append("!").toString();
System.out.println(s);
}
}
Continued...
Example : insert()
// Demonstrate insert().
class insertDemo {
public static void main(String args[]) { * Output
StringBuffer sb = new StringBuffer("I Java!"); I like Java!
Example : insert()
// Using reverse() to reverse a StringBuffer. * Output
class ReverseDemo { abcdef
public static void main(String args[]) { fedcba
StringBuffer s = new StringBuffer("abcdef");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
14 java.lang
Introduction
4 java.lang
Boolean Integer SecurityManager
Character Long String
Class Math StringBuffer
ClassLoader Number System
Compiler Object Thread
Double Process ThreadGroup
Float Runtime Throwable
4 java.lang
4 Cloneable runnable
Continued...
4 Number
– abstract class int, long, float, double
– (Integer, Long, Float, Double)
• abstract double doubleValue() : double
• abstract float floatValue() : float abstract int
intValue() : int abstract long longValue() : long
Continued...
4 Double (double wrapper) & Float (float wrapper)
– Constructor
• Float(double num)
• Float(float num)
• Float(String str) throws
• Double(double num)
• Double(String str) throws NumberFormatException
– method :
– Constant
• MAX_VALUE :
• MIN_VALUE :
• NaN :
• POSITIVE_INFINITY :
• NEGATIVE_INFINITY :
Continued…
F Example ( Double)
* Output
listing 1
3.14159 = 3.14159 -> true
class DoubleDemo {
public static void main(String args[]) {
Double d1 = new Double(3.14159);
Double d2 = new Double("314159E-5");
4 clone()
– Cloneable
– Cloneable clone()
– CloneNotSupportedException.
Continued...
F Example : clone()
listing 12 class CloneDemo {
// Demonstrate the clone() method. public static void main(String args[]) {
class TestClone implements Cloneable { TestClone x1 = new TestClone();
int a; TestClone x2;
double b;
// This method calls Object's clone(). x1.a = 10;
TestClone cloneTest() { x1.b = 20.98;
try {
// call clone in Object. x2 = x1.cloneTest(); // clone x1
return (TestClone) super.clone();
} catch(CloneNotSupportedException e) { System.out.println("x1: " + x1.a + " " + x1.b);
System.out.println("Cloning not allowed."); System.out.println("x2: " + x2.a + " " + x2.b);
return this; }
}
} * Output
} x1: 10 20.98
}
x2: 10 20.98
Continued...
F Example : clone()
listing 13 class CloneDemo2 {
// Override the clone() method. public static void main(String args[]) {
TestClone x1 = new TestClone();
class TestClone implements Cloneable { TestClone x2;
int a;
double b; x1.a = 10;
// clone() is now overriden and is public. x1.b = 20.98;
public Object clone() {
try { // here, clone() is called directly.
// call clone in Object. x2 = (TestClone) x1.clone();
return super.clone();
} catch(CloneNotSupportedException e) { System.out.println("x1: " + x1.a + " " + x1.b);
System.out.println("Cloning not allowed."); System.out.println("x2: " + x2.a + " " + x2.b);
return this; }
} } * Output
} x1: 10 20.98
} x2: 10 20.98
Class & Class Loader
4 Class
Class Object getClass() Class.
– method : 14.11
4 Class Loader
– abstract class.
– applicationClassLoader
Continued...
F Example : getClass() & getSuperClass()
listing 14 class X {
// Demonstrate Run-Time Type Information . int a;
class RTTI { float b;
public static void main(String args[]) {
X x = new X(); }
Y y = new Y();
Class clObj; class Y extends X {
double c;
clObj = x.getClass(); // get Class reference
System.out.println("x is object of type: " + }
clObj.getName());
System.out.println("Capacity after four additions: " + // enumerate the elements in the vector.
v.capacity()); Enumeration vEnum = v.elements();
ht.put(name, number);
changed = true; Oresult
} while(!name.equals("quit"));
Enter new name ('quit' to stop):
// If phone book data has changed, save it. ddd
if(changed) { Enter number:
PrintStream fout = new 33
PrintStream(new FileOutputStream Enter new name ('quit' to stop):
("phonebook.dat")); kkk
Enter number:
ht.save(fout, "Telephone Book"); 44
fout.close(); Enter new name ('quit' to stop):
}
ddd
// Look up numbers given a name. 33
do { Enter name to find ('quit' to quit):
System.out.println("Enter name to find" + lll
" ('quit' to quit): "); null
name = inData.readLine(); Enter name to find ('quit' to quit):
if(name.equals("quit")) continue; quit
number = (String) ht.get(name);
System.out.println(number);
} while(!name.equals("quit"));
}
}
FExample : Demonstrate a StringTokenizer
import java.util.StringTokenizer;
class STDemo {
static String in = "title=Java: The Complete Reference;" +
"author=Naughton and Schildt;" +
"publisher=Osborne/McGraw-Hill;" +
"copyright=1997";
– Date()
– Date(int year,int month,int datOfMonth)
– Date(int year,int dayOfMonth,int hours,int minutes)
– Date(int year,int dayOfMonth,int hours,int minutes,
int seconds)
– year 1900
– month
– dayOfMonth
class DateFormats {
public static void main(String args[]) {
Date curDate = new Date();
– Random()
• seed
– Random(long seed)
• seed
– double nextDouble(), float nextFloat(), int nextInt()
• Double,Float,Int
– setSeed(long newSeed)
• newSeed
– nextGaussian()
import java.util.Random; System.out.println("Average of values: ”
+ (sum/100));
class RandDemo {
public static void main(String args[]) { // display bell curve, sideways
Random r = new Random(); for(int i=0; i<10; i++) {
double val;
for(int x=bell[i]; x>0; x--)
double sum = 0;
int bell[] = new int[10]; System.out.print("*");
System.out.println();
for(int i=0; i<100; i++) { }
val = r.nextGaussian(); C:\java\>java
} RandDemo
sum += val; }Average of values: 0.0552335
double t = -2;
*****
************
for(int x=0; x<10; x++, t += 0.5) ***********
if(val < t) { **********************
bell[x]++; *****************
break; ****************
}
**********
******
}
Example Observerable class ObserverDemo {
public static void main(String args[]) {
import java.util.*; BeingWatched observed =
class Watcher implements Observer { new BeingWatched();
public void update(Observable obj, Object arg) { Watcher observing = new Watcher();
System.out.println("update() called, count is " +
((Integer)arg).intValue()); observed.addObserver(observing);
}
} observed.counter(10);
class BeingWatched extends Observable { }
void counter(int period) { }
for( ; period >=0; period--) {
setChanged(); update() called, count is 10
notifyObservers(new Integer(period)); update() called, count is 9
try { update() called, count is 8
Thread.sleep(100); update() called, count is 7
} catch(InterruptedException e) { update() called, count is 6
System.out.println("Sleep interrupted"); update() called, count is 5
} update() called, count is 4
} update() called, count is 3
} update() called, count is 2
} update() called, count is 1
update() called, count is 0
import java.util.*;
observed.counter(10);
}
}
- java.io
16
Java I/O
4 Java.io I/O
InputStream FileInputStream PushbackInputStream
OutputStream FileOutputStream SequenceInputStream
BufferedInputStream FilterInputStream StringBufferInputStream
BufferedOutputStream FilterOutputStream File
ByteArrayInputStream LineNumberInputStream FileDescriptor
ByteArrayOutputStream PipedInputStream RandomAccessFile
DataInputStream PipedOutputStream StreamTokenizer
DataOutputStream PrintStream
InputStream OutputStream . (File, FileDescriptor,
RandomAccessFile, StreamTokenizer )
Streams
4 Abstraction that either produces or
consumes information
4 Linked to physical device by Java IO
– Byte streams
(Convenient way handling IO of bytes)
– Character streams
(Convenient way handling IO of characters)
ByteStreams
4 Two class hierarchies
– InputStream (An abstract class that defines
Java’s model of streaming byte input)
– OutputStream (An abstract class that defines
Java’s model of streaming byte output)
– Each of them have several concrete classes
CharacterStream classes
4 Two classes hierarchies
4 Reader
4 Writer
File
– File(String directoryPath)
– File(String directoryPath, String filename)
– File(file dirObj, String filename)
4 Methods
– getName()
– getParent() :
– exists() : (true or false)
Result
File Name : COPYRIGHT
Path : /java/COPYRIGHT
import java.io.File;
Abs Path : /java/COPYRIGHT
class FileDemo { Parent : /java
static void p(String s) { exists
System.out.println(s); is writeable
} is readable
public static void main(String args[]) { is not a directory
File f1 = new File(“/java/COPYRIGHT”); is normal file
p(“File Name : “ + f1.getName()); is absolute
p(“Path : “ + f1.getPath());
File last modified: 81246520400
p(“Abs Path: “ + F1.getAbsolutePath());
p(“Parent: “ + f1.getParent()); File size : 695 Bytes
p(f1.exists() ? “exists” : “does not exits”);
p(f1.canWrite() ? “is writeable” : “is not writeable”);
p(f1.canRead() ? “is readable” : “is not readable”);
p(“is “ + (f1.isDirectory() ? “ “ : “not” + “a directory”));
p(f1.isFile() ? “is normal file” : “might be a named pipe”);
p(f1.isAbsolute() ? “is absolute” : “is not absolute”);
p(“File last modified: “ + f1.lastModified());
p(“File size: “ + f1.length() + “ Bytes”);
}
}
Import java.io.File;
class DirList{
public static void main(String args[]) {
String dirname = “/java”;
File f1 = new File(dirname);
if (f1.isDirectory()) {
System.out.println(“Directory of “ + dirname);
String s[] = f1.list();
String[] list() :
for(int I=0 ; I<s.length ; I++) {
File f = new File(dirname + “/” + s[I]);
if (f.isDirectory()) {
System.out.println(s[I] + “ is a directory”);
} else {
System.out.println(s[I] + “ is a file”);
}
}
} else {
System.out.println(dirname + “ is not a directory”);
}
}
}
public OnlyExt(String ext) {
4 FilenameFilter this.ext = “.” + ext;
}
if (f.read(b) != n) {
System.err.println("couldn’t read " + n + " bytes.");
}
System.out.println(new String(b, 0, 0, n));
System.out.println("\nStill Available: " + (size = f.available()));
System.out.println("Skipping half of remaining bytes with skip()");
f.skip(size/2);
System.out.println("Still Available: " + f.available());
System.out.println("Reading " + n/2 + " into the end of array");
if (f.read(b,n/2,n/2) != n/2) {
System.err.println("couldn’t read " + n/2 + " bytes.");
}
System.out.println(new String(b,0,0,b.length));
System.out.println("\nStill Available: " + f.available());
f.close();
}
}
4 FileOutputStream
: FileOutputStream(String filePath)
FileOutputStream(File fileObj)
- OutputStream
import java.io.*;
class FileOutputStreamDemo {
public static void main(String args[]) throws Exception {
String source = "Now is the time for all good men\n"
+ " to come to the aid of their country\n"
+ " and pay their due taxes.";
byte buf[] = new byte[source.length()];
source.getBytes(0, buf.length, buf, 0); FileOutputStream
OutputStream f0 = new FileOutputStream("file1.txt"); FileOutputStream
for (int i=0; i < buf.length; i += 2) {
f0.write(buf[i]);
}
f0.close();
OutputStream f1 = new FileOutputStream("file2.txt");
f1.write(buf);
f1.close();
OutputStream f2 = new FileOutputStream("file3.txt");
f2.write(buf,buf.length-buf.length/4,buf.length/4);
f2.close();
}
}
4 ByteArrayInputStream
: ByteArrayInputStream(byte array[])
ByteArrayInputStream(byte array[], int start, int numbytes)
-
import java.io.*;
class ByteArrayInputStreamDemo {
public static void main(String args[]) throws IOException { ByteArrayInputStream
String tmp = "abcdefghijklmnopqrstuvwxyz";
byte b[] = new byte[tmp.length()];
tmp.getBytes(0, tmp.length(), b, 0);
ByteArrayInputStream input1 = new ByteArrayInputStream(b);
ByteArrayInputStream input2 = new ByteArrayInputStream(b, 0, 3);
}
}
import java.io.*;
reset()
class ByteArrayInputStreamReset {
public static void main(String args[]) throws IOException {
byte b[] = { 'a', 'b', 'c' };
ByteArrayInputStream in = new ByteArrayInputStream(b);
class ByteArrayOutputStreamDemo {
public static void main(String args[]) throws IOException {
ByteArrayOutputStream f = new ByteArrayOutputStream();
String s = "This should end up in the array";
byte buf[] = new byte[s.length()];
• StringBufferInputStream
StringBufferInputStream(String str)
- StringByteArrayInputStream
4BufferedInputStream
: BufferedInputStream(InputStream inputStream)
BufferedInputStream(InputStream
inputStream, int bufSize)
- import java.io.*;
class BufferedInputStreamDemo {
public static void main(String args[]) throws IOException {
String s = "This is a © copyright symbol " +
"but this is © not.\n";
byte buf[] = new byte[s.length()];
s.getBytes(0, s.length(), buf, 0);
ByteArrayInputStream in = new ByteArrayInputStream(buf);
BufferedInputStream f = new BufferedInputStream(in);
int c;
boolean marked = false;
while ((c = f.read()) != -1) {
switch(c) {
case ‘&’ :
if (!marked) {
f.mark(32); 32
marked = true;
} else {
marked = false;
}
break;
case ‘;’ :
if (marked) {
marked = false;
System.out.print("(c)");
} else
System.out.print((char) c);
break;
case ‘ ’ :
if (marked) {
marked = false;
f.reset();
System.out.print("&");
} else
System.out.print((char) c);
break;
default:
if (!marked)
System.out.print((char) c);
break;
}
}
}
}
4BufferedOutputStream
: BufferedOutputStream(OutputStream outputStream)
BufferedOutputStream(OutputStream
outputStream, int bufSize)
- BufferedOutputStream flush() OutputStream
4PushbackInputStream
.
import java.io.*;
class PushbackInputStreamDemo {
public static void main(String args[]) throws IOException {
String s = "if (a == 4) a = 0;\n";
byte buf[] = new byte[s.length()];
s.getBytes(0, s.length(), buf, 0);
ByteArrayInputStream in = new ByteArrayInputStream(buf);
PushbackInputStream f = new PushbackInputStream(in);
int c;
while ((c = f.read()) != -1) {
switch(c) {
case '=':
if ((c = f.read()) == '=')
System.out.print(".eq.");
else {
System.out.print("<-");
f.unread(c);
}
break;
default:
System.out.print((char) c);
break;
}
}
}
}
4 SequenceInputStream
: SequenceInputStream(InputStream first, InputStream second)
SequenceInputStream(Enumeration streamEnum)
InputStream.
import java.io.*;
import java.util.*;
class InputStreamEnumerator implements Enumeration {
private Enumeration files;
public InputStreamEnumerator(Vector files) {
this.files = files.elements();
}
public boolean hasMoreElements() {
return files.hasMoreElements();
}
public Object nextElement() {
try {
return new FileInputStream(files.nextElement().toString());
} catch (Exception e) {
return null;
}
}
}
class SequenceInputStreamDemo {
public static void main(String args[]) throws Exception {
int c;
Vector files = new Vector();
files.addElement("/autoexec.bat");
files.addElement("/config.sys");
InputStreamEnumerator e = new InputStreamEnumerator(files);
InputStream input = new SequenceInputStream(e);
while ((c = input.read()) != -1) {
System.out.print((char) c);
}
input.close();
}
}
4PrintStream
: PrintStream(OutputStream outputStream)
PrintStream(OutputStream outputStream, boolean
flushOnNewline)
- System System.out
- flushOnNewline : ‘\n’
4RandomAccessFile
: RandomAccessFile(File fileObj, String access)
RandomAccessFile(String filename, String access)
- Method : void seek(long newPos) //
import java.io.*;
class WordCount {
public static int words=0;
public static int lines=0;
public static int chars=0;
public static void wc(InputStream f) throws IOException {
int c=0;
boolean lastNotWhite=false;
String whiteSpace = " \t\n\r";
while ((c = f.read()) != -1) {
chars++;
if (c == '\n') {
lines++;
}
if (whiteSpace.indexOf(c) != -1) {
if (lastNotWhite) {
words++;
}
lastNotWhite = false;
} else {
lastNotWhite = true;
}
}
}
public static void main(String args[]) {
FileInputStream f;
try {
if (args.length == 0) { // We're working with stdin
wc(System.in);
} else { // We're working with a list of files
for (int i=0; i < args.length; i++) {
f = new FileInputStream(args[i]);
wc(f);
}
}
} catch (IOException e) { wc(Word Count) :.
return;
}
System.out.println(lines + " " + words + " " + chars);
}
}
4 wc()
public static void wc(InputStream f) throws IOException {
int c=0;
PushbackInputStream pbf = new PushbackInputStream(f);
String whiteSpace = " \t\n\r";