Sie sind auf Seite 1von 31

Java Tutorial for Beginners

http://www.personal.psu.edu/kxt179/teaching/index.html 1 Introduction to Java Programming.............................................................................. 3 1.1 What is Java? ...................................................................................................... 3 1.2 Features of Java Programming Language ........................................................... 3 1.3 Why Java? ........................................................................................................... 3 1.4 Different Types of Java Programs ...................................................................... 3 1.5 Getting stated with Java Programming ............................................................... 4 2 Important Java Concepts ............................................................................................. 6 2.1 Object .................................................................................................................. 6 2.2 Message ............................................................................................................... 6 2.3 Class.................................................................................................................... 7 2.4 Inheritance........................................................................................................... 7 2.5 Interface .............................................................................................................. 8 2.6 Package ............................................................................................................... 8 3 Java Language Basics ............................................................................................... 10 3.1 Statements and Expressions .............................................................................. 10 3.2 Variables and Data Types ................................................................................. 10 3.3 Expressions and Operators................................................................................ 11 3.4 String Arithmetic ............................................................................................... 12 3.5 Modifiers ........................................................................................................... 12 3.6 Conditional Statement....................................................................................... 12 3.6.1 if conditional statement ............................................................................. 12 3.6.2 switch Conditional Statement ................................................................... 12 3.7 Loop statement .................................................................................................. 13 3.7.1 for Loops ................................................................................................ 13 3.7.2 while and do Loops................................................................................... 13 3.7.3 Breaking Out of Loops.............................................................................. 14 4 Working with Objects ............................................................................................... 16 4.1 Package ............................................................................................................. 16 4.1.1 Defining package ...................................................................................... 16 4.1.2 Using package ........................................................................................... 16 4.2 Class.................................................................................................................. 16 4.2.1 Defining classes ........................................................................................ 16 4.2.2 Defining variables..................................................................................... 16 4.2.3 Defining methods ...................................................................................... 16 4.2.4 Java access specifiers................................................................................ 17 4.3 Inheritance......................................................................................................... 17 4.4 Interface ............................................................................................................ 17 4.5 Creating New Objects ....................................................................................... 18 4.6 Accessing and Setting Class and Instance Variables ........................................ 19 4.7 Calling Methods ................................................................................................ 19 4.8 References to Objects........................................................................................ 20 4.9 Casting and Converting Objects and Primitive Types ...................................... 20 4.10 Comparing Objects ........................................................................................... 21 IE582 Spring-2004 1

4.11 The Java Class Library...................................................................................... 21 Array and Container Objects..................................................................................... 22 5.1 Array Objects .................................................................................................... 22 5.1.1 Arrays in Java ............................................................................................ 22 5.1.2 Declaring Array Variables ........................................................................ 22 5.1.3 Creating Array Objects ............................................................................. 22 5.1.4 Accessing Array Element s ........................................................................ 22 5.1.5 Changing Array Elements ......................................................................... 22 5.2 Container Objects.............................................................................................. 23 5.2.1 Container taxonomy.................................................................................. 23 5.2.2 Some Useful Container Objects ................................................................ 23 5.2.3 More on LinkedList .................................................................................. 23 Input and Output ....................................................................................................... 25 6.1 Stream? .............................................................................................................. 25 6.2 Character Streams and Byte Streams ................................................................ 25 6.3 Reading Console Input...................................................................................... 26 6.4 Writing Console Output .................................................................................... 27 6.5 Reading and Writing Files ................................................................................ 27 6.6 Parsing String Input using Tokenizers .............................................................. 27 Java Application........................................................................................................ 29 7.1 Creating Java Applications ............................................................................... 29 7.2 Java Applications and Command-Line Arguments .......................................... 29 What you need for (serious) Java Programming....................................................... 31 8.1 Buy a Java book (or use online tutorials).......................................................... 31 8.2 Use (hyperlinked) Java APT specification........................................................ 31 8.3 Use RAD Tools (especially for GUI programming) if possible ....................... 31 8.4 * Some (possibly) important, but not covered topics ....................................... 31

IE582 Spring-2004

Java Tutorial for Beginners


Kaizhi Tang

1 Introduction to Java Programming


1.1 What is Java?
l l Java is a Programming Language: Full- fledged general-purpose programming language, especially object-oriented programming Java is a Platform: Java Virtual Machine (JVM) and Java API (Application Programming Interface)

1.2 Features of Java Programming Language


l Platform Independent: n n l l n n l l Java program can run on any computer system for which a JVM has been installed Java bytecode / Compiler / Interpreter Java is a pure object oriented programming langauge Similar to C and C++, but most of more complex parts of them have been excluded

Object Oriented Easy to Learn

Performance n Exception handling mechanism Robust n Interpreted but still high performance (using Just In Time Compiler technology) And, Network-Savvy, Secure, Multi-threaded, Dynamic, etc.

1.3 Why Java?


l l l Shorten development time n Easy to use, Automatic garbage collection, using the third party s APIs Shorten deployment time n Platform independent Solve complicated problem

1.4 Different Types of Java Programs


l l l l Console Application: Run in command line (*) Applet: Run in the browser (IE or Netscape) Servlet: Run in the Java Servlet container (Jakarta Tomcat) Beans: component strategy in Java, especially in J2EE

IE582 Spring-2004

1.5 Getting stated with Java Programming


l Getting a Java Development Environment (JDK) and documentation n n l l l n Go to the JavaSoft Web site (http://java.sun.com/j2se/1.4.2/download.html) Download SDK, JRE and documentation For example: C:\ j2sdk1.4.2

Install the JDK Unzip the documentation: C:\ j2sdk1.4.2\docs Creating a Java Application n Creating the Source File: u using text editors u file name extension: .java u file name = class name (example: HelloWorld.javafor class HelloWorld ) class HelloWorld { public static void main(String[] args){ System.out.println("Hello World!"); } }

Compiling and Running the Source File u javac HelloWorld.java ( bytecode: HelloWorld .class) u java HelloWorld Creating the Source 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); } } }

Creating a Java Applet n

Compiling and Running the Source File

IE582 Spring-2004

Including the Applet in a Web page (Only for Netscape, IE is different) <HTML> <HEAD> <TITLE> A Simple Program </TITLE> </HEAD> <BODY> Here is the output of my program: <APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25> </APPLET> </BODY> </HTML>

Execution Web browser or appletviewer

IE582 Spring-2004

2 Important Java Concepts


2.1 Object
l Two characteristics of real-world objects: states and behaviors Dogs: state (name, color, breed, hungry) and behavior (barking, fetching, and wagging tail)


l l

Bicycles: state (current gear, current pedal cadence, two wheels, number of gears) and behavior (braking, accelerating, slowing down, changing gears) Software objects to model real-world objects: variables and methods Definition : An object is a software bundle of variables and related methods

Encapsulation: package an object s variable within the protective custody of its method => methods restrict and protect the variable access in an object l Benefit of Encapsulation n Modularity: write and maintain source code of other objects independently n Information hiding: only public method can communicate with other objects

2.2 Message
Software objects interact and communicate with each other by sending messages to each other Objects will update states or send messages to other objects in the system

Benefits o Message parsing support all possible interactions between objects o Objects don t need to be in the same processor or even on the same machine => distributed computing is easy in Java Java Program = Objects + Message interactions

IE582 Spring-2004

2.3 Class
l Definition: A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind. o All the bicycles share the same characteristics and they can be defined as one class A class is an abstract of a group of objects

2.4 Inheritance

IE582 Spring-2004

Subclasses: Mountain Bike, Racing Bike, Tandem Bike Superclass: Bicycle The class variables and methods in the subclasses are the subsets of those in the superclass o Mountain bikes, racing bikes, and tandems share some states: cadence, speed, and the like. Also, each subclass inherits methods from the superclass. Mountain bikes, racing bikes, and tandems share some behaviors: braking and changing pedaling speed o Tandem bicycles have two seats and two sets of handle bars; some mountain bikes have an extra set of gears with a lower gear ratio Subclass can overrides some methods in the superclass o For example, if you had a mountain bike with an extra set of gears, you would override the "change gears" method so that the rider could use those new gears. Benefits: o Reuse the code in the superclass many times o Programmers can implement superclasses called abstract classes that define "generic" behaviors . The abstract superclass defines and may partially implement the behavior, but much of the class is undefined and unimplemented. Other programmers fill in the details with specialized subclasses

2.5 Interface
Definition : a device that unrelated objects use to interact with each other o Analogous to a protocol (an agreed on behavior) Example: Inventory Interface o Bicycle class hierarchy defines different bicycle classes o They needs to be used in an inventory program o Inventory program only needs to know tracking numbers and retail prices o An inventory interface is defined to connect bicycles and the inventory programs o This interface can also be used by other class that needs to be used in the inventory program Benefits o Capturing similarities among unrelated classes without artificially forcing a class relationship (inheritance) o Declaring methods that one or more classes are expected to implement o Revealing an object's programming interface without revealing its class

2.6 Package
Definitions : a collection of classes Without explicit declaration, access to the classes in a package is not allowed o import java.io.*;

IE582 Spring-2004

Benefits o Easy to manage large projects o Set access barrier between different groups of classes

IE582 Spring-2004

3 Java Language Basics


3.1 Statements and Expressions
Statement : forms a single Java operation. They must end with semi-colons(;). Example:
int i = 1; import java.awt.Font; System.out.println("This car is a "+ color + " " + make); m.engineState = true;

Expressions : statements which return values Block: compound statements. They are surrounded by braces({}).

3.2 Variables and Data Types


Declaring Variables Variable definition can go anywhere in a method definition Instance variables vs. Class variables Example:
String firstName; // instance variable static String lastName; // class variable

Initializing: Example:
String myName = "Yong-Han";

Finalizing: (constant) Example:


final String myName = "Kumara";

Variable Names Example:


int _number, $money, 5five // O.K button theButton; // By convention, Java variables long reallyBigNumber; // have meaningful names, often boolean currentWeatherState; // are made up of several // words combined.

Variable Types Primitive types:


Category Integer Type byte short Size / Format 8-bit two's complement 16-bit two's complement Description Byte-length integer Short integer

IE582 Spring-2004

10

int long float Real Number double char Other Types boolean

32-bit two's complement 64-bit two's complement 32-bit IEEE 754 64-bit IEEE 754 16-bit Unicode character true or false

Integer Long integer Single -precision floating point Double-precision floating point A single character A boolean (true or false) value

Class types: variables in Java can also be declared to hold an instance of a particular class. These variables can hold instances of the named class or of any of its subclasses. Example:
String myName; Object theObject;//this variable can hold any object.

Assigning Values to Variables: using operator = .


Example:
myName = "Mahima" ; x = y = z = 0; x += y; // x = x + y x -= y; // x = x - y x *= y; // x = x * y x /= y; // x = x / y

Comments: /* and */ // /** and */

used by the javadoc system to generate API documents

Literals Example:
Number Literals: -45, 4L, 0777, 0XFF, 2.56F, 10e45, .36E-2, .. Boolean Literals: true, false Character Literals: 'a', '#', '3', \n, \\, \", .. String Literals: "A string with a \t tab in it.", ..

3.3 Expressions and Operators


Arithmetic : +, -, *, /, % (modulus operator) Incrementing and Decrementing Example:
y = x++; // y = x; x = x + 1; y = ++x; // x = x + 1; y = x;

Comparisons : ==, !=, <, >, <=, >= 11

IE582 Spring-2004

Logical operators: &, &&, |, ||, ^, !

3.4 String Arithmetic


Additional operator (+) to create and concatenate strings. Example:
System.out.println(name + " is a " + color + " beetle"); myName += " Jr."; // myName = myName + " Jr.";

3.5 Modifiers
Modifiers are special keywords that modify the definition of a class, method, or variable. Access Control: public, protected, private Making class methods, variables: static Finalizing: final Others: abstract, synchronized, volatile, native

3.6 Conditional Statement


3.6.1 if conditional statement
if (expression) statement if (expression) statement-1 else statement-2

,or

The conditional expression returns boolean value (true or false) Example:


if (engineState == true) System.out.println("The engine is already on."); else { engineState = true; System.out.println("The engine is now on."); }

3.6.2 switch Conditional Statement


When the result of a test can be represented by byte, char, short, or int. Example:
int month; int numDays; . . .

IE582 Spring-2004

12

switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numDays = 31; break; case 4: case 6: case 9: case 11: numDays = 30; break; case 2: if (((year%4 == 0) && !(year%100 == 0)) || (year%400 == 0)) numDays = 29; else numDays = 28; break;

} // end of switch (month)

3.7 Loop statement


3.7.1 for Loops
for (initialization; test; increment) statement;

Example: String strArray[] = new String[10]; int i; for (i = 0; i < strArray.length; i++) strArray[i]= a ;

3.7.2 while and do Loops


To repeat a statement or block of statements as long as particular condition is true .

while (condition) { bodyOfLoop; } // check the condition before the body of loop

Example:

IE582 Spring-2004

13

int x = 1; while (x <= 10) { System.out.println(looping, round + x); x++; }

do { // check the condition after the body of loop bodyOfLoop; } while (condition);

Example:
int x = 1; do { System.out.println(looping, round + x); x++; } while (x <= 10)

3.7.3 Breaking Out of Loops


break: when used in a loop, it immediately halts execution of the current loop. Example:
// Loop to copy elements from array1 into array2 // until the end of array1 or until a 0 is reached. int count = 0; while (count < array1.length) { if (array1[count] == 0) { break; } array2[count] = array1[count++]; }

continue: when used in a loop, it immediately skip the current iteration, and the loop starts over at the next iteration. Example:
//Loop to copy non-zero elements from array1 into array2 // until the end of the array1. (by skipping zero-elements) int count1 = 0; int count2 = 0; while (count < array1.length) { if (array1[count] == 0) { continue; count1++; } array2[count2++] = array1[count1++]; }

Labeled loops : let the program break to specific points outside nested loops or continue a loop outside the current loop.

IE582 Spring-2004

14

Example:
// When the condition (i * x == 400), the break causes // the execution to break out of both loops (for and // while) and continue executing any code after both loops. out: // a label for (int i = 0; i < 10; I++) { while (x < 50) { if (i * x == 400) break out; ... } ... }

IE582 Spring-2004

15

4 Working with Objects


4.1 Package
4.1.1 Defining package
Put package name at the beginning of a java file Example:
//Bicycle.java package myapp.test;

The directory structure has to be the same as the package organization Example:
Bicycle.java has to be in the directory of .\ myapp\test\Bicyle.java

If no explicit package, default package uses the current directory

4.1.2 Using package


Classes from packages other than java.lang must be explicitly import ed or refereed to by full package name. (* Packages do not limit the inheritance, i.e. a class can be inherited from a class in other packages) Example: import java.awt.Graphics; import java.awt.Font; import java.awt.*;
import myapp.util.*; // The directory .\myapp\util needs to be set in the // classpath of the system variable public class .. { Font f; // java.awt.Font f;

...

4.2 Class
4.2.1 Defining classes
Java access specifiers + class+ class name + variables + methods

4.2.2 Defining variables


Java access specifiers + Type (Class) + variable name

4.2.3 Defining methods


Java access specifiers + return type(class) + method name + parameter list Example:
//Bicycle.java

IE582 Spring-2004

16

public class Bicycle{ double currentSpeed; int currentCadence; int numberOfGears; int currentGear; public void brake(); public void changeCadence(int cadence); public void changeGear(int gear); }

4.2.4 Java access specifiers


Friendly(no specifier): public to the same package and private to other packages public: everybody, everywhere can access it protected: only inheriting classes can access it private: only the class itself can access it

4.3 Inheritance
Use keyword extends Example:
//MountainBicycle.java class MountainBicycle extends Bicycle{ public void climbUp(); public void quickDown(); }

The friendly members in the same package can be accessed by subclasses

4.4 Interface
Use keyword interfaceto define an Interface Example:
//Inventory.java

Use keyword implementsto agree the interface //Bicycle.java will be modified in the following way
public class Bicycle implements Intentory{ double currentSpeed; int currentCadence; int numberOfGears; int currentGear; public void brake(); public void changeCadence(int cadence); public void changeGear(int gear); //implements the following methods

IE582 Spring-2004

17

void setRetailPrice(int price);


}

All the methods defined in the interface needs to be implemented

4.5 Creating New Objects


Using new To create a new object, use the new operator with the name of the class (exception for String object creation using string literal). Example:
String str = new String(); Random r = new Random(); Tree t = new Tree();

The number and type of arguments are defined by the special method constructor. Example:
Date d1 = d2 = d3 = d1, new new new d2, d3; // class in the java.util package Date(); // current time Date(98, 8, 22, 18, 0); // 1998 Sep. 22, 6:00 pm Date(September 22 1998 6:00 PM);

constructors: special methods that initialize a new object, set its variables, create any other objects that object needs, and generally perform any other operations the object needs to initialize itself.

What new Does New instance of the given class is created. Memory is allocated. The constructor method is called. Example:
public class Car { String make = Nissan; String color = red; boolean engineState = false; Car() { System.out.println(a Car object created); } Car(String mk, String cl) { this(); make = mk; color = cl;

IE582 Spring-2004

18

} Car(String mk, String cl, boolean es) { this(mk,cl); engineState = es; } }

4.6 Accessing and Setting Class and Instance Variables


use dot notation. Eexample:
myCar.make, myCar.color

Changing values Example:


myCar.engineState = true;

Class Variables : variables that are defined and stored in the class itself (static keyword), only one copy of the variable exists among all its instantiations.

4.7 Calling Methods


use dot notation Example:
myCar.startEngine(); myCar.changeColor(blue); theMake = myCar.getColor();

More complicated example:


public class Car { Engine engine; ... Engine GetEngine(){ Return engine; } ... } public class Engine { long CC; ... void getCC(){ Return CC; } ... } long theCC = myCar.GetEngine().getCC(); long theCC = myCar.GetEngine().CC; // // They are all

IE582 Spring-2004

19

long theCC = myCar.engine.getCC(); long theCC = myCar.engine.CC;

// the same. //

Class methods: method that can be called without any instantiation of its class. Example:
int biggerOne = Math.max(x, y); // We dont need to create an object of class Math at all!

4.8 References to Objects


Assigning objects to variables and passing objects as arguments to methods passing references to those objects, not the objects themselves or copies of those objects. Example:
Point pt1 = pt2 = pt1.x pt1, pt2; // create two variables for class Point new Point(100,100); Point pt1; pt1 = pt1.y =150; x:

pt2

150 y:

4.9 Casting and Converting Objects and Primitive Types


Casting: converts the value of an object or primitive type into another type. Casting Primitive Types: (typename) value Example:
i = (int) (x / y); // x and y are floats, i is an integer.

Casting Objects: (classname) object The class and the object must be related by inheritance. Apple GreenAppl Example:
Apple a = new Apple(); GreenApple aGreen = new GreenApple(); a = aGreen; // no casting needed aGreen = (GreenApple)a; // casting needed

Converting Primitive Types to Object and Vice Versa direct casting not allowed! Use constructors and special methods in the classes. Example:
Integer intObject = new Integer(35); int theInt = intObject.intValue(); // return 35

IE582 Spring-2004

20

4.10 Comparing Objects


Cannot use the comparison operators except == and !=, which just test whether the two operands refer to exactly the same object in memory. Instead, in order to compare the contents of objects, you have to implement special methods in your class, and use them. Example:
boolean equalOrNot = myString.equals(yourString); // equals() method was implemented in String class.

4.11 The Java Class Library


Standard Java packages support a huge set of classes that are guaranteed to be available in any commercial Java environment. Those classes are in the java and javax package including: java.lang.* Classes that apply to the language itself, including the Object class, the String class, and the System class. It also contains the special classes fo r the primitive types (Integer , Character, Float, and so on). java.util.* Utility classes, such as Data, as well as simple collection classes, such as Vector and Hashtable . java.io.* Input and output classes for writing to and reading from streams (such as standard input and output) and for handling files. java.net.* Classes for networking support, including Socket and URL (a class to represent references to documents on the WWW). java.awt.* This is the Abstract Windowing Toolkit. It contains classes to implement graphical user interface features, including classes for Window, menu, Button, Font, CheckBox, and so on. It also includes mechanisms for managing system events and for processing images (in the java.awt.Image package). java.applet.* Classes to implement Java applets. And a lot more: javax.swing.*, java.bean.*, java.math.*, java.rmi.*, java.security.*, java.sql.*, java.text.*, ...

Reference URL: http://javasoft.com/products

IE582 Spring-2004

21

5 Array and Container Objects


5.1 Array Objects
5.1.1 Arrays in Java
Each slot in the array can hold an object or a primitive value. Arrays in Java are objects. Steps to create an array in Java: Declare a variable to hold the array. Create a new array object and assign it to the array variable. Store things in that array. An array of objects in Java is an array of references to those objects!

5.1.2 Declaring Array Variables


Use empty brackets ([]). Example:
String studentNames[]; String[] studentNames; Point centerPts[]; Point[] centerPts; int temps[]; int[] temps;

5.1.3 Creating Array Objects


Use new, or directly initialize the contents of that array. Example:
String[] names = new String[10]; int[] theNumbers = new int[100]; Car[] theCars = new Car[100]; String[] names = {Yong-Han, Goutam, Shreesh}; boolean[] isGoodGuy = {true, true, true};

5.1.4 Accessing Array Elements


Use the array subscription expression ([]). Use the instance variable length to test the length of an array. Example:
currentString = theStrings[i++]; int theFirst = theNumbers[0]; int theLast = theNumbers[theNumbers.length-1];

5.1.5 Changing Array Elements


Just use assignment statements. Example:
theStrings[10] = Hello!; theNumbers[0] = 15; theNumbers[i] = theNumber[i+1]; // Primitives type

IE582 Spring-2004

22

Car[2] = Car[3]; // Object type // what is the difference between them?

5.2 Container Objects


5.2.1 Container taxonomy

5.2.2 Some Useful Container Objects


Vector: a growable array of objects. ArrayList : resizable-array implementation of the List interface. Hashtable : This class implements a hashtable, which maps keys to values Stack: a growable array implementing first in last out mechanism HashSet: implements a set in a hash table TreeSet: implements a set in a tree structure, it can be sorted HashMap: implements a map in a hash table TreeMap: implements a map in a tree structure LinkedList: implements a linked list

5.2.3 More on LinkedList


Linked list is a simple but powerful data structure for the dynamic memory allocation. Java has fully implemented it. Define a Linked List IE582 Spring-2004 23

import java.util.*; ... List list = new LinkedList(); Iterate the list Iterator it = list.iterator(); while(it.hasNext()){ Object o = it.next(); } Add an item list.add(o); Remove an item List.remove(o); // o is an object in the list list.remove(i); // i is the index of an object in the list Update an item (1) use iterator to locate the object (2) update the object using the reference

IE582 Spring-2004

24

6 Input and Output


6.1 Stream?
A stream is a path of communication between the source of some information and its destination.

Procedure for reading and writing data Reading


open a stream while more information read information close the stream

Writing
open a stream while more information write information close the stream

6.2 Character Streams and Byte Streams


Character Streams: read and write a stream of characters (16 bits) o Reader and Writer are the abstract super classes for all character streams.

IE582 Spring-2004

25

Byte Streams: read and write a stream of bytes (8 bits). o InputStream and OutputStream are the abstract super classes for all byte streams. o These streams are typically used to read and write binary data such as images and sounds

6.3 Reading Console Input


Use predefined stream variable System.in and BufferedReader object. Example:
char ch; String str; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { // read a character. c = (char) br.read(); } catch (IOException e) { System.out.println(e.getMessage()); } try { // read a String. str = br.readLine(); } catch (IOException e) { System.out.println(e.getMessage()); }

IE582 Spring-2004

26

6.4 Writing Console Output


Use predefined print and println methods of System.out object. Example:
String str = a string line; System.out.println(str); System.out.print(str + \n);

6.5 Reading and Writing Files


Use two stream classes, FileInputStream and FileOutputStream. Example:
try { // read String lines from the file input.txt FileInputStream fis = new FileInputStream(input.txt); BufferedReader buff = new BufferedReader(new InputStreamReader(fis)); String line = new String(); while((line = buff.readLine()) != null) System.out.println(line); } catch (FileNotFoundException e){ System.out.println(e.getMessage()); } catch (IOException e){ System.out.println(e.getMessage()); } try { // write a String array to the file output.txt FileOutputStream fos = new FileOutputStream(output.txt); BufferedWriter buff = new BufferedWriter(new OutputStreamWriter(fos)); String[] line = {line 1, line 2, line 3, line 4}; for (int i=0; i<4; i++) { buff.write(line[i],0,line[i].length()); buff.newLine(); } fos.flush(); fos.close(); } catch (FileNotFoundException e){ System.out.println(e.getMessage()); } catch (IOException e){ System.out.println(e.getMessage()); }

6.6 Parsing String Input using Tokenizers


The StringTokenizer class allows an application to break a string into tokens. Example:
StringTokenizer st = new StringTokenizer("this is a test"); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } The output result is: this

IE582 Spring-2004

27

is a test

In the above example, the delimiters are in the string " \t\n\r\f". You can also customize the delimiters. Example:
StringTokenizer st = new StringTokenizer("kaizhi:student:2002", :\n\f); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); }

The output result is:


kaizhi student 2002

The StreamTokenizer class takes an input character stream and parses it into tokens, allowing the tokens to be read one at a time.

IE582 Spring-2004

28

7 Java Application
7.1 Creating Java Applications
Applications are Java programs that run on their own, while applets are Java programs that run on the Java-enabled browser and servlets run on the Javaenabled web server. A main() method must exist in a application. A typical example of the main() method: Public static void main(String args[]) { ... } Helper Classes: you can create as many classes as you want for your program, and as long as (1) they are in the same directory, (2) listed in your CLASSPATH, or (3) explicitly declare using java command option classpath, Java will be able to find them when your program runs.

7.2 Java Applications and Command-Line Arguments


Passing Arguments to Java Programs: append them to the command line! They are separated by spaces.

(example) java Myprogram argumentOne 2 three fourth argument Handling Arguments in Your Java program The arguments are stored in an array of strings.

Example:
class EchoArgs { public static void main(String args[]) { for (int i = 0; i < args.length; i++) { System.out.println(Argument + i + : + args[i]); } } // end of main() } // end of EchoArgs

Example:

IE582 Spring-2004

29

class SumAverage { public static void main(String args[]) { int sum = 0; for (int i = 0; i < args.length; i++) { sum += Integer.parseInt(args[i]); // convert string arguments to integer values } System.out.println(Sum = + sum); System.out.println(Average = + (float)sum / args.length); } // end of main() } // end of SumAverage

IE582 Spring-2004

30

8 What you need for (serious) Java Programming


8.1 Buy a Java book (or use online tutorials)
Java Tutorial from Sun: http://java.sun.com/docs/books/tutorial/

8.2 Use (hyperlinked) Java APT specification


Java 2 (v1.4) API Specification: http://java.sun.com/j2se/1.4/docs/api/

8.3 Use RAD Tools (especially for GUI programming) if possible


Full fledged RAD tools: Vis ual Caf , JBuilder, etc. Or, Java editor for writing, compiling, executing, and locating syntax errors: JPad, Editplus, etc.

8.4 * Some (possibly) important, but not covered topics


Graphic / Window User Interface : JFC/Swing (javax.swing.* ), 2D Graphics (java.awt.Graphics2D, java.awt.geom.*), etc. Multiple tasks at once : Multithreading (java.lang.thread ) Database Access : JDBC Database Access (java.sql.* ) Integrating Native Codes: Java Native Interface (JNI) And, Networking, Remote Method Invoking, Security, etc

IE582 Spring-2004

31