Top Banner
Chapter 1 Introduction to Java Java Java is an object-oriented programming language developed by Sun Microsystems, a company best known for its high-end UNIX workstations. Modeled after C++, the Java language was designed to be small, simple, and portable across platforms and operating systems, both at the source and at the binary level, which means that Java programs (applets and applications) can run on any machine that has the Java virtual machine installed. History The Java language was developed at Sun Microsystems in 1991 as part of a research project to develop software for consumer electronics devices-television sets, VCRs, toasters, and the other sorts of machines you can buy at any department store. Java's goals at that time were to be small, fast, efficient, and easily portable to a wide range of hardware devices. Those same goals made Java an ideal language for distributing executable programs via the World Wide Web and also a general-purpose programming language for developing programs that are easily usable and portable across different platforms. The Java language was used in several projects within Sun (under the name Oak), but did not get very much commercial attention until it was paired with HotJava. HotJava, an experimental World Wide Web browser, was written in 1994 in a matter of months, both as a vehicle for downloading and running applets and also as an example of the sort of complex application that can be written in Java. Although HotJava got a lot of attention in the Web community, it wasn't until Netscape incorporated HotJava's ability to play applets into its own browser that Java really took off and started to generate the excitement that it has both on and off the World Wide Web.
154

Java Complete Manual

Nov 18, 2014

Download

Documents

Nisar Malik
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Java Complete Manual

Chapter 1 Introduction to Java Java Java is an object-oriented programming language developed by Sun Microsystems, a company best known for its high-end UNIX workstations. Modeled after C++, the Java language was designed to be small, simple, and portable across platforms and operating systems, both at the source and at the binary level, which means that Java programs (applets and applications) can run on any machine that has the Java virtual machine installed. History The Java language was developed at Sun Microsystems in 1991 as part of a research project to develop software for consumer electronics devices-television sets, VCRs, toasters, and the other sorts of machines you can buy at any department store. Java's goals at that time were to be small, fast, efficient, and easily portable to a wide range of hardware devices. Those same goals made Java an ideal language for distributing executable programs via the World Wide Web and also a general-purpose programming language for developing programs that are easily usable and portable across different platforms. The Java language was used in several projects within Sun (under the name Oak), but did not get very much commercial attention until it was paired with HotJava. HotJava, an experimental World Wide Web browser, was written in 1994 in a matter of months, both as a vehicle for downloading and running applets and also as an example of the sort of complex application that can be written in Java. Although HotJava got a lot of attention in the Web community, it wasn't until Netscape incorporated HotJava's ability to play applets into its own browser that Java really took off and started to generate the excitement that it has both on and off the World Wide Web.

Page 2: Java Complete Manual

Java Technology With most programming languages, you either compile or interpret a program so that you can run it on your computer. The Java programming language is unusual in that a program is both compiled and interpreted. With the compiler, first you translate a program into an intermediate language called Java bytecodes —the platform-independent codes interpreted by the interpreter on the Java platform. The interpreter parses and runs each Java bytecode instruction on the computer. Compilation happens just once; interpretation occurs each time the program is executed. The following figure illustrates how this works.

…01010101

Source.java

You can think ofthe Java Virtual it's a developmenimplementation once, run anywhbytecodes on anycan then be run that as long as ain the Java progrSolaris workstatJava bytecodes aspecific to any onbytecode interpreinterpreter is alsinterpreter Java ApplicatioJava applicationthe Java languarun; in fact, Javapplications thaprogramming laJava Applets Applets are progrby a Web browseJava-enabled bro

Compiler

Java bytecMachine (Jt tool or a W

of the Java ere" possib platform ton any imp computer hamming laion, or on are a speciae processoter execute

o called the

n s, howeverge. Java apa can be ut you woulnguage to c

ams that ar and run iwser such

Source.class

odes as the maava VM). Every

eb browser thVM. Java bytecle. You can comhat has a Javalementation of as a Java VM,

nguage can runn iMac.

l set of machinr or computer ss the Java byte Java virtual m

, are more genplications don

sed to create ad normally usereate.

re downloadednside an HTMLas Netscape Na

2

Interpreter

chine code instructions for Java interpreter, whether at can run applets, is an odes help make "write pile your program into

compiler. The bytecodes the Java VM. That means the same program written on Windows 2000, a

e instructions that are not ystem. A platform-specific codes. The bytecode achine or the Java runtime

eral programs written in 't require a browser to ll the kinds of a more conventional

from the World Wide Web Web page. You'll need a vigator or Microsoft's

Page 3: Java Complete Manual

3

Internet Explorer to run applets. Applets appear in a Web page much the same way as images do, but unlike images, applets are dynamic and interactive. Applets can be used to create animation, figures, forms that immediately respond to input from the reader, games, or other interactive effects on the same Web pages among the text and graphics. The JDK needs two important modifications to your autoexec.bat file in order to work correctly: The JDK\bin directory must be in your execution path, and you must have the CLASSPATH variable set up. Creating a Java Application As with all programming languages, your Java source files are created in a plain text editor, or in an editor that can save files in plain ASCII without any formatting characters. Your first Java application. class HelloWorld { public static void main (String args[]) { System.out.println("Hello World!"); } } Java source files must have the same name as the class they define (including the same upper- and lowercase letters), and they must have the extension .java. Here, the class definition has the name HelloWorld, so the filename must be HelloWorld.java. Compiling and Running To compile the Java source file, you'll use the command-line Java compiler that comes with the JDK. To run the compiler, you'll need to first start up a DOS shell.From inside DOS, change directories to the location where you've saved your HelloWorld.java file. Once you've changed to the right directory, use the javac command as follows, with the name of the file as you saved it (javac stands for Java compiler). Note that you have to make sure you type all the same upper- and lowercase here as well: javac HelloWorld.java you'll get a file called HelloWorld.class .That's your Java bytecode file. If you get any errors, go back to your original source file and make sure you typed it correctly. Also make sure the filename has exactly the same upper- and lowercase as the name of the class. Once you have a class file, you can run that file using the Java bytecode interpreter. The Java interpreter is called simply java, and

Page 4: Java Complete Manual

4

you run it from the DOS shell as you did javac. Run your Hello World program like this from the command line, with all the same upper- and lowercase. java HelloWorld You should get the phrase Hello World! printed to your screen as a response. Java compiler and the Java interpreter are different things. You use the Java compiler (javac) for your Java source files to create .class files, and you use the Java interpreter (java) to actually run your class files.

Page 5: Java Complete Manual

5

Chapter 2 Java Fundamentals Identifiers Identifiers are tokens that represent names. These names can be assigned to variables, methods, and classes to uniquely identify them to the compiler and give them meaningful names for the programmer. All Java identifiers are case sensitive and must begin with a letter, an underscore (_), or a dollar sign ($). Letters include both uppercase and lowercase letters. Subsequent identifier characters can include the numbers 0 to 9. Keywords Keywords are predefined identifiers reserved by Java for a specific purpose. Java has a richer set of keywords. The following keywords are reserved for Java: abstract double int super boolean else interface switch break extends long synchronized byte false native this byvalue final new threadsafe case finallynull throw catch float package transient char for private true class goto protected try const if public void continue implements return while default import short do instanceof static Data Types One of the fundamental concepts of any programming language is data types. Data types define the storage methods available for representing information, along with how the information is interpreted. To create a variable in memory, you must declare it by providing the type of the variable as well as an identifier that uniquely identifies the variable. The syntax of the Java declaration statement for variables follows: Type Identifier [, Identifier]; The declaration statement tells the compiler to set aside memory for a variable of type Type with the name Identifier. The optional bracketed Identifier indicates that you can make multiple declarations of the same type by separating them with commas. Primitive Types

Page 6: Java Complete Manual

6

The eight primitive data types handle common types for integers, floating-point numbers, characters, and boolean values (true or false). There are four Java integer types, each with a different range of values. All are signed, which means they can hold either positive or negative numbers. Which type you choose for your variables depends on the range of values you expect that variable to hold; if a value becomes too big for the variable type, it is silently truncated. Integer types. Type Size Range byte 8 bits -128 to 127 short 16 bits -32,768 to 32,767 int 32 bits -2,147,483,648 to 2,147,483,647 long 64 bits -9,223,372,036,854,775,808 to

9,223,372,036,854,775,807 Floating-point numbers are used for numbers with a decimal part. There are two floating-point types: float (32 bits, single precision) and double (64 bits, double precision). The char type is used for individual characters. Because Java uses the Unicode character set, the char type has 16 bits of precision, unsigned. The boolean type can have one of two values, true or false. Assigning Values to Variables Once a variable has been declared, you can assign a value to that variable by using the assignment operator =, like this: amount = 14; display = true;

Page 7: Java Complete Manual

7

Comments The symbols /* and */ surround multiline comments, as in C or C++. All text between the two delimiters is ignored: Double-slashes (//) can be used for a single line of comment. All the text up to the end of the line is ignored: Expressions and Operators Expressions are the simplest form of statement in Java that actually accomplishes something: Most of the expressions in Java use operators. Operators are special symbols for things like arithmetic, various forms of assignment, increment and decrement, and logical operations. Arithmetic Java has five operators for basic arithmetic Arithmetic operators. Operator Meaning Example + Addition 3 + 4 - Subtraction 5 - 7 * Multiplication 5 * 5 / Division 14 / 7 % Modulus 20 % 7 Assignment operators. Expression Meaning x += y x = x + y x -= y x = x - y x *= y x = x * y x /= y x = x / y Incrementing and Decrementing As in C and C++, the ++ and -- operators are used to increment or decrement a variable's value by 1. For example, x++ increments the value of x by 1 just as if you had used the expression x = x + 1. Similarly x-- decrements the value of x by 1 .These increment and decrement operators can be prefixed or postfixed; that is, the ++ or can appear before or after the value it increments or decrements

Page 8: Java Complete Manual

8

Comparison operators. Operator Meaning Example == Equal x == 3 != Not equal x != 3 < Less than x < 3 > Greater than x > 3 <= Less than or equal

to x <= 3

>= Greater than or equal to

x >= 3

The boolean operators. Description Operator Evaluation AND & Evaluation OR | Evaluation XOR ^ Logical AND && Logical OR || Negation ! Equal-to == Not-equal-to != Conditional ?: The evaluation operators (&, |, and ^) evaluate both sides of an expression before determining the result. The logical operators (&& and ||) avoid the right-side evaluation of the expression if it is not needed. To better understand the difference between these operators, take a look at the following two expressions: boolean result = isValid & (Count > 10); boolean result = isValid && (Count > 10); The first expression uses the evaluation AND operator (&) to make an assignment. In this case, both sides of the expression are always evaluated, regardless of the values of the variables involved. In the second example, the logical AND operator (&&) is used. This time, the isValid boolean value is first checked. If it is false, the right side of the expression is ignored and the assignment is made. This operator is more efficient because a false value on the left side of the expression provides enough information to determine the false outcome.

Page 9: Java Complete Manual

9

Chapter 3 Programming Constructs if Statement The if conditional statement is used when you want to execute different bits of code based on a simple test. They contain the keyword if, followed by a boolean test, followed by either a single statement or a block statement to execute if the test is true. Here's a simple example that prints the message a is smaller than b only if the value of a is less than the value of b: class demo { Public static void main(String args[]) { int a = 10; int b = 20; if (a < b) System.out.println("a is smaller than b"); } } An optional else keyword provides the alternative statement to execute if the test is false: class demo { Public static void main(String args[]) { int a = 10; int b = 20; if (a < b) System.out.println("a is smaller than b"); else System.out.println("a is bigger"); } }

Page 10: Java Complete Manual

10

cass tmp { public static void main(String args[]) { boolean state if (state == true ) System.out.println("Power is on."); else { System.out.println("Power is off."); if (PowerLevel >= 1) state = true; else System.out.println("Low on Power can't start ..."); } } } public class Demo { public static void main(String[] args) { int score = 80; char grade; if (score >= 90) { grade = 'A'; } else if (score >= 80) { grade = 'B'; } else if (score >= 70) { grade = 'C'; } else if (score >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("Grade = " + grade); } } The Switch Statement Similar to the if-else branch, the switch branch is specifically designed to conditionally switch among multiple outcomes. The syntax for the switch statement follows: switch (Expression) {

Page 11: Java Complete Manual

11

case Constant1: StatementList1 case Constant2: StatementList2 default: defaultStatementList } The switch branch evaluates and compares Expression to all the case constants and branches the program's execution to the matching case statement list. If no case constants match Expression, the program branches to the defaultStatementList. When the program execution moves into a case statement list, it continues from there in a sequential manner. public class Demo { public static void main(String[] args) { int mon = 5; switch (mon) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; } } } Loops Loops Enable you to execute code repeatedly. There are three types of loops in Java: for loops, while loops, and do-while loops. for loops

Page 12: Java Complete Manual

12

The for loop provides a means to repeat a section of code a designated number of times.The syntax for the for statement follows: for (InitializationExpression; LoopCondition; StepExpression) Statement The for loop repeats the Statement the number of times that is determined by the InitializationExpression, the LoopCondition, and the StepExpression. for (int i = 1; i < 11; i++) System.out.println(i); while Loops You use while statement to continually execute a block of statements while a condition remains true. The general syntax of the while statement is: while (expression) { statement } First, the while statement evaluates expression, which must return a boolean value. If the expression returns true, then the while statement executes the statement(s) associated with it. The while statement continues testing the expression and executing its block until the expression returns false. int count = 0; while (count < 5) { System.out.println("Count = " + count); count++; } do-while Loops The do-while loop is very similar to the while loop, as you can see in the following syntax: do Statement while (LoopCondition); The major difference between the do-while loop and the while loop is that, in a do-while loop, the LoopCondition is evaluated after the

Page 13: Java Complete Manual

13

Statement is executed. This difference is important because there may be times when you want the Statement code to be executed at least once, regardless of the LoopCondition.

Page 14: Java Complete Manual

14

Chapter 4 OOPS Object-Oriented Programming Object-oriented programming is a completely new way of programming and, at the same time, contrary to the belief of some, it is much the same as structured programming. Once you learn and embrace the new terms and concepts associated with object programming, the switch can be so easy you may not even notice you are doing it. You see, the goal of OOP is to provide you, the programmer, with a few new ways to actually write code, and a whole lot of new ways to think about programming. Under an OOP paradigm, it is objects, which are represented in a system, not just their acquainted data structures. Objects aren't just numbers, like integers and characters; they are also the methods which relate and manipulate the numbers. In OOP programming, rather than passing data around a system ,messages are passed to and from objects. Rather than taking data and pushing it through a function, a message is passed to an object telling it to perform its task. Objects Objects are robust packages which contain both data and methods. Objects are replicateable and adjustable without damaging the predefined code. Instead of being trapped under innumerable potential additional uses, a method's purpose is easily definable, as is the data upon which it will work. As the needs of new programs begin to grow, the method can be replicated or adjusted to fit the needs of the new system taking advantage of the current method, but not necessarily altering it to do this (by overloading or overriding the method). Objects themselves can be expanded and, by deriving new objects from existing ones, code time is greatly reduced. Equally important, if not more so, debug time is greatly reduced by localizing bugs, because coupling changes are limited, at worst, to new classes. There are four main object oriented principles or paradigms which are important to an overall object oriented approach - Abstraction, Encapsulation,Inheritance and Polymorphism. Abstraction

Page 15: Java Complete Manual

15

This is the process of design which allows us to ignore details, commonly resulting in a top-down approach. To quote Grady Booch (Object Oriented Analysis and Design): An abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of objects and thus provides crisply defined conceptual boundaries, relative to the perspective of the viewer. Concentrating on the essential characteristics of an object which distinguish it from all other objects allows implementation to be ignored. In other words abstraction allows questions such as ' What can it do? ' rather than ' How is it going to do this?'. The essence, then, is to define an object in terms of those features which are unique to it, or which simply summarize its nature or function. There are many kinds of light bulb, but they all share the common function of providing a source of light. This view concentrates on the light bulb's essential function, whilst ignoring its implementation. Regardless of the nature of the light bulb incandescent, fluorescent, or gas vapour - the main features are that you can turn it on and light is produced, or turn it off and the light ceases. This could be shown with the following class: class LightSource { LightSource(); void TurnOn (); void TurnOff (); int IsOn (); } The class LightSource declares an abstraction of a light source, declaring the operators which may be performed on classes derived from it, namely turning the light on and off and determining its current state. At this stage the mechanisms for doing this are ignored. Encapsulation One major difference between conventional structured programming and object-oriented programming is a handy thing called encapsulation. Encapsulation enables you to hide, inside the object,

Page 16: Java Complete Manual

16

both the data fields and the methods that act on that data. fter you do this, you can control access to the data, forcing programs to retrieve or modify data only through the object's interface. In strict object-oriented design, an object's data is always private to the object. Other parts of a program should never have direct access to that data. Inheritance Inheritance is the ability to build on base classes, adding functionality as required without losing the features of the base class. Inheritance enables you to create a class that is similar to a previously defined class, but one that still has some of its own properties. Consider a car-simulation program. Suppose that you have a class for a regular car, but now you want to create a car that has a high-speed passing gear. In a traditional program, you might have to modify the existing code extensively and might introduce bugs into code that worked fine before your changes. To avoid these hassles, you use the object-oriented approach: Create a new class by inheritance. This new class inherits all the data and methods from the tested base class. You can control the level of inheritance with the public, private, and protected keywords. Think of how human children inherit many of their characteristics from their parents. But the children also have characteristics that are uniquely their own. In object-oriented programming, you can think of a base class as a parent and a derived class as a child.

Page 17: Java Complete Manual

17

Polymorphism The last major feature of object-oriented programming is polymorphism. By using polymorphism, you can create new objects that perform the same functions as the base object but which perform one or more of these functions in a different way. For example, you may have a shape object that draws a circle on the screen. By using polymorphism, you can create a shape object that draws a rectangle instead. You do this by creating a new version of the method that draws the shape on the screen. Both the old circle-drawing and the new rectangle-drawing method have the same name (such as DrawShape()) but accomplish the drawing in a different way.

Page 18: Java Complete Manual

18

Chapter 5 Classes Classes are the major building block of an object-oriented structure. In fact, classes are what make objects possible. classes are a way to assemble a set of data and then determine all of the methods needed to access, use, and change that data. Every class has two major portions. The first portion is that of state. The state of an object is nothing more than the values of each of its variables. If, for instance, you had a class Engine with one variable, onoff, the state of the Engine would be determined by the value of onoff. public class Engine{ int onoff; } The second portion of a class is its methods. The methods of a class determine the utility the class has. In the case of the Engine, it is likely that you would have a method called start(), which would cause the Engine to start. public class Engine{ int onoff; start(){ onoff=1; } } In general, Java class declarations have the form: <modifiers > class <ClassName> [<extends>] [<NameofSuperClass>] [<implements>] [<NameofInterface>] Public Classes By placing the modifier public in front of the class declaration, the class is defined to be public. Public classes are, as their name implies, accessible by all objects. This means that they can be used or extended by any object. public class Picture note that public classes must be defined in a file called ClassName.java. Final Classes

Page 19: Java Complete Manual

19

Final classes may not have any subclasses and are created by placing the modifier final in front of the class declaration. final class Picture Abstract Classes An abstract class, denoted by the modifier abstract, is a class in which at least one method is not complete. This state of not being finished is referred to as abstract.(explained in chapter “Interfaces”) abstract class PictureFrame { abstract void pictype(); } Extending Another Class One of the most important aspects of OOP is the ability to use the methods and fields of a class you have already built. By building upon these simpler classes to build bigger ones, you can save yourself a lot of coding. Possibly even more important, you can greatly reduce the work of finding and fixing bugs in your code. In order to build upon a previous class, you must extend the class in the class declaration. By extending a super class, you are making your class a new copy of that class but are allowing for growth. public class MyClass extends Applet { Constructors Constructors are very special methods with unique properties and a unique purpose. Constructors are used to set certain properties and perform certain tasks when instances of the class are created.

Page 20: Java Complete Manual

20

Public class myclass { public myclass () { ………. } Constructors are identified by having the same name as the class itself. constructors do not specify a return argument because they are not actually called as a method. myclass myobject = new myclass(); When the new myclass() is actually instantiated, the constructor method is called. constructors are used to initialize the class's fields and perform various tasks related to creation, such as performing some initial calculations. Instance of a Class An instance is an object of the type of the class. Any class you create can be instantiated, just like any other data type in Java. For example, to create an instance of the GameBoard, you would generally declare a variable of that type. The following code fragment shows a class called Inventory creating an instance of the Stock: public class Inventory{ Stock stk = new Stock(); .... } new tells the computer to allocate the necessary space ,Causes the constructor method to be called.,Returns a reference to the object Class Fields These variables are declared outside of any methods, but within a given class are referred to as fields of the class and are accessible to all methods of it.

Page 21: Java Complete Manual

21

Method Variables These variables are local to the method and may only be accessed within that method. Access modifiers public The public modifier makes fields visible to all classes, regardless of their package, as well as all subclasses. public int size; protected protected fields may be accessed by all subclasses of the current class, but are not visible to classes outside of the current package. protected int size; private The highest degree of protection, private fields are accessible to all methods within the current class. They are, however, not accessible to any other classes, nor are they accessible to the subclasses of the current class. private int size; private protected private protected fields, like private protected methods, are accessible within the class itself, as well as within subclasses of the current class. private protected int size; static Static fields are fields of the class whose values are the same in all instances of the class. static fields may be modified in both static and non-static methods. static int size; final

Page 22: Java Complete Manual

22

By placing the modifier final in front of a field declaration, you tell the compiler that the value of the field may not change during execution. Furthermore, because it cannot change elsewhere, it is necessary to set the value of all final fields when they are declared. final int SIZE = 5; finalize() Method This method is called by the Java runtime system during the process of garbage collection and, thus, may be used to clean up any ongoing processes before the object is destroyed. The finalize() method is very similar to the ~classname() method in C++. Nested Classes / Inner Classes Nested classes are classes that are actually included within the body of another class. Inner classes provide you with the ability to organize your code in a more understandable fashion, and occasionally provide the compiler with a means to further optimize the final code. The major advantage of inner classes is the ability to create what are known as adapter classes. Adapter classes are classes that implement an interface. By isolating individual adapters into nested classes you can, in essence, build a package-like structure right within a single top-level class. Methods Methods serve the same purpose in Java that functions do for C, C++.... All execution, which takes place in any applet or application, takes place within a method.Java methods are the essence of the class and are responsible for managing all tasks that will be performed. The simplest method would look like this:

Page 23: Java Complete Manual

23

void method() { ……. } The declaration for a method is similar to the first line in the previous section. At the very least, it specifies what the method will return, and the name the method will be known by. Ordinarily, as you will soon see, more options than these two are used. In general, method declarations have the form: <access_specifier> <modifier> <return_value> <nameofmethod> (parameters) throws ExceptionList Access specifiers are used to restrict access to the method. Regardless of what the access specifier is, though, the method is accessible from any other method in the same class. public By specifying a method as public, it becomes accessible to all classes. private A private method is only accessible by those methods in the same class. Even classes that extend from the current class do not have access to a private class. private protected Those methods declared to be private protected are accessible to both the class and any subclasses, but not the rest any classes Method modifiers enable you to set properties for the method, such as where it will be visible and how subclasses of the current class will interact with it. final By placing the keyword final in front of the method declaration, you prevent any subclasses of the current class from overriding the given method.

Page 24: Java Complete Manual

24

static Placing the static modifier in front of a method declaration makes the method a static method. While non-static methods can also operate with static variables, static methods can only deal with static variables and static methods abstract Abstract methods are simply methods that are declared, but are not implemented in the current class. The responsibility of defining the body of the method is left to subclasses of the current class. synchronized By placing the keyword synchronized in front of a method declaration, you can prevent data corruption that may result when two methods attempt to access the same piece of data at the same time. While this may not be a concern for simple programs, once you begin to use threads in your programs, this may become a serious problem. Method Overloading Method overloading is the ability to define multiple methods with the same name in a class; when the method is invoked, the compiler picks the correct one based on the arguments passed to the method. This implies, of course, that overloaded methods must have different numbers or types of arguments. (explained in Chapter “Inheritance”) Overriding methods Overriding a method means that its entire functionality is being replaced. Overriding is something done in a child class to a method defined in a parent class. To override a method a new method is defined in the child class with exactly the same signature as the one in the parent class. (explained in Chapter “Inheritance”) Creating objects

Page 25: Java Complete Manual

25

An object is an instance of a class. Use the following syntax to create an object: 'new' constructor The new keyword, often called the creation operator, allocates an object's memory and initializes that memory to default values. An object's field values are stored in memory. Because new is an operator, it takes an operand: constructor, which is the name of a special method that constructs the object. Once new finishes allocating and initializing memory, it calls the constructor to perform object initialization. class Demo { int i = 3; public static void main (String [] args) { Demo obj1 = new Demo (); System.out.println ("obj1.i = " + obj1.i); obj1.myprint(); Demo obj2 = new Demo(); obj1.i = 5; System.out.println ("obj1.i = " + obj1.i); obj1.myprint(); System.out.println ("obj2.i = " + obj2.i); obj2.myprint(); } void myprint() { System.out.println ("Hello! i = " + i + "\n"); } } Field declaration statement int i = 3; specifies a field named i, which is of type integer (as specified by the int keyword) and initializes i to 3 (as specified by the integer literal 3). Demo obj1 = new CODemo2 (); creates an object from the Demo class. Demo obj2 = new Demo (); creates a second object from Demo. Because an object is an instance of a class, class instance is often used as a synonym for object. Demo obj1 and Demo obj2 declare variables in a manner similar to int count or double balanceOwing. Data type keywords int and double declare storage locations named count and balanceOwing for holding values of primitive data types: integer and double-precision floating-point, respectively. Demo, on the other hand, declares a storage location for holding a value of a reference or address data type. In other words, because obj1 and obj2 have the

Page 26: Java Complete Manual

26

Demo data type and Demo is a reference data type, any value assigned to either obj1 or obj2 is a reference to (that is, the address of) an object created from the Demo class. Once the constructor has finished building the object, creation operator new returns the address of that object.

Page 27: Java Complete Manual

27

Chapter 6 Arrays Arrays Arrays are probably the oldest and still the most generally effective means of storing groups of variables. An array is a group of variables that share the same name and are ordered sequentially from zero to one less than the number of variables in the array. The number of variables that can be stored in an array is called the array's dimension. Each variable in the array is called an element of the array. Creating Arrays There are three steps to creating an array, declaring it, allocating it and initializing it. Like other variables in Java, an array must have a specific type like byte, int, String or double. Only variables of the appropriate type can be stored in an array. You cannot have an array that will store both ints and Strings, for instance. Like all other variables in Java an array must be declared. When you declare an array variable you suffix the type with [ ] to indicate that this variable is an array. Here are some examples: int[] k; float[] yt; String[] names; Allocating Arrays To actually create the array (or any other object) use the new operator. When we create an array we need to tell the compiler how many elements will be stored in it. Here's how we'd create the variables declared above: k = new int[3]; yt = new float[7]; names = new String[50]; The numbers in the brackets specify the dimension of the array; i.e. how many slots it has to hold values. With the dimensions above k can hold three ints, yt can hold seven floats and names can hold fifty Strings. Therefore this step is sometimes called

Page 28: Java Complete Manual

28

dimensioning the array. More commonly this is called allocating the array since this step actually sets aside the memory in RAM that the array requires. new is a reserved word in java that is used to allocate not just an array, but also all kinds of objects. Java arrays are full-fledged objects with all that implies. For now the main thing it implies is that we have to allocate them with new. Individual elements of the array are referenced by the array name and by an integer which represents their position in the array. The numbers we use to identify them are called subscripts or indexes into the array. Subscripts are consecutive integers beginning with 0. Thus the array k above has elements k[0], k[1], and k[2]. Since we started counting at zero there is no k[3], and trying to access it will generate an ArrayIndexOutOfBoundsException. Here's how we'd store values in the arrays we've been working with: k[0] = 2; k[1] = 5; k[2] = -2; yt[6] = 7.5f; names[4] = "Surya"; We can declare and allocate an array at the same time like this: int[] k = new int[3]; float[] yt = new float[7]; String[] names = new String[50]; int[] k = {1, 2, 3}; float[] yt = {0.0f, 1.2f, 3.4f, -9.87f, 65.4f, 0.0f, 567.9f};

Page 29: Java Complete Manual

29

imort java.util.*; class RandomTest { public static void main (String args[]) { int[] ndigits = new int[10]; double x; int n; Random myRandom = new Random(); // Initialize the array for (int i = 0; i < 10; i++) { ndigits[i] = 0; } for (long i=0; i < 100000; i++) { // generate a new random number between 0 and 9 x = myRandom.nextDouble() * 10.0; n = (int) x; //count the digits in the random number ndigits[n]++; } // Print the results for (int i = 0; i <= 9; i++) { System.out.println(i+": " + ndigits[i]); } } } import java.util.*; class BubbleSort { public static void main(String args[]) { int[] n; n = new int[10]; Random myRand = new Random();

Page 30: Java Complete Manual

30

// initialize the array for (int i = 0; i < 10; i++) { n[i] = myRand.nextInt(); } // print the array's initial order System.out.println("Before sorting:"); for (int i = 0; i < 10; i++) { System.out.println("n["+i+"] = " + n[i]); } boolean sorted = false; // sort the array while (!sorted) { sorted = true; for (int i=0; i < 9; i++) { if (n[i] > n[i+1]) { int temp = n[i]; n[i] = n[i+1]; n[i+1] = temp; sorted = false; } } } // print the sorted array System.out.println(); System.out.println("After sorting:"); for (int i = 0; i < 10; i++) { System.out.println("n["+i+"] = " + n[i]); } } } Two dimensional arrays are declared, allocated and initialized much like one dimensional arrays. However we have to specify two dimensions rather than one, and we typically use two nested for loops to fill the array. class FillArray { public static void main (String args[]) { int[][] M; M = new int[4][5];

Page 31: Java Complete Manual

31

for (int row=0; row < 4; row++) { for (int col=0; col < 5; col++) { M[row][col] = row+col; } } } } class IDMatrix { public static void main (String args[]) { double[][] ID; ID = new double[4][4]; for (int row=0; row < 4; row++) { for (int col=0; col < 4; col++) { if (row != col) { ID[row][col]=0.0; } else { ID[row][col] = 1.0; } } } } } Like C Java does not have true multidimensional arrays. Java fakes multidimensional arrays using arrays of arrays. This means that it is possible to have unbalanced arrays. An unbalanced array is a multidimensional array where the dimension isn't the same for all rows. IN most applications this is a horrible idea and should be avoided.

Page 32: Java Complete Manual

Chapter 7 Inheritance Inheritance Inheritance is the ability to build on base classes, adding functionality as required without losing the features of the base class. Inheritance is the process of creating a new class with the characteristics of an existing class, along with additional characteristics unique to the new class. Inheritance provides a powerful and natural mechanism for organizing and structuring programs. In Java all classes are subclasses from a super class called Object.

Deriving Classes The syntax for deriving a class using the extends keyword is: class Identifier extends SuperClass { ClassBody } Identifier refers to the name of the newly derived class, SuperClass refers to the name of the class you are deriving from, and ClassBody is the new class body. class Base { public void amethod(){ System.out.println("Base amethod()"); }

32

Page 33: Java Complete Manual

33

} public class Subclass extends Base{ public static void main(String argv[]){ Subclass b = new Subclass(); b.amethod(); } } When a class is based on another class, it inherits all the properties of that class, including the data and methods for the class. The class doing the inheriting is referred to as the subclass (or the child class), and the class providing the information to inherit is referred to as the superclass or the parent class. Overloading methods Method overloading is a powerful and useful feature. It's another form of polymorphism. The idea is to create methods that act in the same way on different types of arguments and have what appears to be a single method that operates on any of the types. The Java PrintStream's print() method is a good example of method overloading in action. The variable out is a reference to an object (a PrintStream) that defines nine different versions of the print() method. They take, respectively, arguments of the following types: Object, String, char[], char, int, long, float, double, and boolean. class PrintStream { void print( Object arg ) { ... } void print( String arg ) { ... } void print( char [] arg ) { ... } ...} Overriding methods To override a method a new method is defined in the child class with exactly the same signature as the one in the parent class. class a { public void m1() { System.out.println(“Hello from Base class : method m1..”); }

Page 34: Java Complete Manual

34

} class b extends a { public void m1() { System.out.println(“Hello from derived class : method m1..”); } } class impl { public static void main(String args[]) { System.out.println(“…in main…”); b obj = new b(); obj.m1(); } } constructors with super() A constructor is a special method that is automatically run every time an instance of a class is created. Java knows that a method is a constructor because it has the same name as the class itself and no return value. Constructors are not inherited however, so if you want to get at some useful constructor from an ancestor class it is not available by default, the word you need to get at a constructor in an ancestor is super. This keyword can be used as if it were a method and passed the appropriate parameters to match up with the version of the parental constructor you require. class Base{ public Base(){ } public Base(int i){ } } public class SubClass extends Base{ public static void main(String arg[]){ SubClass m = new SubClass(10); } SubClass(int i) { super(i); } } constructors with this()

Page 35: Java Complete Manual

35

You can call a base class constructor-using super () you can call another constructor in the current class by using this as if it were a method. Thus in the previous example you could define another constructor as follows ………. SubClass(String s, int i){ this(i); } ……………….. If you use super() or this() in a constructor it must be the first method call.

Page 36: Java Complete Manual

36

Chapter 8 Interfaces Interfaces provide templates of behavior that other classes are expected to implement. Interfaces provide a means to define the protocols for a class without worrying about the implementation details.once interfaces have been designed, the class development can take place without worrying about communication among classes. Another important use of interfaces is the capacity for a class to implement multiple interfaces which is supported in C++ but not in Java. Multiple inheritance enables you to derive a class from multiple parent classes. Declaring Interfaces The syntax for creating interfaces follows: interface <Interface Name> { public int Method1(); } <Interface Name> Identifier is the name of the interface and Method1() refers to the abstract method. Because it is assumed that all the methods in an interface are abstract, it isn't necessary to use the abstract keyword. Implementing Interfaces Implementing an interface is similar to deriving from a class, except that you are required to implement any methods defined in the interface. To implement an interface, you use the implements keyword. class <Class Name> implements <Interface Name> { …. ClassBody … } Class Name refers to the name of the new class, Interface Name is the name of the interface you are implementing, and ClassBody is the new class body. interface Clock { public String dispTime(int hour);

Page 37: Java Complete Manual

37

} class Iclock implements Clock { public String dispTime(int hour) { StringBuffer str = new StringBuffer(); for (int i=0; i < hour; i++) str.append("Iclock "); return str.toString(); } } class DigiClock implements Clock { public String dispTime(int hour) { return new String("It is " + hour + ":00"); } } In the above example, Clock is an interface that provides a single method, dispTime. What this means is that any class that is derived from Clock must provide a dispTime function. Iclock is an example of a class that implements Clock A new class can be derived from a superclass and one or more interfaces. This could be done as follows for a class that implements two interfaces and has one superclass: class MyClass extends MySuperClass implements Interface1, Interface2 { // class implementation } It is possible for one class to implement more than one interface.

Page 38: Java Complete Manual

Chapter 9 Exception Handling An exceptional condition is a problem that prevents the continuation of the method or scope that you’re in.With an exceptional condition, you cannot continue processing because you don’t have the information necessary to deal with the problem in the current context. All you can do is jump out of the current context and relegate that problem to a higher context. Exception handling, therefore, is the process of detecting and responding to exceptions in a consistent and reliable manner. The term "exception" is used instead of "error" because exceptions represent exceptional, or abnormal, conditions that aren't necessarily errors.Most often, exceptions are used as a way to report error conditions. Exceptions can be used as a means of indicating other situations as well. Exceptions provide notification of errors and a way to handle them. A simple example is a divide. If you’re about to divide by zero, it’s worth checking to makesure you don’t go ahead and perform the divide. Java exceptions are class objects subclassed from java.lang.Throwable. Because exceptions are class objects, they can contain both data and methods. In fact, the base class Throwable implements a method that returns a String describing the error that caused the exception.

throw, try, and catch Blocks A try block is a block of code beginning with the try keyword followed by a left and a right curly brace. Every try block is associated with one or more catch blocks.

38

Page 39: Java Complete Manual

39

try { // method calls ……. } If a method is to catch exceptions thrown by the methods it calls, the calls must be placed within a try block. If an exception is thrown, it is handled in a catch block. This is a try block and a catch block set up to handle exceptions of type Exception: try { // method calls … } catch( Exception e ) { // handle exceptions here } class Demo { public static void main(String args[]) { int d,a; try { d = 0; a = 42/d; System.out.println(“This will not be printed”); } catch (ArithmeticException e) { System.out.println(“Division by Zero..”); } System.out.println(“After Catch….”); } } When any method in the try block throws any type of exception, execution of the try block ceases. Program control passes immediately to the associated catch block. If the catch block can handle the given exception type, it takes over. If it cannot handle the exception, the exception is passed to the method's caller. In an application, this process goes on until a catch block catches the exception or the exception reaches the main() method uncaught and causes the application to terminate.

Page 40: Java Complete Manual

40

Multiple catch Blocks In some cases, a method may have to catch different types of exceptions. Java supports multiple catch blocks. Each catch block must specify a different type of exception: try { // method calls go here } catch( SomeExceptionClass e ) { // handle SomeExceptionClass exceptions here } catch( SomeOtherExceptionClass e ) { // handle SomeOtherExceptionClass exceptions here } When an exception is thrown in the try block, it is caught by the first catch block of the appropriate type. Only one catch block in a given set will be executed. Notice that the catch block looks a lot like a method declaration. The exception caught in a catch block is a local reference to the actual exception object. You can use this exception object to help determine what caused the exception to be thrown in the first place. Class Demo { Public static void main(String args[]) { try { int a = args.length; System.out.println(“a = “ + a); int b = 42/ a; int c[] = { 1 }; c[42] = 99; } catch(ArithmeticException e ) { System.out.println(“Divide by Zero : “ + e); } catch(ArrayIndexOutOfBoundsException e ) { System.out.println(“Array Index Out Of.. “ + e); } System.out.println(“After try/catch block”); } }

Page 41: Java Complete Manual

41

/*This program will cause a divide by zero exception if started with no command line parameers and ArrayOutOfBounds Exception if started with command line parameters. */ throw Statement A throw statement is used to cause an exception to be thrown: The expression in a throw statement must produce a reference to an object that is an instance of the Throwable class or one of its subclasses. Otherwise, the compiler issues an error message. Here is an example of a throw statement: throw new ProtocolException(); A throw statement causes normal program execution to stop. Control is immediately transferred to the innermost enclosing try statement in the search for a catch clause that can handle the exception. If the innermost try statement cannot handle the exception, the exception propagates up through enclosing statements in the current method. If the current method does not contain a try statement that can handle the exception, the exception propagates up to the invoking method. If this method does not contain an appropriate try statement, the exception propagates up again, and so on. Finally, if no try statement is found to handle the exception, the currently running thread terminates. throws Clause The throws clause tells the compiler that a method is a possible source of that type of checked exception and that anyone calling that method must be prepared to deal with it. The caller may use a try/catch block to catch it, or it may, itself, declare that it can throw the exception.

Page 42: Java Complete Manual

42

finally Clause The finally clause sets apart a block of code that is always executed. public class MultiThrow { public static void main( String[] args ) { try { ……………//java statements } catch( Exception e } { System.out.println( "Caught exception " ) ; } finally() { System.out.println( "Finally. " ) ; } } } Custom Exception Custom Exceptions are necessary to handle abnormal conditions of applications created by user . The advantage of creating such exceptions is that according to the situations defined by the user exceptions can be thrown. class MyException extends Exception { private int val; MyException(int xx) { val = xx; } public String toString() { return “Myexception :” + val ; } } class demo {

Page 43: Java Complete Manual

43

public static void main(String args[]) { int x = -100; try { if (x <= 0) throw new MyException(x); else System.out.println(“Value of x = “ + x); } catch(Exception e) { System.out.println(e); } } } The java.lang Exceptions. Exception Cause ArithmeticException Divide by zero ArrayIndexOutOfBoundsException index is less than zero or greater than the size. ClassCastException Cast of object to inappropriate type. ClassNotFoundException Unable to load the requested class. Exception Root class of the exception hierarchy. IllegalAccessException Class is not accessible. IllegalArgumentException Method receives an illegal argument. IndexOutOfBoundsException Index is out of bounds. InstantiationException Attempt to create an instance of the abstract class. InterruptedException Thread interrupted. NegativeArraySizeException Array size is less than zero. NoSuchMethodException Unable to resolve method. NullPointerException Attempt to access a null object member. NumberFormatException Unable to convert the string to a number. RuntimeException Base class for many java.lang exceptions. SecurityException Security settings do not allow the operation. StringIndexOutOfBoundsException Index is negative or greater than the size of the string java.io Exceptions Exception Cause IOException Root class for I/O exceptions. EOFException End of file. FileNotFoundException Unable to locate the file. java.net Exceptions

Page 44: Java Complete Manual

44

Exception Cause MalformedURLException Unable to interpret URL. ProtocolException Socket class protocol error. SocketException Socket class exception. UnknownHostException Unable to resolve the host name. UnknownServiceException Connection does not support the service.

Page 45: Java Complete Manual

45

Chapter 10 Packages Classpath Before you can understand much about packages, you will need to understand the classpath environment variable.The purpose of the classpath environment variable is to tell the JVM and other Java applications such as the javac compiler and the java interpreter where to find class files and class libraries. One way to set the classpath environment variable is to enter the information into your autoexec.bat file. SET CLASSPATH=c:\jdk1.2\myclasses; Another way to set the classpath when working with java is to use a command-line parameter that is available with javac and java . javac -classpath c:\jdk1.2\myclasses myclass.java In this case myclass.java is the name of the Java source file that you are compiling If you specify the classpath with javac, be sure to also specify the same classpath later when you use java to run the program.Your classpath must contain a fully-qualified path name for every folder that contains class files of interest, or for every zip or jar file of interest. The paths should begin with the letter specifying the drive and end either with the name of the zip or jar file or the name of the folder that contains the class files. Packages Packages are groups of related classes and interfaces. Packages provide a convenient mechanism for managing a large group of classes and interfaces, while avoiding potential naming conflicts. The Java Package name also reflects its directory structure. The package name should always be same as directory name.

Page 46: Java Complete Manual

46

Declaring Packages The syntax for the package statement follows: package <pakage name>; This statement must be placed at the beginning of a compilation unit,before any class declarations. Every class located in a compilation unit with a package statement is considered part of that package.Packages can be nested within other packages. When this is done, the Java interpreter expects the directory structure containing the executable classes to match the package hierarchy. Importing Packages The import statement enables you to import classes from other packages into a compilation unit. You can import individual classes or entire packages of classes at the same time if you want. import <package name>.<class Name>; Steps for Creating a Package 1) Create a folder named mypackage. 2) Code the following and store it in the folder. package mypackage; public class Vector { public Vector() { System.out.println("hello from Vector...."); } } 3) Compile the source file to Vector.class When you create your own packages, you’ll discover that the package statement must be the first non-comment code in the file. 4) set the classpath to the to the folder(package) location. 5) code the following ,compile and run.

Page 47: Java Complete Manual

47

import mypackage.*; public class Test { public static void main(String[] args) { Vector v = new Vector(); System.out.println("Package Demo...."); } } or public class Test { public static void main(String[] args) { mypackage.Vector v = new mypackage.Vector(); System.out.println("Package Demo...."); } } Class Visibility Class visibility is determined relative to packages. For example, a public class is visible to classes in other packages. Actually, public is the only explicit access modifier allowed for classes. Without the public access modifier, classes default to being visible to other classes in a package but not visible to classes outside the package.

Page 48: Java Complete Manual

Chapter 11 Java I/O Streams A stream is a flowing sequence of characters. The task is to move data from memory to an external device or vice versa, but not necessarily. it is the responsibility of the computer to move bytes from one place to another without regard for the meaning associated with those bytes. It is the responsibility of the programmer to assign meaning to the bytes. For example, a group of 32 bytes could represent 32 pieces of graphic data, or 8 integer values; the stream I/O system doesn't usually know and doesn't care. Only the programmer and the user know and care what the 32 bytes are meant to represent. a stream is usually considered to be an abstraction for the capability to move bytes. The package named java.io contains a set of input and output stream classes that can be used to read and write data. Stream Hierarchay

48

Page 49: Java Complete Manual

The InputStream class and OutputStream class are abstract superclasses that define the behavior for sequential input and output streams in Java. The java.io package also provides specialized InputStream and OutputStream subclasses that are used for specialized types of input and output. For example, we have been using the following code fragments since the beginning of the Introductory course: System.out.println("Hello.."); System.out refers to an output stream managed by the System class that implements the standard output system. System.out is an instance of the PrintStream class defined in the java.io package. The PrintStream class is a subclass of OutputStream. Input Stream Java uses input streams as the means of reading data from an input source, such as the keyboard. The basic input stream classes supported by Java follow: InputStream BufferedInputStream DataInputStream FileInputStream StringBufferInputStream The InputStream Class The InputStream class is an abstract class that serves as the base class for all other input stream classes. InputStream defines a basic interface for reading streamed bytes of information. InputStream class Methods

49

abstract int read()

Page 50: Java Complete Manual

50

int read(byte b[]) int read(byte b[], int off, int len) long skip(long n) int available() synchronized void mark(int readlimit) synchronized void reset() boolean markSupported() void close() System.in The keyboard is the most standard device for retrieving user input. The System class contained in the language package contains a member variable that represents the keyboard, or standard input stream. This member variable is called in and is an instance of the InputStream class. This variable is useful for reading user input from the keyboard. class Demo { public static void main (String args[]) { StringBuffer s = new StringBuffer(); char c; try { while ((c = (char)System.in.read()) != '\n') { s.append(c); } } catch (Exception e) { System.out.println("Error: " + e.toString()); } System.out.println(s); } } BufferedInputStream As its name implies, the BufferedInputStream class provides a buffered stream of input. This means that more data is read into the buffered stream than you might have requested, so that subsequent reads come straight out of the buffer rather than from the input device. This arrangement can result in much faster read access because reading from a buffer is really just reading from memory BufferedInputStream constructors BufferedInputStream(InputStream in) BufferedInputStream(InputStream in, int size)

Page 51: Java Complete Manual

51

Notice that both constructors take an InputStream object as the first parameter. The only difference between the two is the size of the internal buffer. In the first constructor, a default buffer size is used; in the second constructor, you specify the buffer size with the size integer parameter. import java.io.*; class Demo { public static void main (String args[]) { BufferedInputStream bin = new BufferedInputStream(System.in); byte buf[] = new byte[10]; try { bin.read(buf, 0, 10); } catch (Exception e) { System.out.println("Error: " + e.toString()); } String s = new String(buf, 0); System.out.println(s); } } The DataInputStream Class The DataInputStream class is useful for reading primitive Java data types from an input stream in a portable fashion. There is only one constructor for DataInputStream, which simply takes an InputStream object as its only parameter. This constructor is defined as follows: DataInputStream(InputStream in) DataInputStream implements the following useful methods. final int skipBytes(int n) final void readFully(byte b[]) final void readFully(byte b[], int off, int len) final String readLine() final boolean readBoolean() final byte readByte() final int readUnsignedByte() final short readShort()

Page 52: Java Complete Manual

52

final int readUnsignedShort() final char readChar() final int readInt() final long readLong() final float readFloat() final double readDouble() The readLine() method is used to read a line of text that has been terminated with a newline , carriage return , carriage return / newline, or end-of-file character sequence. readLine() returns the line of text in a String object. import java.io.*; class Demo { public static void main (String args[]) { DataInputStream in = new DataInputStream(System.in); String s = new String(); try { s = in.readLine(); float f = Float.valueOf(s).floatValue(); System.out.println(f); } catch (Exception e) { System.out.println("Error: " + e.toString()); } } } The File Class The File class models an operating system directory entry, providing you with access to information about a file-including file attributes and the full path where the file is located. File class constructors: File(String path) File(String path, String name) File(File dir, String name) The first constructor takes a single String parameter that specifies the full pathname of the file. The second constructor takes two String parameters: path and name. The path parameter specifies

Page 53: Java Complete Manual

53

the directory path where the file is located; the name parameter specifies the name of the file. The third constructor is similar to the second except that it takes another File object as the first parameter instead of a string. The File object in this case is used to specify the directory path of the file. File Class Methods String getName() String getPath() String getAbsolutePath() String getParent() boolean exists() boolean canWrite() boolean canRead() boolean isFile() boolean isDirectory() boolean isAbsolute() long lastModified() long length() boolean mkdir() boolean mkdirs() boolean renameTo(File dest) boolean delete() String[] list() String[] list(FilenameFilter filter)

Page 54: Java Complete Manual

54

import java.io.*; class FileDemo { public static void main(String args[]) { File fl = new File(“c:\\java”,”tmp.txt”); System.out.println(“File Name : “ + fl.getName()); System.out.println(“Path : “ + fl.getPath()); System.out.println(fl.exists() ? “File Exists” : “File does not Exist”); System.out.println(fl.isDirectory() ? “Directory” : “Not a Directory”); } } import java.io.*; class FileDemo { public static void main(String args[]) throws IOException { File f = new File(“c:/demofolder”); if(f.mkdir()) System.out.println(“Directory Created..”); else System.out.println(“Cannot Create Directory ..”); } } import java.io.*; class FileDemo { public static void main(String args[]) { String dname = “/windows”; File f1 = new File(dname); if (f1.isDirectory()) { System.out.println(“Directory Listing..\n”) String s[] = f1.list(); for (int i = 0; i < s.length;i++) { File f = new File(dname + “/” + s[I]); if (f.isDirectory()) { System.out.println(s[i] + “is a directory”); } else { System.out.println(s[i] + “ is a file”); } } }

Page 55: Java Complete Manual

55

else { System.out.println(dname + “ is not a directory”); } } } The FileInputStream Class The FileInputStream class is useful for performing simple file input. The FileInputStream class can be instantiated using one of the in three following constructors: FileInputStream(String name) FileInputStream(File file) The first constructor takes a String object parameter called name, which specifies the name of the file to use for input. The second constructor takes a File object parameter that specifies the file to use for input. import java.io.*; class ReadDemo { public static void main (String args[]) { byte buf[] = new byte[64]; try { FileInputStream in = new FileInputStream("tmp.txt"); in.read(buf, 0, 64); } catch (Exception e) { System.out.println("Error: " + e.toString()); } String s = new String(buf, 0); System.out.println(s); } } A FileInputStream object is first created by passing a string with the name of the file ("tmp.txt") as the input file. The read() method is then called to read from the input file into a byte array. The byte array is then used to create a String object, which is in turn used for output. Output Stream Classes

Page 56: Java Complete Manual

56

Output streams handle writing data to output sources. you use output streams to output data to various output devices, such as the screen. OutputStream PrintStream BufferedOutputStream DataOutputStream FileOutputStream OutputStream Class OutputStream class serves as an abstract base class for all the other output stream classes. OutputStream defines the basic protocol for writing streamed data to an output device. The OutputStream class implements the following methods: abstract void write(int b) void write(byte b[]) void write(byte b[], int off, int len) void flush() void close() OutputStream defines three different write() methods for writing data in a few different ways. The first write() method writes a single byte to the output stream, as specified by the integer parameter b. The second version of write() takes an array of bytes as a parameter and writes it to the output stream. The last version of write() takes a byte array, an integer offset, and a length as parameters.The off parameter specifies an offset into the byte array from which you want to begin outputting data, and the len parameter specifies how many bytes are to be output. The flush() method is used to flush the output stream. Calling flush() forces the OutputStream object to output any pending data. Finally, the close() method closes an output stream and releases any resources associated with the stream. . The PrintStream Class The PrintStream class is derived from OutputStream and is designed primarily for printing output data as text. PrintStream has two different constructors :

Page 57: Java Complete Manual

57

PrintStream(OutputStream out) PrintStream(OutputStream out, boolean autoflush) Both PrintStream constructors take an OutputStream object as their first parameter. The only difference between the two methods is how the newline character is handled. In the first constructor, the stream is flushed based on an internal decision by the object. In the second constructor, you can specify that the stream be flushed every time it encounters a newline character. You specify this through the boolean autoflush parameter. The PrintStream class implements the following methods. void print(Object obj) synchronized void print(String s) synchronized void print(char s[]) void print(char c) void print(int i) void print(long l) void print(float f) void print(double d) void print(boolean b) void println() synchronized void println(Object obj) synchronized void println(String s) synchronized void println(char s[]) synchronized void println(char c) synchronized void println(int I) synchronized void println(long l) synchronized void println(float f) synchronized void println(double d) synchronized void println(boolean b) System.out The System class has a member variable that represents the standard output stream, which is typically the monitor. The member variable is called out and is an instance of the PrintStream class. The out member variable is very useful for outputting text to the screen. BufferedOutputStream

Page 58: Java Complete Manual

58

This class enables you to write to a stream without causing a bunch of writes to an output device. The BufferedOutputStream class maintains a buffer that is written to when you write to the stream. When the buffer gets full or when it is explicitly flushed, it is written to the output device. constructors for BufferedOutputStream : BufferedOutputStream(OutputStream out) BufferedOutputStream(OutputStream out, int size) import java.io.*; class WriteDemo { public static void main (String args[]) { String s = new String("Kalyani Institute of Technology\n"); byte[] buf = new byte[64]; s.getBytes(0, s.length(), buf, 0); BufferedOutputStream out = new BufferedOutputStream(System.out); try { out.write(buf, 0, 64); out.flush(); } catch (Exception e) { System.out.println("Error: " + e.toString()); } } } The DataOutputStream Class The DataOutputStream class is useful for writing primitive Java data types to an output stream. This constructor is defined as follows: DataOutputStream(OutputStream out) The DataOutputStream class implements the following methods : final int size() final void writeBoolean(boolean v) final void writeByte(int v) final void writeShort(int v) final void writeChar(int v) final void writeInt(int v)

Page 59: Java Complete Manual

59

final void writeLong(long v) final void writeFloat(float v) final void writeDouble(double v) final void writeBytes(String s) final void writeChars(String s) The FileOutputStream Class The FileOutputStream class provides a means to perform simple file output. A FileOutputStream object can be created using one of the following constructors: FileOutputStream(String name) FileOutputStream(File file) The FileOutputStream class functions exactly like the OutputStream class except that it is specifically designed to work with files. import java.io.*; class WriteDemo { public static void main (String args[]) { // Read the user input byte buf[] = new byte[64]; try { System.in.read(buf, 0, 64); } catch (Exception e) { System.out.println("Error: " + e.toString()); } // Output the data to a file try { FileOutputStream out = new FileOutputStream("Output.txt"); out.write(buf); } catch (Exception e) { System.out.println("Error: " + e.toString()); } } } InputStreamReader

Page 60: Java Complete Manual

60

InputStreamReader is a bridge from byte streams to character streams. It reads bytes and translates them into characters. Each invocation of one of an InputStreamReader's read( ) methods may cause one or more bytes to be read from the underlying byte-input stream and is declared: import java.io.*; public class ReaderDemo { public static void main(String args[]) throws IOException{ InputStreamReader input = new InputStreamReader(System.in); int ch; String st; System.out.println("enter a character and press enter :"); ch = input.read(); System.out.println("Character value " +(char) ch); } } FileReaderFileReader allows an application to gain access to character input specified of file type. File myfile = new File("xyz.dat"); FileReader FR = new FileReader(myfile); int c; While ((c = FR.read() !=-1) { System.out.println("FR : " + c); } FR.close(); In this case the application reads directly from the file. This would be very inefficient if the application had to read many times and thus a buffered reader could be used. BufferedReaderBufferedReader allocates memory storage for data input. In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. This could lead to many reading steps, and reading is one of the slowest aspects of computer processing. The Buffered reader allows for one reading step by providing data input storage which can then be accessed efficiently. "The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

Page 61: Java Complete Manual

61

InputStreamReader mystream= new InputStreamReader(System.in); BufferedReader br = new BufferReader(mystream); BufferedWriter BufferedWriter allocates memory storage for data output. Each read request made of a FileWriter causes a corresponding write request to be made of the underlying character or byte stream. This could lead to many writing steps. The BufferedWritter allows for one writing step by providing data output storage which can then be outputted efficiently. "The buffer size may be specified, or the default size may be used. File outputFile = new File("output.dat"); FileWriter fwr = new FileWriter(outputFile); BufferedWriter out = new BufferedWriter(fwr); String TokenizerString Tokenizer is useful in applications using java.io to manipulate strings. StringTokenizer is a Java utility used to separate a string into tokens (generally individual words) in an application by recognizing delimiters, the white space and comment characters and procuring substrings or tokens between delimiters. StringTokenizer st = new StringTokenizer( " this is a test " ); While (st.hasMoreTokens ()) { Println(st.nextToken( ) ); } The above code prints the following output: this is a test Methods countTokens( ) - Calculates the number of tokens contained in a tokenizable string from the current token. nextToken (String delim) - Returns the next string Token from a tokenizable string. hasMoreTokens( ) - Tests if a tokenizable string has more tokens. nextElement( ) - Returns the next object Token from a tokenizable string

Page 62: Java Complete Manual

62

import java.io.*; import java.util.*; public class FileDemo { public static void main ( String args[] ) throws IOException { File inputFile = new File("test.dat"); BufferedReader br = new BufferedReader(new FileReader(inputFile)); int temp; StringTokenizer st; String c; while(true) { if((c = br.readLine()) == null) break; st = new StringTokenizer(c); temp = st.countTokens(); System.out.println("Count = " + temp); for (int i = 0 ; i < temp ; i++) { System.out.println(" "+ st.nextToken()); } } } } Object Serialization Object Serialization capability of Java makes it possible to write objects to streams and read objects from streams without the requirement to decompose those objects into their component parts before writing, and without the requirement to reconstruct the object from its component parts after reading. Object serialization provides the capability to store and retrieve Java objects. This capability is provided on the basis of streams so that objects can be "stored" and "retrieved" from any medium that supports streams in Java. This includes disk files, communication links via sockets, stream buffers in memory, etc. ObjectOutputStream Class Constructors public ObjectOutputStream(OutputStream out) Creates an ObjectOutputStream that writes to the specified OutputStream. . . . . . FileOutputStream ostream = new FileOutputStream("t.tmp"); ObjectOutputStream p = new ObjectOutputStream(ostream);

Page 63: Java Complete Manual

63

p.writeInt(12345); p.writeObject("Today"); p.writeObject(new Date()); p.flush(); ostream.close(); . . . . . . ObjectInputStream Constructors ObjectInputStream(InputStream in) Create an ObjectInputStream that reads from the specified InputStream. . . . . . FileInputStream istream = new FileInputStream("t.tmp"); ObjectInputStream p = new ObjectInputStream(istream); int i = p.readInt(); String today = (String)p.readObject(); Date date = (Date)p.readObject(); istream.close(); . . . . .

Page 64: Java Complete Manual

64

Page 65: Java Complete Manual

65

Chapter 12 Applets A Java program is executed as either an application that runs stand-alone from the command line or as an applet that runs under a Web browser. Applications and applets start program execution in different ways; an application has a main() method and an applet has a init() method initiated by the browser. The source code of a Java applet is stored in file with the suffix ".java". The source code is compiled into byte code and stored in a file with the suffix ".class". The ".class" file is included in the HTML document using the applet tag. A Web browser executes a Java applet when the browser loads an HTML document that contains an applet tag. The applet tag defines the width and height of the applet window within the HTML document. The applet tag has numerous attributes to enhance its placement within the HTML document. <APPLET CODE="myapplet.class" WIDTH=170 HEIGHT=150> Packages java.awt This is a package of classes for building a graphical user interface. java.applet This is a package of classes including the Applet class that the Contact class is extending. Applet Class All applets must be a subclass of the Applet class. When a class is extended from another class it inherits all data and methods of the class it extends. The following figure shows the inheritance hierarchy of the Applet class. This hierarchy determines much of what an applet can do and how.

Page 66: Java Complete Manual

66

java.lang.Object | +----java.awt.Component | +----java.awt.Container | +----java.awt.Panel | +----java.applet.Applet The browser controls the applet's behavior by executing four standard applet methods named: init(), start(), stop(), and destroy(). An applet requires the initialization code to be placed in the init() method, which is the first method called by the browser to get things going. An applet may optionally override the other three methods in order to perform functions at certain times in the lifecycle of the applet as listed below. init( ) - called when the applet is first created to perform first-time initialization of the applet start( ) - called every time the applet moves into sight on the Web browser to allow the applet to start up its normal operations (especially those that are shut off by stop( )). Also called after init( ). paint( ) - Part of the base class Component (three levels of inheritance up). Called as part of an update( ) to perform special painting on the canvas of an applet. stop( ) - called every time the applet moves out of sight on the Web browser to allow the applet to shut off expensive operations. Also called right before destroy( ). destroy( ) called when the applet is being unloaded from the page to perform final release of resources when the applet is no longer used import java.awt.*; import java.applet.*; public class myapplet extends Applet { public void paint(Graphics g) { g.drawString("my first applet", 10, 10);

Page 67: Java Complete Manual

67

} } /*The applet tag <applet code=”myapplet” width=200 height=200> </applet> */ Passing parameters Applet parameters are used to provide information that the applet can retrieve. Parameters are in the form : <param name=identifier value = "information”> import java.awt.*; import java.applet.*; public class ParamTest extends Applet { Font f = new Font(“Arial”,Font.BOLD,30); String nm; public void init() { nm = getParameter(“name”); if nm == null) nm = “folk”; else nm = “Happy Learning ” + nm ; } public void paint(Graphics g) { g.setFont(f); g.setColor(Color.green); g.drawstring(nm,60,60); } <Applet code=”ParamTest.class” width=400 height=400> <Param Name=”name” value=”Sameer”> </Applet> The paint( ) method is called automatically when the the applet decides that it needs to update itself perhaps because it’s being moved back onto the screen or placed on the screen for the first time, or perhaps some other window had been temporarily placed over your Web browser. The applet calls its update( ) method which goes about restoring everything and as a part of that restoration calls paint( ). When update( ) calls paint( ) it hands it a

Page 68: Java Complete Manual

68

handle to a Graphics object that represents the surface on which you can paint. The Graphics object also has a set of operations you can perform on it. These operations like painting on the canvas, so most of them have to do with drawing images, shapes, arcs, etc .The most commonly used one is drawString( ). For this, you must specify the String you want to draw and its starting location on the applet’s drawing surface. This location is given in pixels. import java.awt.*; import java.applet.*; public class Applet2 extends Applet { public void paint(Graphics g) { g.drawString("Second applet", 10, 15); g.draw3DRect(0, 0, 100, 20, true); } } The following applet keeps track of the number of times the init(), Start(),stop() methods are called and displays them using paint( ) import java.awt.*; import java.applet.*; public class MyApplet extends Applet { String s; int in = 0; int st = 0; int sto = 0; public void init() { in++; } public void start() { st++; } public void stop() { sto++; } public void paint(Graphics g) { s = "in : " + in + ", st : " + st + ", sto : " + sto; g.drawString(s, 10, 10); } }

Page 69: Java Complete Manual

69

Page 70: Java Complete Manual

70

Graphics Class methods Drawing drawLine(int, int, int, int) - Draws a line, using the current color, between two points in this graphics context's coordinate system. drawPolyline(int[], int[], int) - Draws a sequence of connected lines defined by arrays of x and y coordinates. The figure will not be closed if the first point differs from the last point. drawRect(int, int, int, int) - Draws the outline of the specified rectangle using the current color of the graphics context.. fillRect(int, int, int, int) - Fills the specified rectangle with the context's current color. Be sure to check the documentation regarding the coordinates of the right edge and bottom edge of the rectangle before using. This comment applies to all the fill methods. drawRoundRect(int, int, int, int, int, int) - Draws an outlined round-cornered rectangle using this graphics context's current color. You might need to look at a book containing a diagram to learn how to specify how the corners are rounded. fillRoundRect(int, int, int, int, int, int) - Fills the specified rounded corner rectangle with the current color. draw3DRect(int, int, int, int, boolean) - Draws a 3-D highlighted outline of the specified rectangle. The edges of the rectangle are highlighted so that they appear to be beveled and lit from the upper left corner. The boolean parameter determines whether the rectangle appears to be raised above the surface or sunk into the surface. It is raised when the parameter is true. fill3DRect(int, int, int, int, boolean) - Paints a 3-D highlighted rectangle filled with the current color. drawOval(int, int, int, int) - Draws the outline of an oval in the current color. When the last two parameters are equal, this method draws a circle. fillOval(int, int, int, int) - Fills an oval bounded by the specified rectangle with the current color. As with drawOval(), when the last two parameters are equal, the method fills a circle. drawArc(int, int, int, int, int, int) - Draws the outline of a circular or elliptical arc covering the specified rectangle. You will probably need to examine the documentation to figure out how to specify the parameters for this method as well as the fillArc() method. fillArc(int, int, int, int, int, int) - Fills a circular or elliptical arc covering the specified rectangle. drawPolygon(Polygon) - Draws the outline of a polygon defined by the specified Polygon object. Another overloaded version is available that accepts a list of coordinate values to specify the

Page 71: Java Complete Manual

71

polygon. The following description of a Polygon object was taken from the JavaSoft documentation fillPolygon(Polygon) - Fills the polygon defined by the specified Polygon object with the graphics context's current color. Another overloaded version is available that accepts a list of coordinate values to specify the polygon.overloaded version is available that accepts a list of coordinate values to specify the polygon. import java.awt.*; import java.applet.*; public class DrawDemo extends Applet { int xps[] = {40,49,60,70,57,40,35}; int yps[] = {260,310,315,280,260,270,265}; int xpps[] = {140,150,180,200,170,150,140 }; int ypps[] = {260,310,315,280,260,270,265 }; public void pain(Graphics g) { g.drawString("Sample Program"); g.drawLine(40,30,200,30); g.drawRect(40,60,70,40); g.fillRect(140,60,70,40); g.drawRoundRect(240,60,70,40,10,20); g.fillRoundRect(40,120,70,40,10,20); g.draw3DRect(140,120,70,40,true); g.drawOval(240,120,70,40); g.fillOval(40,180,70,40); g.drawArc(140,180,70,40,0,180); g.fillArc(240,180,70,40,0,-180); g.drawPolygon(xps,yps,7); g.fillPolygon(xpps,ypps,7); } } Text drawString(String, int, int) - Draws the text given by the specified string, using this graphics context's current font and color. drawChars(char[], int, int, int, int) - Draws the text given by the specified character array, using this graphics context's current font and color. Another version lets you pass an array of bytes to represent the characters to be drawn. getFont() - Gets the current font and returns an object of type Font which describes the context's current font. getFontMetrics() - Gets the font metrics of the current font. Returns an object of type FontMetrics. Methods of the FontMetrics

Page 72: Java Complete Manual

72

class can be used to obtain metrics information (size, etc.) about the font to which the getFontMetrics() method is applied. getFontMetrics(Font) - Gets the font metrics for the specified font. setFont(Font) - Sets the specified font import java.applet.*; import java.awt.*; public class FontDemo extends Applet { Font f; public void init() { f = new Font(“Helvetica”,Font.BOLD + Font.ITALIC,20); } public void paint(Graphics g) { g.setFont(f); g.drawstring(“Font Name is Helvetica and size is 20”,50,50); } }

Page 73: Java Complete Manual

73

Image drawImage(Image, int, int, int, int, int, int, int, int, Color, ImageObserver) Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface. import java.applet.*; import java.awt.*; public class ImgSample extends Applet { Image img; public void init() { img = getImage(getCodeBase(),”Picture.gif”); } public void paint(Graphics g) { g.drawstring(img,20,20,this); } } /*getCodeBase() returns the URL of the .html file */ The Color Class TheColor Class encapsulates colors using the RGB format. This is a format in which a particular color is created by adding contributions from the primary colors: red, green, and blue. In RGB format, the red, green, and blue components of a color are each represented by an integer in the range 0-255. The value 0 indicates no contribution from the associated primary color. A value of 255 indicates the maximum intensity of the primary color component. The Color class provides a set of convenience methods for converting between RGB and HSB colors. object.setBackground(Color.red); The Color class provides a set of static final variables which make it convenient to specify any one of thirteen predefined colors. black ,blue ,cyan ,darkGray ,gray ,green ,lightGray magenta,orange ,pink ,red ,white and yellow Constructors Color(int, int, int) - Creates a color with the specified RGB components. Color(int) - Creates a color with the specified value. Font Class

Page 74: Java Complete Manual

74

The Font class provides the following symbolic constants that are used to establish the style of an instantiated Font object. PLAIN ,BOLD ,ITALIC Constructor Font(String, int, int) - Creates a new font object with the specified name, style and point size where the name is provided by the String parameter, and the style and point size are provided by the two int parameters. Methods decode(String) - Gets the specified font using the name passed in. equals(Object) - Compares this object to the specified object. getFamily() - Gets the platform specific family name of the font. getFont(String) - Gets a font from the system properties list. getFont(String, Font) - Gets the specified font from the system properties list. getName() - Gets the logical name of the font. getPeer() - Gets the peer of the font. getSize() - Gets the point size of the font. getStyle() - Gets the style of the font. hashCode() - Returns a hashcode for this font. isBold() - Indicates whether the font's style is bold. isItalic() - Indicates whether the font's style is italic. isPlain() - Indicates whether the font's style is plain. toString() Converts this object to a String representation. Chapter 13 AWT The Java Abstract Windowing Toolkit (AWT) is a general-purpose, multiplatform windowing library. The AWT provides classes that encapsulate many useful graphical user interface GUI components also called controls. The AWT also includes classes to manage component layout and utility classes to handle fonts, colors, and other GUI-related items. AWT provides a common interface to the native GUI components on a wide variety of platforms. This abstraction makes the AWT highly portable. The AWT classes can be divided into three groups : Control classes The control classes of the AWT provide a platform-independent wrapper for the basic GUI Controls. These classes include most of the components necessary to create a modern user interface for your Java applets or applications.

Page 75: Java Complete Manual

75

Layout classes The AWT contains a group of classes designed to handle placement of controls in Container objects. Menu classes The AWT provides a hierarchy of classes that allow you to include menus in your applets and applications Button The Button class is "A class that produces a labeled button component." The Button class extends Component which causes it to have access to the many methods defined in the Component class. Constructors : Button() -- Constructs a Button with no label. Button(String) -- Constructs a Button with the specified label. Methods addActionListener(ActionListener) -- Adds the specified action listener to receive action events from this button. getLabel() -- Gets the label of the button. removeActionListener(ActionListener) -- Removes the specified action listener so it no longer receives action events from this button. setLabel(String) -- Sets the button with the specified label. Checkbox The Checkbox class extends the Component class, and implements the ItemSelectable interface. ItemSelectable interface is the interface for objects which contain a set of items for which zero or more can be selected. constructors. Checkbox() -- Constructs a Checkbox with an empty label. Checkbox(String) -- Constructs a Checkbox with the specified label. Checkbox(String, boolean) -- Constructs a Checkbox with the specified label. The check box starts in the specified state. Checkbox(String, boolean, CheckboxGroup) -- Constructs a Checkbox with the specified label, set to the specified state, and in the specified check box group.

Page 76: Java Complete Manual

76

Checkbox(String, CheckboxGroup, boolean) -- Constructs a Checkbox with the specified label, set to the specified state, and in the specified check box group. CheckboxGroup CheckboxGroup() -- Creates a new CheckboxGroup. Methods getSelectedCheckbox() -- Gets the current choice. Returns type Checkbox. setSelectedCheckbox(Checkbox) -- Sets the current choice to the specified Checkbox. toString() -- Returns the String representation of this CheckboxGroup's values. import java.awt.*; import java.applet.*; public class demo extends Applet { public void init() { CheckboxGroup cbg = new CheckboxGroup(); Checkbox cb1 = new Checkbox(“Male “,cbg,true); Checkbox cb2 = new Checkbox(“Female “,cbg,false); add(cb1); add(cb2); } } Choice The Choice class is a pop-up menu of choices. The current choice is displayed as the title of the menu. Choice() -- Constructs a new Choice. Methods add(String) Adds an item to this Choice. addItem(String) Adds an item to this Choice. addItemListener(ItemListener) Adds the specified item listener to receive item events from this choice. getItem(int) Returns the String at the specified index in the Choice. getItemCount() Returns the number of items in this Choice. getSelectedIndex() Returns the index of the currently selected item. getSelectedItem() Returns a String representation of the current choice. getSelectedObjects() Returns an array (length 1) containing the currently selected item.

Page 77: Java Complete Manual

77

insert(String, int) Inserts the item into this choice at the specified position. remove(int) Removes an item from the choice menu. remove(String) Remove the first occurrence of item from the choice menu. removeAll() Removes all items from the choice menu. removeItemListener(ItemListener) Removes the specified item listener so that it no longer receives item events from this choice. select(int) Selects the item with the specified position. select(String) Selects the item with the specified String. import java.awt.*; import java.awt.event.*; import java.util.*; public class ChoiceDemo extends Applet { Choice myChoice = new Choice(); public void init() { myChoice.add("First Choice"); myChoice.add("Second Choice"); myChoice.add("Third Choice"); myChoice.select("Second Choice"); add(myChoice); } } List The List class is described as a scrolling list of items. Constructors : List() -- Creates a new scrolling list . List(int) -- Creates a new scrolling list initialized with the specified number of visible lines. List(int, boolean) -- Creates a new scrolling list initialized with the specified number of visible lines and a boolean stating whether multiple selections are allowed or not. Methods The following is a partial list of methods. add(String) -- Adds the specified item to the end of scrolling list. add(String, int) -- Adds the specified item to the scrolling list at the specified position. addActionListener(ActionListener) -- Adds the specified action listener to receive action events from this list. addItem(String) -- Adds the specified item to the end of scrolling

Page 78: Java Complete Manual

78

list. addItem(String, int) -- Adds the specified item to the scrolling list at the specified position. import java.awt.*; import java.applet.*; class ListDemo Extends Applet { List myList = new List(); for(int cnt = 0; cnt < 15; cnt++) myList.add("List Item " + cnt); myList.setMultipleMode(true); myList.select(1); add( myList); } } TextField The TextField class can be used to instantiate components that allow the editing of a single line of text. The class can also be used to display non-editable text in a single-line format with a border. The TextField class extends the TextComponent class which extends the Component class. Methds of TextComponent addTextListener(TextListener) -- Adds the specified text event listener to receive text events from this textcomponent. removeTextListener(TextListener) -- Removes the specified text event listener so that it no longer receives text events from this textcomponent getSelectedText() -- Returns the selected text contained in this TextComponent. getSelectionEnd() -- Returns the selected text's end position. getSelectionStart() -- Returns the selected text's start position. getText() -- Returns the text contained in this TextComponent. select(int, int) -- Selects the text found between the specified start and end locations. selectAll() -- Selects all the text in the TextComponent. setSelectionEnd(int) -- Sets the selection end to the specified position. setSelectionStart(int) -- Sets the selection start to the specified position. setCaretPosition(int) -- Sets the position of the text insertion caret for the TextComponent getCaretPosition() -- Returns the position of the text insertion caret for the text component. setEditable(boolean) -- Sets the specified boolean to indicate whether

Page 79: Java Complete Manual

79

or not this TextComponent should be editable. isEditable() -- Returns the boolean indicating whether this TextComponent is editable or not. setText(String) -- Sets the text of this TextComponent to the specified text. Constructors TextField() -- Constructs a new TextField. TextField(int) -- Constructs a new empty TextField with the specified number of columns. TextField(String) -- Constructs a new TextField initialized with the specified text. TextField(String, int) -- Constructs a new TextField initialized with the specified text and columns. Methods of TextField addActionListener(ActionListener) -- Adds the specified action listener to receive action events from this textfield. removeActionListener(ActionListener) -- Removes the specified action listener so that it no longer receives action events from this textfield. getColumns() -- Returns the number of columns in this TextField. setColumns(int) -- Sets the number of columns in this TextField. getMinimumSize() -- Returns the minimum size Dimensions needed for this TextField. getMinimumSize(int) -- Returns the minimum size Dimensions needed for this TextField with the specified amount of columns. getPreferredSize() -- Returns the preferred size Dimensions needed for this TextField. getPreferredSize(int) -- Returns the preferred size Dimensions needed for this TextField with the specified amount of columns. setEchoChar(char) -- Sets the echo character for this TextField. This is useful for fields where the user input shouldn't be echoed to the screen, as in the case of a TextField that represents a password. echoCharIsSet() -- Returns true if this TextField has a character set for echoing. getEchoChar() -- Returns the character to be used for echoing. import java.awt.*; import java.applet.*; public class TextFieldDemo extends Applet TextField myTextField = new TextField("Initial Text"); public void init(){ add (myTextField); }

Page 80: Java Complete Manual

80

} TextArea A TextArea object is a multi-line area that displays text. It can be set to allow editing or read-only modes. Constructors TextArea() -- Constructs a new TextArea. TextArea(int, int) -- Constructs a new empty TextArea with the specified number of rows and columns. TextArea(String) -- Constructs a new TextArea with the specified text displayed. TextArea(String, int, int) -- Constructs a new TextArea with the specified text and number of rows and columns. TextArea(String, int, int, int) -- Constructs a new TextArea with the specified text and number of rows, columns, and scrollbar Methods append(String) -- Appends the given text to the end. insert(String, int) -- Inserts the specified text at the specified position. replaceRange(String, int, int) -- Replaces text from the indicated start to end position with the new text specified. Label An object of class Label is an object that can be used to display a single line of read-only text. Constructors Label() -- Constructs an empty label. Label(String) -- Constructs a new label with the specified String of text. Label(String, int) -- Constructs a new label with the specified String of text and the specified alignment. Methods getAlignment() Gets the current alignment of this label. getText() Gets the text of this label. setAlignment(int) Sets the alignment for this label to the specified alignment. setText(String) Sets the text for this label to the specified text. import java.awt.*; import java.awt.event.*; public class LabelDemo { public void init(){ Label myLabel = new Label("Initial Text");

Page 81: Java Complete Manual

81

add(myLabel) ; } } Scrollbar The Scrollbar component is an up-down or left-right slider that can be used to set a numeric value. The component can be used by clicking the mouse on an arrow or grabbing the box on the slider. Constructors Scrollbar() -- Constructs a new vertical scroll bar. Scrollbar(int) -- Constructs a new scroll bar with the specified orientation. public Scrollbar(int orientation, int value, int visible, int minimum, int maximum) Constructs a new scroll bar with the specified orientation, initial value, page size, and minimum and maximum values. The orientation argument must take one of the two values Scrollbar.HORIZONTAL, or Scrollbar.VERTICAL, indicating a horizontal or vertical scroll bar, respectively. orientation - indicates the orientation of the scroll bar. value - the initial value of the scroll bar. visible - the size of the scroll bar's bubble, representing the visible portion; the scroll bar uses this value when paging up or down by a page. minimum - the minimum value of the scroll bar. maximum - the maximum value of the scroll bar. Methods addAdjustmentListener(AdjustmentListener) -- Adds the specified adjustment listener to receive instances of AdjustmentEvent from this scroll bar. addNotify() -- Creates the Scrollbar's peer. getBlockIncrement() -- Gets the block increment of this scroll bar. getLineIncrement() -- Deprecated. getMaximum() -- Gets the maximum value of this scroll bar. getMinimum() -- Gets the minimum value of this scroll bar. getOrientation() -- Determines the orientation of this scroll bar. getValue() Gets the current value of this scroll bar.

Page 82: Java Complete Manual

82

import java.applet.*; import java.awt.*; class ScrollDemo extends Applet { public void init() { Scrollbar myScrollbar; myScrollbar = new Scrollbar(Scrollbar.HORIZONTAL,0,10,10,100); add(myScrollbar); } } Controling Layout The way components are placed on a form is controlled by a “layout manager” that decides how the components lie based on the order that you add( ) them. The size, shape, and placement of components will be remarkably different from one layout manager to another. In addition, the layout managers adapt to the dimensions of your applet or application window, so if that window dimension is changed (for example, in the HTML page’s applet specification) the size, shape, and placement of the components could change. Both the Applet and Frame classes are derived from Container, whose job it is to contain and display Components. The Container is a Component so it can also react to events. In Container, there’s a method called setLayout( ) that allows you to choose a different layout manager. FlowLayout Applet uses a default layout scheme : the FlowLayout. This simply “flows” the components onto the form, from left to right until the top space is full, then moves down a row and continues flowing the components. FlowLayout the components take on their “natural” size. A Button, for example, will be the size of its string. import java.awt.*; import java.applet.*; public class FlowLayout1 extends Applet { public void init() { setLayout(new FlowLayout()); //by default an Applet has has FlowLayout for(int i = 0; i < 20; i++) add(new Button("Button " + i));

Page 83: Java Complete Manual

83

} } BorderLayout This layout manager has the concept of four border regions and a center area. When you add something to a panel that’s using a BorderLayout you must use an add( ) method that takes a String object as its first argument, and that string must specify with proper capitalization “North” (top), “South” (bottom), “East” (right), “West” (left), or “Center.” import java.awt.*; import java.applet.*; public class BorderLayout1 extends Applet { public void init() { int i = 0; setLayout(new BorderLayout());//by default Frame & Windows have BorderLayout add("North", new Button("Button " + i++)); add("South", new Button("Button " + i++)); add("East", new Button("Button " + i++)); add("West", new Button("Button " + i++)); add("Center", new Button("Button " + i++)); } } For every placement but “Center,” the element that you add is compressed to fit in the smallest amount of space along one dimension while it is stretched to the maximum along the other dimension. “Center,” however, spreads out along both dimensions to occupy the middle. The BorderLayout is the default layout manager for applications and dialogs. GridLayout A GridLayout allows you to build a table of components, and as you add them they are placed left-to-right and top-to-bottom in the grid. In the constructor you specify the number of rows and columns that you need and these are laid out in equal proportions. import java.awt.*; import java.applet.*;

Page 84: Java Complete Manual

84

public class GridLayout1 extends Applet { public void init() { setLayout(new GridLayout(7,3)); for(int i = 0; i < 20; i++) add(new Button("Button " + i)); } } CardLayout The CardLayout allows you to create the rough equivalent of a “tabbed dialog,” which in more sophisticated environments has actual file-folder tabs running across one edge, and all you have to do is press a tab to bring forward a different dialog. Not so in the AWT: The CardLayout is simply a blank space and you’re responsible for bringing forward new cards. The Container Classes The following hierarchy diagram shows where the Container classes Panel, Window, and Frame fit into the overall inheritance hierarchy. java.lang.Object | +----java.awt.Component | +----java.awt.Container | +----java.awt.Panel | +----java.awt.Window | +----java.awt.Frame The Panel Class The Panel class inherits from the Container class and can be used to produce a completely generic container. Panel() -- Creates a new panel with a default FlowLayout manager. Panel(LayoutManager) -- Creates a new panel with the specified layout manager.

Page 85: Java Complete Manual

85

The default layout manager for a Panel object is FlowLayout. It is also possible to specify a different layout manger for the object when it is instantiated, and it is possible to accept the default initially and change it later using the setLayout() method. import java.awt.*; import java.applet.*; public class PanelDemo extends Applet { public void init() { Panel leftPanel = new Panel(); leftPanel.setBackground(Color.yellow); leftPanel.add(new TextField("Left Panel is Yellow")); Panel middlePanel = new Panel(); middlePanel.setBackground(Color.red); middlePanel.add(new Label("Middle Panel is Red")); Panel rightPanel = new Panel(); rightPanel.setBackground(Color.blue); rightPanel.add(new Button("Right Panel is Blue")); add(leftPanel); add(middlePanel); add(rightPanel); } } The Window Class As shown in the earlier hierarchy diagram, the Window class extends the Container class. It is a top-level window with no borders and no menubar. The JDK documentation indicates that it could be used, for example, to implement a pop-up menu.Window is rarely used directly; its subclasses Frame and Dialog are more commonly useful. The Frame Class The Frame class extends the Window class. A Frame object is an optionally resizable top-level window with a title, a minimize box, a maximize box, a close box, and a control box.The default layout for a Frame object is BorderLayout. Frames are capable of generating the following types of window events: WindowOpened WindowClosing

Page 86: Java Complete Manual

86

WindowClosed WindowIconified WindowDeiconified WindowActivated WindowDeactivated constructors: Frame() -- Constructs a new Frame that is initially invisible. Frame(String) -- Constructs a new, initially invisible Frame with the specified title. import java.awt.*; public class FrameDemo { public static void main(String[] args){ win obj = new win(); } } class win { Frame myFrame; public win() { Button Button1 = new Button("Button1"); Button Button2 = new Button("Button2"); Button Button3 = new Button("Button3"); myFrame = new Frame("Demo"); myFrame.setLayout(new FlowLayout()); myFrame.add(Button1); myFrame.add(Button2); myFrame.add(Button3); myFrame.setSize(250,200); myFrame.setVisible(true); } } The Dialog Class A class that produces a dialog - a window that takes input from the user. The default layout for a dialog is BorderLayout. The Dialog class extends Window which extends Container which extends Component.

Page 87: Java Complete Manual

87

Constructors: Dialog(Frame) -- Constructs an initially invisible Dialog with an empty title. Dialog(Frame, boolean) -- Constructs an initially invisible Dialog with an empty title. Dialog(Frame, String) -- Constructs an initially invisible Dialog with a title. Dialog(Frame, String, boolean) -- Constructs an initially invisible Dialog with a title. Methods show() -- Shows the dialog. getTitle() -- Gets the title of the Dialog. setTitle(String) -- Sets the title of the Dialog. isModal() -- Returns true if the Dialog is modal. setModal(boolean) -- Specifies whether this Dialog is modal. isResizable() -- Returns true if the user can resize the dialog. setResizable(boolean) -- Sets the resizable flag. import java.awt.*; import java.awt.event.*; public class DialogDemo extends Frame{ public DialogDemo() { setTitle("MyDialog"); setSize(250,150); setVisible(true); Dialog myDialog = new Dialog(this,"Dialog"); myDialog.setSize(125,75); myDialog.show(); } public static void main(String[] args) { new DialogDemo() } } Chapter 14 Event Handling Events are organized into a hierarchy of event classes. The new model makes use of event sources and event listeners. An event source is an object that has the ability to determine when an interesting event has occurred, and to notify listener objects of the occurrence of the event. Although you as the programmer

Page 88: Java Complete Manual

88

establish the framework for such notification, the actual notification takes place automatically behind the scenes. A listener object is an instance of a class (or instance of a subclass of a class) that implements a specific listener interface. A number of listener interfaces are defined where each interface declares the methods appropriate for a specific class of events. Thus, there is natural pairing of classes of events and interface definitions. For example, there is a class of mouse events that includes most of the events normally associated with mouse action and there is a matching interface definition which is used to define a listener class for those events A listener object can be registered on a source object to be notified of the occurrence of all events of the specific class for which the listener object is designed. Once a listener object is registered to be notified of those events, the occurrence of an event defined by the specified class will automatically invoke the matching method in the listener object. The code in the body of the method is designed by the programmer to perform the desired action when the event occurs. A listener class which implements the matching interface for that event class must implement or define (provide a body for) all the methods declared in the interface. Low-level vs. Semantic Events The AWT provides two conceptual types of events: Low-Level Event Low-level event is one which represents a low-level input or window-system occurrence on a visual component on the screen. java.util.EventObject java.awt.AWTEvent java.awt.event.ComponentEvent (component resized, moved,etc.) java.awt.event.FocusEvent (component got focus, lost focus) java.awt.event.InputEvent java.awt.event.KeyEvent (component got key-press, key-release,etc.) java.awt.event.MouseEvent (component got mouse-down, mouse-move,etc.) java.awt.event.ContainerEvent java.awt.event.WindowEvent

Page 89: Java Complete Manual

89

Generally, there are corresponding Listener interfaces for each of the event classes, and corresponding interface methods for each of the different event types in each event class. Semantic Events Semantic events are defined at a higher-level to encapsulate the semantics of a user interface component's model. java.util.EventObject java.awt.AWTEvent java.awt.event.ActionEvent ("do a command") java.awt.event.AdjustmentEvent ("value was adjusted") java.awt.event.ItemEvent ("item state has changed") java.awt.event.TextEvent ("the value of the text object changed") The semantic events are not tied to specific screen-based component classes, but may apply across a set of components which implement a similar semantic model. An EventListener interface will typically have a separate method for each distinct event type that the event class represents. For example, the FocusEventListener interface defines two methods, focusGained() and focusLost(), one for each event type that the FocusEvent class represents. Listener H java.util.EventListener java.awt.event.ComponentListener java.awt.event.ContainerListener java.awt.event.FocusListener java.awt.event.KeyListener java.awt.event.MouseListener java.awt.event.MouseMotionListener java.awt.event.WindowListener ou match this up with the previous list of low-level event classes, you will see that there is a listener interface defined for each of the "leaf" classes in the hierarchy of event classes. (In fact, there are two different listener interfaces defined for the MouseEvent class. This will be discussed further at the appropriate point in time.) The semantic listener interfaces defined by the AWT are as follows: java.util.EventListener java.awt.event.ActionListener java.awt.event.AdjustmentListener java.awt.event.ItemListener

Page 90: Java Complete Manual

90

java.awt.event.TextListener There is a one-to-one correspondence between semantic listener interfaces and semantic event classes.

Page 91: Java Complete Manual

91

Example import java.awt.*; import java.awt.event.*; import java.applet.*; public class ActionDemo extends Applet implements ActionListener { String msg="initial text"; public void init(){ Button b=new Button("click me"); b.addActionListener(this); add(b); } public void paint(Graphics g){ g.drawString(msg,50,100); } public void actionPerformed(ActionEvent ae){ msg="button was clicked"; repaint(); } } Above Example by using Inner Class import java.awt.*; import java.awt.event.*; import java.applet.*; public class ActionDemo extends Applet{ String msg="initial text"; public void init(){ Button b=new Button("click me"); b.addActionListener(new MyListener()); add(b); } public void paint(Graphics g){ g.drawString(msg,50,100); } class MyListener implements ActionListener{ public void actionPerformed(ActionEvent ae){ msg="button was clicked"; repaint(); } } } Handling Mouse Events

Page 92: Java Complete Manual

92

MouseListner defines the following methods : public void mouseClicked(MouseEvent m) public void mouseClicked(MouseEvent m) public void mousePrssed(MouseEvent m) public void mouseEntered(MouseEvent m) public void mouseExited(MouseEvent m) public void mouseReleased(MouseEvent m) MouseMotionListener defines the following methods : public void mouseDragged(MouseEvent me) public void mouseMoved(MouseEvent me) example import java.awt.*; import java.applet.*; import java.awt.event.*; import java.awt.*; public class MouseDemo extends Applet implements MouseListener,MouseMotionListener { String mouseString="initial mouse string"; String mouseMotionString="initial mouse motion string"; public void init() { addMouseListener(this); addMouseMotionListener(this); } public void paint(Graphics g) { g.drawString(mouseString,50,100); g.drawString(mouseMotionString,100,200); } public void mouseClicked(MouseEvent m){ mouseString="mouse was clicked"; repaint(); } public void mousePressed(MouseEvent m){} public void mouseEntered(MouseEvent m){} public void mouseExited(MouseEvent m){} public void mouseReleased(MouseEvent m){} public void mouseMoved(MouseEvent m){} public void mouseDragged(MouseEvent m){ mouseMotionString="mouse was dragged"; repaint();

Page 93: Java Complete Manual

93

} } Handling KeyEvents The Listner interface used for handling Key events is KeyListener the methods in it are : public void keyPressed(KeyEvent e) public void keyReleased(KeyEvent e) public void keyTyped(KeyEvent e) example import java.applet.*; import java.awt.event.*; import java.awt.*; public class KeyDemo extends Applet implements KeyListener{ TextField tf; public void init(){ tf=new TextField("initial text"); tf.addKeyListener(this); add(tf); } public void keyPressed(KeyEvent e){} public void keyReleased(KeyEvent e){} public void keyTyped(KeyEvent e){ tf.setText("you pressed a key inside text box"); } } Handling Focus Events A FocusListener object is instantiated and registered to listen for focusGained() and focusLost() events on the Frame and the Label. When these events occur, the FocusListener object makes a color change on the Frame or the Label to provide a visual indication of focus gained or lost. Handling Item Events The Component Checkbox generates ItemEvent the listener interface for it is ItemListener.The method defined in this interface is public void itemStateChanged(ItemEvent i) example import java.awt.*; import java.applet.*; import java.awt.event.*; public class KeyDemo extends Applet implements ItemListener { Checkbox cb; public void init(){ cb=new Checkbox(“check box 1”);

Page 94: Java Complete Manual

94

cb.addItemListner(this); } public void itemStateChanged(ItemEvent e){ showStatus(“item event occurred”); } } import java.awt.*; import java.awt.event.*; import java.util.*; public class ItemStateDemo extends Frame implements ItemListener{ CheckboxGroup cbGrp = new CheckboxGroup(); Checkbox aButton = new Checkbox("AButton",true, cbGrp); Checkbox bButton = new Checkbox("BButton",false,cbGrp); Checkbox cButton = new Checkbox("CButton",false,cbGrp); TextField tbox = new TextField(50); public static void main(String[] args){ new ItemStateDemo(); } ItemStateDemo(){ aButton.addItemListener(this); bButton.addItemListener(this); cButton.addItemListener(this); Checkbox theCheckbox = new Checkbox("Check Box"); theCheckbox.addItemListener(this); this.add(aButton); this.add(bButton); this.add(cButton); this.add(theCheckbox); this.add(tbox); this.setLayout(new FlowLayout()); this.setSize(350,100); this.setTitle("Demo”); this.setVisible(true); } public void itemStateChanged(ItemEvent e){ String txt = "Item: " + e.getItem(); txt = " " + txt + "State Change: " + e.getStateChange(); txt = " " + txt + "State: " + ((Checkbox)e.getSource()).getState(); tbox.setText(txt); } } Handling Adjustment Event

Page 95: Java Complete Manual

95

To create a listener object for a Scrollbar you implement an AdjustmentListener interface. The method declared in the AdjustmentListener interface receives an AdjustmentEvent object as a parameter. This is one of the semantic events similar to ActionEvent, ItemEvent, and TextEvent. The AdjustmentListener interface declares only one method: public abstract void adjustmentValueChanged(AdjustmentEvent e) The adjustmentValueChanged() method is invoked when the value of the adjustable object (the Scrollbar object in this case) has changed. import java.awt.*; import java.awt.event.*; class AdjustDemo { public static void main(String[] args){ WIN wind = new WIN(); } } class WIN extends Frame { Scrollbar myScrollbar; TextField tbox; int bubbleWidth; WIN(){ myScrollbar = new Scrollbar(Scrollbar.HORIZONTAL,50, 20,0,100); myScrollbar.setBlockIncrement(15); myScrollbar.setUnitIncrement(2); tbox = new TextField("Initial Text"); tbox.setEditable(false); add("South", myScrollbar); add("North", tbox); setSize(300,75); setVisible(true); myScrollbar.addAdjustmentListener(new MyListener()); } class MyListener implements AdjustmentListener{ public void adjustmentValueChanged(AdjustmentEvent e){ tbox.setText("Value = " + myScrollbar.getValue()); } } } Handling Window Events import java.awt.*; import java.awt.event.*;

Page 96: Java Complete Manual

96

public class WinEventDemo { public static void main(String[] args){ WIN obj = new WIN(); } } class WIN extends Frame { public WIN(){ setSize(300,200); setTitle("Title"); addWindowListener(new WLIS()); setVisible(true); } class WLIS implements WindowListener { public void windowClosed(WindowEvent e){ System.out.println("Window Closed.."); } public void windowIconified(WindowEvent e){ System.out.println("Window Iconified..."); } public void windowOpened(WindowEvent e){ System.out.println("Window Opened... "); } public void windowClosing(WindowEvent e){ System.out.println("WindowClosing..."); dispose(); System.exit(0); } public void windowDeiconified(WindowEvent e){ System.out.println("Window Deiconified..."); } public void windowActivated(WindowEvent e){ System.out.println("Window Activated..."); } public void windowDeactivated(WindowEvent e){ System.out.println("Window Deactivated..."); } } } Adapters Many EventListener interfaces are designed to listen to multiple event classes. For example, . the MouseListener listens to mouse-

Page 97: Java Complete Manual

97

down, mouse-up, mouse-enter, etc. The interface declares a method for each of these subtypes. When you implement an interface, you are required to define all of the methods that are declared in the interface, even if you define them with empty methods. In some cases, the requirement to define all the methods declared in an interface can be burdensome. For this reason the AWT provides a set of abstract adapter classes which match up with the defined interfaces. Each adapter class implements one interface and defines all of the methods declared by that interface as empty methods, thus satisfying the requirement to define all of the methods. You can then define your listener classes by extending the adapter classes instead of implementing the listener interfaces.. This allows you the freedom to override only those methods of the interface which interest you. Adapter Classes java.awt.event.ComponentAdapter java.awt.event.FocusAdapter java.awt.event.KeyAdapter java.awt.event.MouseAdapter java.awt.event.MouseMotionAdapter java.awt.event.WindowAdapter Handling Component Events If you instantiate an object of type ComponentListener and register that object on an object that is a subclass of the Component class, methods of the listener object will be invoked whenever the object is hidden, moved, resized, or shown. import java.awt.*; import java.awt.event.*; class Event34 extends Frame implements ComponentListener{ public static void main(String[] args){ new Event34(); } public Event34(){ this.addComponentListener(this); this.setSize(350,100); this.setTitle("Demo"); this.setVisible(true); this.setVisible(false); this.setVisible(true);

Page 98: Java Complete Manual

98

this.addWindowListener( new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } } ); } public void componentResized(ComponentEvent e){ System.out.println("Resized\n" + e.getSource()); } public void componentMoved(ComponentEvent e){ System.out.println("Moved\n" + e.getSource()); } public void componentShown(ComponentEvent e){ System.out.println("Shown\n" + e.getSource()); } public void componentHidden(ComponentEvent e){ System.out.println("Hidden\n" + e.getSource()); } } Handling Text Event If you instantiate an object of type TextListener and register that object on an object that has an addTextListener() method, the textValueChanged() method of the listener object will be invoked whenever the text contents of the source object changes. import java.awt.*; import java.awt.event.*; import java.util.*; public class TextDemo extends Frame implements TextListener{ public static void main(String[] args){ new TextDemo(); } TextDemo(){ TextField myTextField = new TextField("Initial String",30); myTextField.addTextListener(this); this.add(myTextField); this.setLayout(new FlowLayout()); this.setSize(350,100); this.setTitle("Demo"); this.setVisible(true);

Page 99: Java Complete Manual

99

addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0);}}); } public void textValueChanged(TextEvent e){ System.out.println(((TextField)e.getSource()).getText()); } } Positioning The Component class provides the methods setBounds(int,int,int,int) and setBounds(Rectangle) that allow you to specify the location and size of a component in absolute coordinates measured in pixels. import java.awt.*; import java.awt.event.*; public class PosDemo { public static void main(String[] args){ WIN win = new WIN(); } } class WIN { public WIN(){ Button myButton = new Button("Button"); myButton.setBounds(new Rectangle(25,50,100,75)); Label myLabel = new Label("Positioning Demo...."); myLabel.setBounds(new Rectangle(100,100,100,75)); myLabel.setBackground(Color.yellow); Frame myFrame = new Frame("Demo"); myFrame.setLayout(null); myFrame.add(myButton); myFrame.add(myLabel); myFrame.setSize(250,150); myFrame.setVisible(true); } } Menus The inheritance hierarchy for menus is as shown below : java.lang.Object | +----MenuShortcut | +----java.awt.MenuComponent | +----java.awt.MenuBar

Page 100: Java Complete Manual

100

| +----java.awt.MenuItem | +----java.awt.Menu | +----java.awt.CheckboxMenuItem | +----java.awt.PopupMenu Menu Classes MenuComponent Class - Super class of all menu related components. MenuShortcut Class - Represents a keyboard accelerator for a MenuItem. MenuItem Class - Represents a choice in a menu. Menu Class - A component of a menu bar. MenuBar Class - Encapsulates the platform's concept of a menu bar bound to a Frame. PopupMenu Class - Implements a menu which can be dynamically popped up within a component. CheckboxMenuItem Class - Produces a checkbox that represents a choice in a menu. Menu Class The Menu class is used to construct a pull-down menu. Constructors Menu() -- Constructs a new Menu with an empty label. Menu(String) -- Constructs a new Menu with the specified label. Menu(String, boolean) -- Constructs a new Menu with the specified label. Methods add(MenuItem) -- Adds the specified item to this menu. add(String) -- Adds an item with the specified label to this menu. addSeparator() -- Adds a separator line, or a hyphen, to the menu at the current position. getItem(int) -- Returns the item located at the specified index of this menu. getItemCount() -- Returns the number of elements in this menu. insert(MenuItem, int) -- Inserts the MenuItem to this menu at the specified position. insert(String, int) -- Inserts an item with the specified label to this menu at the specified position. insertSeparator(int) -- Inserts a separator at the specified position

Page 101: Java Complete Manual

101

remove(int) -- Deletes the item from this menu at the specified index. removeAll() -- Deletes all items from this menu. MenuItem Class This class is used to instantiate objects which can become the choices in a menu. Constructors MenuItem() -- Constructs a new MenuItem with an empty label and no keyboard shortcut. MenuItem(String) -- Constructs a new MenuItem with the specified label and no keyboard shortcut. MenuItem(String, MenuShortcut) -- Create a MenuItem with an associated keyboard shortcut. Methods addActionListener(ActionListener) -- Adds the specified action listener to receive action events from this menu item. removeActionListener(ActionListener) -- Removes the specified action listener so it no longer receives action events from this menu item. setEnabled(boolean) -- Sets whether or not this menu item can be chosen. isEnabled() -- Checks whether the menu item is enabled. MenuBar Class Constructor MenuBar() -- Creates a new menu bar. Methods add(Menu) -- Adds the specified menu to the menu bar. getHelpMenu() -- Gets the help menu on the menu bar. remove(int) -- Removes the menu located at the specified index from the menu bar. remove(MenuComponent) -- Removes the specified menu from the menu bar. setHelpMenu(Menu) -- Sets the help menu to the specified menu on the menu bar. MenuShortcut Class

Page 102: Java Complete Manual

102

This class is used to instantiate an object which represents a keyboard accelerator for a MenuItem. Constructor MenuShortcut(int) -- Constructs a new MenuShortcut for the specified key. MenuShortcut(int, boolean) -- Constructs a new MenuShortcut for the specified key. All of the shortcuts automatically require the user to hold down the Ctrl key while pressing another key. The boolean parameter in the second version of the constructor specifies whether or not the user will also have to hold down the Shift key as well (true means the Shift key is required). import java.awt.*; import java.awt.event.*; public class MenuDemo { public static void main(String[] args){ MyMenu mnu = new MyMenu(); } } class MyMenu { public MyMenu(){ MenuShortcut myShortcut = new MenuShortcut(KeyEvent.VK_K,true); MenuItem M1 = new MenuItem("First Item.. ",myShortcut); MenuItem M2 = new MenuItem("Second Item.."); MenuItem M3 = new MenuItem("First Item ..."); MenuItem M4 = new MenuItem("Second Item...."); MenuItem M5 = new MenuItem("Third Item.."); MyMenuListener myMenuListener = new MyMenuListener(); M1.addActionListener(myMenuListener); M2.addActionListener(myMenuListener); M3.addActionListener(myMenuListener); M4.addActionListener(myMenuListener); M5.addActionListener(myMenuListener); Menu menu1 = new Menu("Menu 1"); menu1.add(M1); menu1.add(M2); Menu menu2 = new Menu("Menu 2"); menu2.add(M3); menu2.add(M4); menu2.add(M5); MenuBar menuBar = new MenuBar();

Page 103: Java Complete Manual

103

menuBar.add(menu1); menuBar.add(menu2); Frame myFrame = new Frame("Demo"); myFrame.setMenuBar(menuBar); myFrame.setSize(250,100); myFrame.setVisible(true); myFrame.addWindowListener(new Terminate()); } } class MyMenuListener implements ActionListener{ public void actionPerformed(ActionEvent e){ System.out.println(e.getSource()); } } class Terminate extends WindowAdapter{ public void windowClosing(WindowEvent e){ System.exit(0); } } CheckboxMenuItem Class Produces a checkbox that represents a choice in a menu. Constructors CheckboxMenuItem() -- Creates a checkbox menu item with an empty label, initially set to off (false state). CheckboxMenuItem(String) -- Creates the checkbox item with the specified label, initially set to off (false state). CheckboxMenuItem(String, boolean) -- Creates a checkbox menu item with the specified label and state. Methods addItemListener(ItemListener) -- Adds the specified item listener to receive item events from this checkbox menu item. getSelectedObjects() -- Returns an array containing the checkbox menu item label or null if the checkbox is not selected. getState() -- Returns the state of this MenuItem. removeItemListener(ItemListener) -- Removes the specified item listener so it no longer receives item events from this checkbox menu item. setState(Boolean) -- Sets the state of this MenuItem if it is a Checkbox. PopupMenu Class Implements a menu which can be dynamically popped within a component.

Page 104: Java Complete Manual

104

Constructors PopupMenu() -- Creates a new popup menu. PopupMenu(String) -- Creates a new popup menu with the specified name. import java.awt.*; import java.awt.event.*; public class MenuDemo { public static void main(String[] args){ MyMenu mnu = new MyMenu(); } } class MyMenu { public MyMenu(){ CheckboxMenuItem M1 = new CheckboxMenuItem("First Item"); CheckboxMenuItem M2 = new CheckboxMenuItem("Second Item"); CheckboxMenuItem M3 = new CheckboxMenuItem("Third Item"); M1.addItemListener(new CheckBoxMenuProcessor()); M2.addItemListener(new CheckBoxMenuProcessor()); M3.addItemListener(new CheckBoxMenuProcessor()); PopupMenu myPopupMenu = new PopupMenu("Popup Menu"); myPopupMenu.add(M1); myPopupMenu.add(M2); myPopupMenu.add(M3); Frame myFrame = new Frame("Demo"); myFrame.addMouseListener(new MouseProcessor(myFrame,myPopupMenu)); myFrame.add(myPopupMenu); myFrame.setSize(250,100); myFrame.setVisible(true); myFrame.addWindowListener(new Terminate()); } } class MouseProcessor extends MouseAdapter{ Frame aFrame; PopupMenu aPopupMenu; MouseProcessor(Frame inFrame, PopupMenu inPopupMenu){ aFrame = inFrame; aPopupMenu = inPopupMenu; } public void mousePressed(MouseEvent e){ aPopupMenu.show(aFrame,e.getX(),e.getY()); } } class CheckBoxMenuProcessor implements ItemListener{

Page 105: Java Complete Manual

105

public void itemStateChanged(ItemEvent e){ System.out.println(e.getSource()); } } class Terminate extends WindowAdapter{ public void windowClosing(WindowEvent e){ System.exit(0); } } Chapter 13 Swing Swing is the name given to a new set of lightweight components developed by JavaSoft to supplement and possibly replace the components in the AWT. With the exception of top-level containers, Swing components are developed completely using Java and don't depend on the peer component rendering provided by the operating system. The components are not rendered on the screen by the operating system, the look and feel of a component does not change as the application or applet is executed on different platforms running under different operating systems. It is possible to cause Swing components to mimic the look and feel of a specific platform no matter what platform the program is running on. This is known as pluggable look and feel. Swing comes with three different PLAF implementations: Motif Windows 9x/NT Metal (JavaSoft) Swing provides a number of components that are not contained in the AWT (progress bars, tool tips, trees, combo boxes, etc.). Lightweight Components The ability to create lightweight components is a new feature of JDK 1.1. This capability was added to deal with some problems under JDK 1.0 Specifically, creating new components in JDK 1.0 requires subclassing Canvas or Panel. This places each new component in its own opaque window based on the native components of the platform. Because native windows are opaque, they can't be used to implement transparent regions. Also native windows are handled

Page 106: Java Complete Manual

106

differently across different platforms so the view of a user interface may differ from one platform to the next. The ability to implement lightweight components in JDK 1.1 is referred to as the Lightweight UI Framework. The Lightweight UI Framework makes it possible to extend the java.awt.Component class and the java.awt.Container class. This in turn makes it possible to create components that are not associated with native opaque windows. These lightweight components mesh into the different AWT models allowing you to do layout, paint, handle events, etc., with no additional APIs required. Lightweight components can have transparent areas. This is accomplished by simply not rendering those areas needing transparency in the overridden paint() method. The lightweight component requires no native data-structures or peer classes. There is no native code required to process lightweight components. Thus, the handling of lightweight components is completely implemented in java code. This should lead to consistency across platforms. You can mix lightweight components with the existing heavyweight components. For example, lightweight components can be made children of heavyweight containers or heavyweight components can be made children of lightweight containers Heavyweight and lightweight components can be mixed within containers. Note however, that the heavyweight component will always be "on top" if it overlaps a lightweight component. almost all Swing components behave as containers. This means that they can contain other things, including other Swing components. JApplet JApplet inherits from Applet- init, start, stop, etc. unchanged. Main differences Components go in the "content pane", not directly in the frame. Changing other properties (layout manager, background color, etc.) also apply to the content pane. Access content pane via getContentPane.Default layout manager is BorderLayout (like Frame and JFrame), not FlowLayout (like Applet). This is really the layout manager of the content pane. You get Java (Metal) look by default, so you have to explicitly switch if you want native look. import java.awt.*; import javax.swing.*;

Page 107: Java Complete Manual

107

public class JAppletDemo extends JApplet { public void init() { WindowUtilities.setNativeLookAndFeel(); Container content = getContentPane(); content.setBackground(Color.white); content.setLayout(new FlowLayout()); content.add(new JButton("Button 1")); content.add(new JButton("Button 2")); content.add(new JButton("Button 3")); } } JFrame Main differences compared to Frame: JFrames close automatically when you click on the close button (unlike AWT Frames). However, closing the last JFrame does not result in your program exiting Java. So your "main" JFrame still needs a WindowListener.You get Java (Metal) look by default, so you have to explicitly switch if you want native look. import java.awt.*; import javax.swing.*; public class JFrameExample { public static void main(String[] args) { WindowUtilities.setNativeLookAndFeel(); JFrame f = new JFrame("Demo"); f.setSize(400, 150); Container content = f.getContentPane(); content.setBackground(Color.white); content.setLayout(new FlowLayout()); content.add(new JButton("Button 1")); content.add(new JButton("Button 2")); content.add(new JButton("Button 3")); f.setVisible(true); } } Internal Frames Windows products such as Microsoft PowerPoint, Excel are Multiple Document Interface (MDI) applications. This means that there is one large "desktop" pane that holds all other windows. The other windows can be iconified (minimized) and moved around within this desktop pane, but not moved outside it. Furthermore, minimizing the desktop pane hides all the windows it contains as well. Swing introduced MDI support by means of two main classes. The first is JDesktopPane, and serves as a holder for the other

Page 108: Java Complete Manual

108

windows. The second is JInternalFrame, which acts mostly like a JFrame, except that it is constrained to stay inside the JDesktopPane. import java.awt.*; import java.awt.event.*; import javax.swing.*; class IFrames extends JFrame { public static void main(String[] args) { new IFrames(); } public IFrames() { super("Multiple Document Interface"); Container content = getContentPane(); content.setBackground(Color.white); JDesktopPane desktop = new JDesktopPane(); desktop.setBackground(Color.white); content.add(desktop, BorderLayout.CENTER); setSize(450, 400); for(int i=0; i<5; i++) { JInternalFrame frame = new JInternalFrame(("Internal Frame " + i), true, true, true, true); frame.setLocation(i*50+10, i*50+10); frame.setSize(200, 150); frame.setBackground(Color.white); desktop.add(frame); frame.moveToFront(); } setVisible(true); } } JLabel JLabel is used exactly like Label. A JLabel can have an image instead of or in addition to the text. JButton JButtons are very similar to Button. Events are normally handled just as with a Button, you attach an ActionListener . The new feature is the ability to associate images with buttons. Swing introduced a utility class called ImageIcon that lets you very easily specify an image file (jpeg or GIF, including animated GIFs). Many Swing controls allow the inclusion of icons. The simplest way to associate an image with a JButton is to pass the ImageIcon to the constructor, either in place of the text or in addition to it.You

Page 109: Java Complete Manual

109

can also easily set keyboard mnemonics via setMnemonic. This results in the specified character being underlined on the button, and also results in ALT-char activating the button. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JButtonDemo extends JFrame { public static void main(String args[]) { JButtonDemo demoFrame = new JButtonDemo(); } JButtonDemo() { this.setTitle("Demo"); this.getContentPane().setLayout(new FlowLayout()); this.getContentPane().add(new JLabel("JLabel Demo")); JButton f = new JButton("JButton"); f.setToolTipText("JButton"); this.getContentPane().add(f); this.setSize(400,280); this.setVisible(true); } } JPanel You use a JPanel exactly the same way as you would a Panel. New feature is the ability to assign borders to JPanels. Swing gives you seven basic border types: titled, etched, beveled (regular plus a "softer" version), line, matte, compound, and empty. You can also create your own, of course. You assign a Border via the setBorder method, and create the Border by calling the constructors directly. JSlider You create a JSlider in a similar manner to Scrollbar: the zero-argument constructor creates a horizontal slider with a range from 0 to 100 and an initial value of 50. You can also supply the orientation (via JSlider.HORIZONTAL or JSlider.VERTICAL) and the range and initial value to the constructor. You handle events by attaching a ChangeListener. Its stateChanged method normally calls getValue to look up the current JSlider value. Swing sliders can have major and minor tick marks. Turn them on via setPaintTicks(true), then specify the tick spacing via setMajorTickSpacing and setMinorTickSpacing. If you want users to only be able to choose values that are at the tick marks, call setSnapToTicks(true). Turn on labels via setPaintLabels(true).

Page 110: Java Complete Manual

110

import java.awt.*; import javax.swing.*; public class JSliderDemo extends JFrame { public static void main(String[] args) { new JSliderDemo(); } public JSliderDemo() { super("Using JSlider"); Container content = getContentPane(); content.setBackground(Color.white); JSlider slider3 = new JSlider(); slider3.setBorder(BorderFactory.createTitledBorder("JSlider with Tick Marks & Labels")); slider3.setMajorTickSpacing(20); slider3.setMinorTickSpacing(5); slider3.setPaintTicks(true); slider3.setPaintLabels(true); content.add(slider3, BorderLayout.SOUTH); pack(); setVisible(true); } } JColorChooser JColorChooser lets the user interactively select a Color. The default behavior is to present a dialog box containing a tabbed pane letting the user choose via swatches, HSB values, or RGB values. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JColorChooserTest extends JFrame implements ActionListener { public static void main(String[] args) { new JColorChooserTest(); } public JColorChooserTest() { super("Using JColorChooser"); Container content = getContentPane(); content.setBackground(Color.white); content.setLayout(new FlowLayout()); JButton colorButton = new JButton("Choose Background Color"); colorButton.addActionListener(this); content.add(colorButton);

Page 111: Java Complete Manual

111

setSize(300, 100); setVisible(true); } public void actionPerformed(ActionEvent e) { Color bgColor = JColorChooser.showDialog(this,"Choose Background Color",getBackground()); if (bgColor != null) getContentPane().setBackground(bgColor); } } JCheckBox Similar to Checkbox. You can attach either an ActionListener or an ItemListener to monitor events. You can supply an icon to replace the normal square with a check in it (via setIcon), but if you do, be sure to also supply an icon to be displayed when the checkbox is selected (setSelectedIcon). JRadioButton A JRadioButton is similar to a Checkbox when the Checkbox is inside a CheckboxGroup. Create several JRadioButtons, add them to a ButtonGroup, and also add them to a Container. Like JCheckBox, you can attach either an ActionListener or an ItemListener. JFileChooser This control lets users interactively select a filename by browsing directories. import java.io.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.filechooser.*; public class FileChooserDemo extends JFrame { static private final String newline = "\n"; public FileChooserDemo() { super("FileChooserDemo"); final JFileChooser fc = new JFileChooser(); ImageIcon openIcon = new ImageIcon("images/open.gif"); JButton openButton = new JButton("Open a File...", openIcon); JPanel buttonPanel = new JPanel(); buttonPanel.add(openButton); Container contentPane = getContentPane();

Page 112: Java Complete Manual

112

contentPane.add(buttonPanel, BorderLayout.NORTH); openButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int returnVal = fc.showOpenDialog(FileChooserDemo.this); } }); } public static void main(String[] args) { JFrame frame = new FileChooserDemo(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.pack(); frame.setVisible(true); } } JTextField The basic use of this widget works almost exactly like the AWT"s TextField, including size options to the constructor. You can set the text alignment via setHorizontalAlignment; supply JTextField.LEFT, JTextField.CENTER, or JTextField.RIGHT. import java.awt.*; import java.awt.event.*; import javax.swing.*; class JFCDemo extends JFrame implements ActionListener{ JButton jButton = new JButton("JButton"); JTextField jTextField = new JTextField("JTextField"); JLabel jLabel = new JLabel("JLabel"); JFCDemo(){ jButton.addActionListener(this); jTextField.addActionListener(this); getContentPane().setLayout(new FlowLayout()); getContentPane().add(jButton); getContentPane().add(jTextField); getContentPane().add(jLabel); setTitle("Demo"); setSize(300,100); setVisible(true); this.addWindowListener( new WindowAdapter(){

Page 113: Java Complete Manual

113

public void windowClosing(WindowEvent e){ System.exit(0); } } ); } public static void main(String args[]) { new JFCDemo(); } public void actionPerformed(ActionEvent e){ jLabel.setText(e.getActionCommand()); } } JTextArea This is very similar to the AWT TextArea, but unlike TextArea it does not directly have scrolling behavior. Instead, like other Swing components, scrolling behavior is obtained by wrapping it in a JScrollPane. Second, JTextArea is only for simple text, but Swing also provides JTextPane and JEditorPane, which support much more complex options. JLlist Jlist allows the user to select one or more objects from a list. JComboBox JComboBox is similar to List . It is a combination of a TextField and rop down List that lets the use either type in a value or select it from a list. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ComboBoxDemo extends JPanel { String[] crsStrings = { "Oracle", "Visual Basic", "Java", "Windows", "Linux" }; JComboBox crsList = new JComboBox(crsStrings); JLabel jlb = new JLabel("Initial Text"); public ComboBoxDemo() { crsList.setSelectedIndex(4);

Page 114: Java Complete Manual

114

petList.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JComboBox cb = (JComboBox)e.getSource(); String crsName = (String)cb.getSelectedItem(); jlb.setText(crsName); } }); setLayout(new BorderLayout()); add(petList, BorderLayout.NORTH); add(jlb, BorderLayout.SOUTH); } public static void main(String s[]) { JFrame frame = new JFrame("ComboBoxDemo"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); frame.setContentPane(new ComboBoxDemo()); frame.setSize(300,300); frame.setVisible(true); } } Chapter 14 Threads One of the characteristics that makes Java a powerful programming language is its support of multithreaded programming as an integrated part of the language. Multithreaded programming is an essential aspect of programming in Java. Multitasking Refers to a computer's ability to perform multiple jobs concurrently. For the most part, modern desktop operating systems like Windows 9x or OS/2 have the ability to run two or more programs at the same time. While you are using Netscape to download a big file, you can be playing Solitaire in a different window; both programs are running at the same time.

Page 115: Java Complete Manual

115

Multithreading Multithreaded programs are similar to the single-threaded programs that you have been studying. They differ only in the fact that they support more than one concurrent thread of execution-that is, they are able to simultaneously execute multiple sequences of instructions. Each instruction sequence has its own unique flow of control that is independent of all others. These independently executed instruction sequences are known as threads. If your computer has only a single cpu, you might be wondering how it can execute more than one thread at the same time. In single-processor systems, only a single thread of execution occurs at a given instant. The cpu quickly switches back and forth between several threads to create the illusion that the threads are executing at the same time. Single-processor systems support logical concurrency, not physical concurrency. Logical concurrency is the characteristic exhibited when multiple threads execute with separate, independent flows of control. On multiprocessor systems, several threads do, in fact, execute at the same time, and physical concurrency is achieved. The important feature of multithreaded programs is that they support logical concurrency, not whether physical concurrency is actually achieved. Java Thread Support Java's multithreading support is centered around the java.lang.Thread class. The Thread class provides the capability to create objects of class Thread, each with its own separate flow of control. Java provides two approaches to creating threads. In the first approach, you create a subclass of class Thread and override the run() method to provide an entry point into the thread's execution. When you create an instance of your Thread subclass, you invoke its start() method to cause the thread to execute as an independent sequence of instructions. The start() method is inherited from the Thread class. It initializes the Thread object using your operating system's multithreading capabilities and invokes the run() method. Java's other approach to creating threads does not limit the location of your Thread objects within the class hierarchy. In this approach, your class implements the java.lang.Runnable interface. The Runnable interface consists of a single method, the run() method, which must be overridden by your class. The run() method provides an entry point into your thread's execution. In order to run an object of your class as an independent thread, you pass it as an argument to a constructor of class Thread. Constructors

Page 116: Java Complete Manual

116

public Thread(); public Thread(Runnable target); public Thread(Runnable target, String name); public Thread(String name); Thread Methods getPriority() gets priority of thread interrupt() wakes sleep/waiting thread via InterruptedException sets interrupted flag on non-sleeping thread resume() restarts suspended thread run() body of thread setPriority() sets priority of thread sleep(msecs) makes thread sleep for msecs milliseconds start() initiates thread by executing its run() method stop() kills thread suspend() temporarily suspends thread until resumed yield() gives way to equal priority threads on scheduling Thread States Threads can be in one of four states: New When you create a thread with the “new” operator. Runnable Once you invoke the start method, the thread is runnable. Blocked Call to “sleep()” In a blocking operation In a call to “wait()” Attempt to acquire a resource that’s locked Dead Natural death Uncaught exceptions can terminate the “run()” method

Page 117: Java Complete Manual

new

runnable

dead

start

run exits

blocked

sleep

done sleeping

wait

notify

block on I/O

I/O complete

117

Page 118: Java Complete Manual

118

Example 1 import java.awt.Graphics; import java.awt.Font; import java.util.Date; public class DigitalClock extends java.applet.Applet implements Runnable { Font theFont = new Font("TimesRoman",Font.BOLD,24); Date theDate; Thread runner; public void start() { if (runner == null) { runner = new Thread(this); runner.start(); } } public void stop() { if (runner != null) { runner.stop(); runner = null; } } public void run() { while (true) { theDate = new Date(); repaint(); try { Thread.sleep(1000); } catch (InterruptedException e) { } } } public void paint(Graphics g) { g.setFont(theFont); g.drawString(theDate.toString(),10,50); } } Example 2 import java.awt.*;

Page 119: Java Complete Manual

119

import java.awt.event.*; import java.applet.*; public class Runner extends Applet implements Runnable { public static final int number = 5; public Button[] button = new Button[number]; public TextField[] output = new TextField[number]; public Thread[] thread = new Thread[number]; public boolean[] suspend = new boolean[number]; public void init() { RunnerButtonListener bList = new RunnerButtonListener(this); setLayout(new GridLayout(number, 2)); for (int i=0; i<number; i++) { output[i] = new TextField(4); button[i] = new Button("suspend/resume"); button[i].addActionListener(bList); add(output[i]); add(button[i]); } } public void start() { for (int i=0; i<number; i++) { thread[i] = new Thread(this, i + ""); thread[i].start(); } } public void stop() { for (int i=0; i<number; i++) thread[i].stop(); } public void run() { while ( true ) { try { Thread.sleep((int)( Math.random()*300 )); } catch ( InterruptedException e ) { e.printStackTrace(); } for (int i=0; i<number; i++) if ( Thread.currentThread().getName().equals(i + "") ) output[i].setText(i + ": " + Math.random()*10 + " "); }

Page 120: Java Complete Manual

120

} } Threads and Shared data One of the strengths of the Java programming language is its support for multithreading at the language level. Much of this support centers on coordinating access to data shared among multiple threads. Inside the Java virtual machine, each thread is awarded a Java stack, which contains data no other thread can access, including the local variables, parameters, and return values of each method the thread has invoked. The data on the stack is limited to primitive types and object references. In the JVM, it is not possible to place the image of an actual object on the stack. All objects reside on the heap. There is only one heap inside the JVM, and all threads share it. The heap contains nothing but objects. There is no way to place a solitary primitive type or object reference on the heap these things must be part of an object. Arrays reside on the heap, including arrays of primitive types, but in Java, arrays are objects too. Besides the Java stack and the heap, the other place data may reside in the JVM is the method area, which contains all the class or static variables used by the program. The method area is similar to the stack in that it contains only primitive types and object references. Unlike the stack, however, all threads share the class variables in the method area. Object and class locks As described above, two memory areas in the Java virtual machine contain data shared by all threads. These are: The heap, which contains all objects The method area, which contains all class variables If multiple threads need to use the same objects or class variables concurrently, their access to the data must be properly managed. Otherwise, the program will have unpredictable behavior. To coordinate shared data access among multiple threads, the Java virtual machine associates a lock with each object and class. A lock is like a privilege that only one thread can "possess" at any one time. If a thread wants to lock a particular object or class, it asks the JVM. At some point after the thread asks the JVM for a lock maybe very soon, maybe later, possibly never -- the JVM gives the lock to the thread. When the thread no longer needs the lock, it returns it to the JVM. If another thread has requested the same lock, the JVM passes the lock to that thread.

Page 121: Java Complete Manual

121

Class locks are actually implemented as object locks. When the JVM loads a class file, it creates an instance of class java.lang.Class. When you lock a class, you are actually locking that class's Class object. Threads need not obtain a lock to access instance or class variables. If a thread does obtain a lock, however, no other thread can access the locked data until the thread that owns the lock releases it. Monitors The JVM uses locks in conjunction with monitors. A monitor is basically a guardian in that it watches over a sequence of code, making sure only one thread at a time executes the code.Each monitor is associated with an object reference. When a thread arrives at the first instruction in a block of code that is under the watchful eye of a monitor, the thread must obtain a lock on the referenced object. The thread is not allowed to execute the code until it obtains the lock. Once it has obtained the lock, the thread enters the block of protected code. When the thread leaves the block, no matter how it leaves the block, it releases the lock on the associated object. Multiple locks A single thread is allowed to lock the same object multiple times. For each object, the JVM maintains a count of the number of times the object has been locked. An unlocked object has a count of zero. When a thread acquires the lock for the first time, the count is incremented to one. Each time the thread acquires a lock on the same object, a count is incremented. Each time the thread releases the lock, the count is decremented. When the count reaches zero, the lock is released and made available to other threads. Synchronized blocks In Java language terminology, the coordination of multiple threads that must access shared data is called synchronization. class KitchenSync { private int[] intArray = new int[10]; void reverseOrder() { synchronized (this) { int halfWay = intArray.length / 2; for (int i = 0; i < halfWay; ++i) { int upperIndex = intArray.length - 1 - i; int save = intArray[upperIndex];

Page 122: Java Complete Manual

122

intArray[upperIndex] = intArray[i]; intArray[i] = save; } } } } Thread Coordination Threads are often interdependent-one thread may depend on another thread to complete an operation or to service a request.There may be cases where one of the created thread requires data from another. It becomes essential to check every few seconds, whether the second thread has produced the required information or not. wait() and notify() Threads are usually coordinated using a concept known as a condition, or a condition variable. A condition is a logical statement that must hold true in order for a thread to proceed; if the condition does not hold true, the thread must wait for the condition to become true before continuing. check to see whether the desired condition is already true. If it is true, there is no need to wait. If the condition is not yet true, call the wait() method. When wait() ends, recheck the condition to make sure that it is now true. wait() method waits indefinitely on another thread of execution until it receives a noty() or notifyAll() message. notify () method wakes up a single thread waiting on the Objects’s monitor. notifyAll() method wakes up all threads waiting on the Object’s monitor. public class Producer implements Runnable { private Buffer buffer; public Producer(Buffer b) { buffer = b; } public void run() { for (int i=0; i<250; i++) { buffer.put((char)('A' + (i%26))); }

Page 123: Java Complete Manual

123

} } public class Consumer implements Runnable { private Buffer buffer; public Consumer(Buffer b) { buffer = b; } public void run() { for (int i=0; i<250; i++) { System.out.println(buffer.get()); } } } public class Buffer { private char[] buf; // buffer storage private int last; // last occupied position public Buffer(int sz) { buf = new char[sz]; last = 0; } public boolean isFull() { return (last == buf.length); } public boolean isEmpty() { return (last == 0); } public synchronized void put(char c) { while(isFull()) { // wait for room to put stuff try { wait(); } catch(InterruptedException e) { } } buf[last++] = c; notify(); } public synchronized char get() { while(isEmpty()) { // wait for stuff to read try { wait(); } catch(InterruptedException e) { } } char c = buf[0]; System.arraycopy(buf, 1, buf, 0, --last); notify(); return c; } }

Page 124: Java Complete Manual

124

Page 125: Java Complete Manual

125

Chapter 15 Java Networking In order for two or more computers connected to a network to be able to exchange data in an orderly manner, they must adhere to a mutually acceptable communication protocol. The protocol defines the rules by which they communicate. For example, the HTTP protocol defines how web browsers and servers communicate and the SMTP protocol defines how email is transferred. IP IP, which stands for Internet Protocol, is the protocol that will be involved to move our data between a client and a server. IP is a network protocol that moves packets of data from a source to a destination TCP The Transmission Control Protocol (TCP) was added to IP to give each end of a connection the ability to acknowledge receipt of IP packets and to request retransmission of lost packets. Also TCP makes it possible to put the packets back together at the destination in the same order that they were sent. The two work together to provide a reliable method of encapsulating a message into data packets, sending the packets to a destination, and reconstructing the message from the packets at the destination. UDP Sometimes it may not be important that all the packets arrive at the destination or that they arrive in the proper order. Further, sometimes, you may not want to incur the time delays and overhead cost associated with those guarantees. The User Datagram Protocol (UDP) is available to support this type of operation. UDP is often referred to as an unreliable protocol because there is no guarantee that a series of packets will arrive in the right order, or that they will arrive at all. IP Addresses Every computer attached to an IP network has a unique four-byte (32-bit) address. Domain Names

Page 126: Java Complete Manual

126

Humans remember words and names better. Therefore, most IP addresses have a corresponding name known as a domain name. The Domain Name System (DNS) was developed to translate between IP addresses and domain names. Whenever you log your browser onto the internet and attempt to connect to a server using its domain name, the browser first communicates with a DNS server to learn the corresponding numeric IP address. The numeric IP address is encapsulated into the data packets and used by the internet protocol to route those packets from the source to the destination. Ports Each server computer that you may connect to will be logically organized into ports. These are not physical ports in the sense of the printer port on the back of your computer. Rather, they are simply logical sub-addresses which you provide to the operating system on the server so that the operating system can cause the appropriate server software to "answer the call." Theoretically, there are 65,535 available ports. Port numbers between 1 and 1023 are predefined to be used for certain standard services. For example, if you want to connect with server software that communicates using the HTTP protocol, you would normally connect to port 80 on the server of interest. Similarly, if you want to connect to a port that will tell you the time, you should connect to port 13. If you want to connect to a port that will simply echo whatever you send to it (usually for test purposes), you should connect to port 7. We will write Java applications that connect to all of these ports The InetAddress class Provides objects that you can use to manipulate and deal with IP addresses and domain names. The class provides several static methods that return an object of type InetAddress. Methods static getByName(String host) method returns an InetAddress object representing the host passed as a parameter. This method can be used to determine the IP address of a host, given the host's name. getLocalHost() method returns an InetAddress object representing the local host computer.

Page 127: Java Complete Manual

127

import java.net.*; class InetDemo{ public static void main(String[] args){ try{ System.out.println("IP address of LocalHost..."); InetAddress address = InetAddress.getLocalHost(); System.out.println(address); }catch(Exception e) { System.out.println(e.getMessage()); } } URL URL is an acronym for Uniform Resource Locator. A URL is a pointer to a particular resource at a particular location on the Internet. A URL specifies the following: protocol used to access the server (such as http), name of the server, port on the server (optional) path, and name of a specific file on the server (sometimes optional) anchor or reference point within the file (optional) Sometimes the name of the file can be omitted, in which case an HTTP browser will usually append the file name index.html to the specified path and try to load that file. The general syntax of a URL is : protocol://hostname[:port]/path/filename URL Class The URL class enables you to retrieve a resource from the Web by specifying the Uniform Resource Locator for it import java.net.*; import java.io.*; class UrlDemo{ public static void main(String[] args){ String dataLine; try{ URL url = new URL("http://192.168.1.1"); BufferedReader htmlPage = new BufferedReader(new InputStreamReader(url.openStream())); while((dataLine = htmlPage.readLine()) != null){

Page 128: Java Complete Manual

128

System.out.println(dataLine); } } catch(UnknownHostException e){ System.out.println(e); } catch(MalformedURLException e){System.out.println(e);} catch(IOException e){System.out.println(e);} } } UrlConnection Class It is an abstract class that can be extended, and it has a protected constructor that takes a URL object as a parameter.The class provides methods to know more about the remote resource. import java.net.*; import java.io.*; import java.util.*; class UrlDemo { public static void main(String[] args){ String dataLine; try{ URL url = new URL("http://192.168.1.1"); URLConnection urlConnection = url.openConnection(); System.out.println(urlConnection.getURL()); Date lastModified = new Date(urlConnection.getLastModified()); System.out.println(lastModified); System.out.println(urlConnection.getContentType()); BufferedReader htmlPage = new BufferedReader(new InputStreamReader(url.openStream())); while((dataLine = htmlPage.readLine()) != null){ System.out.println(dataLine); } } catch(UnknownHostException e){ System.out.println(e); } catch(MalformedURLException e){System.out.println(e); } catch(IOException e){System.out.println(e); } } }

Page 129: Java Complete Manual

129

Socket Class The Socket class provides a reliable, ordered stream connection (TCP/IP). The host and port number of the destination are specified when the Socket is created. import java.net.*; import java.io.*; import java.util.*; class SocketsDemo{ public static void main(String[] args){ String server = "192.168.1.1"; int port = 13; try{ Socket socket = new Socket(server,port); System.out.println("Got socket"); BufferedReader inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println(inputStream.readLine()); socket.close(); } catch(UnknownHostException e){ System.out.println(e.getMessage()); } catch(IOException e){System.out.println(e); } } } ServerSocket Class Server sockets listen on a given port for connection requests when their accept() method is called. The ServerSocket offers the same connection-oriented, ordered stream protocol (TCP) that the Socket object does. ServerSocket class is used to implement servers. import java.net.*; import java.io.*; class SocketsDemo{ public static void main(String[] args){ String server = "192.168.1.1"; int port = 80; try{

Page 130: Java Complete Manual

130

Socket socket = new Socket(server,port); BufferedReader inputStream = new BufferedReader(new InputStreamReader( socket.getInputStream())); PrintWriter outputStream = new PrintWriter(new OutputStreamWriter( socket.getOutputStream()),true); outputStream.println("GET /index.html"); String line = null; while((line = inputStream.readLine()) != null) System.out.println(line); socket.close(); } catch(UnknownHostException e){ System.out.println(e); } catch(IOException e){System.out.println(e);} } } Server Program import java.util.Date; import java.io.*; import java.net.*; public class Dayserver { public static void main(String[] args) { ServerSocket theserver; Socket asocket; PrintWriter p; BufferedReader timestream; Socket csocket; try { theserver = new ServerSocket(13); try { while(true) { System.out.println("Waiting for customers..."); asocket = theserver.accept(); p = new PrintWriter(asocket.getOutputStream()); p.println(new Date());

Page 131: Java Complete Manual

131

p.close(); asocket.close(); } } catch(IOException e) { theserver.close(); System.err.println(e);} } catch(IOException e) { System.err.println(e);} } } Client Program import java.io.*; import java.net.*; public class Dayclient { public static void main(String[] args) { Socket csocket; BufferedReader timestream; if (args.length < 1) { System.err.println("Please Enter.. Host name or IP Address : ); System.exit(0); } try { csocket = new Socket(args[0],13); timestream = new BufferedReader(new InputStreamReader(csocket.getInputStream())); String thetime = timestream.readLine(); System.out.println("it is "+ thetime + " at " + args[0]); csocket.close(); } catch(IOException e) { System.err.println(e);} } }

Page 132: Java Complete Manual

132

Chapter 16 JDBC JDBC stands for Java Database Connectivity. It is a set API’s used for Executing SQL Statements.JDBC defines a number of Java interfaces to enable developers to access Database. Using JDBC, it is easy to send SQL statements to virtually any relational database. In other words, with the JDBC API, it isn't necessary to write one program to access a Sybase database, another program to access an Oracle database, another program to access an Informix database, and so on. One can write a single program using the JDBC API, and the program will be able to send SQL statements to the appropriate database. And, with an application written in the Java programming language, one also doesn't have to worry about writing different applications to run on different platforms. The combination of Java and JDBC lets a programmer write it once and run it anywhere. Two-tier Models In the two-tier model, a Java applet or application talks directly to the database. This requires a JDBC driver that can communicate with the particular database management system being accessed. A user's SQL statements are delivered to the database, and the results of those statements are sent back to the user. The database may be located on another machine to which the user is connected via a network. This is referred to as a client/server configuration, with the user's machine as the client, and the machine housing the database as the server. Three-tier Models In the three-tier model, commands are sent to a middle tier of services, which then send SQL statements to the database. The database processes the SQL statements and sends the results back to the middle tier, which then sends them to the user. Middle tier makes it possible to maintain control over access and the kinds of updates that can be made to corporate data. Another advantage is that when there is a middle tier, the user can employ an easy-to-use higher-level API which is translated by the middle tier into the appropriate low-level calls. Finally, in many cases the three-tier architecture can provide performance advantages.

Page 133: Java Complete Manual

133

ODBC Open Database Connectivity (ODBC) is an API (Application Program Interface) module written in C. It allows data exchanging between different kind of databases which implement SQL query language. At the beginning ODBC was introduced by Microsoft (1992) to connect its DBMS to the ones produced by different software companies. ODBC soon became a standard gaining a great diffusion all over the world. It is build up by a ODBC Manager and a Driver Manager distributed in 16 and 32 bit versions. Windows's ODBC Manager allows users to manage, through a user friendly interface, connections to one or more databases. Driver Manager's task is loading drivers, checking for errors, managing multiple database connections. JDBC versus ODBC (Open DataBase Connectivity) ODBC is not appropriate for direct use from Java because it uses a C interface. Calls from Java to native C code have a number of drawbacks in the security, implementation, robustness, and automatic portability of applications. Java has no pointers, and ODBC makes copious use of them, including the notoriously error-prone generic pointer ``void *''. You can think of JDBC as ODBC translated into an object-oriented interface that is natural for Java programmers. When ODBC is used, the ODBC driver manager and drivers must be manually installed on every client machine. When the JDBC driver is written completely in Java, however, JDBC code is automatically installable, portable, and secure on all Java platforms from network computers to mainframes. Types of JDBC drivers. JDBC-ODBC bridge Provides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. A native-API Partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.

Page 134: Java Complete Manual

134

Net-protocol fully Java technology-enabled driver Translates JDBC API calls into a DBMS-independent net protocol, which is then translated, to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC API alternative. Native-protocol fully Java technology-enabled driver Converts JDBC technology calls into the network protcol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. JDBC Interfaces JDBC defines the following interfaces that must be implemented by a driver. java.sql.Driver java.sql.Connection java.sql.Statement java.sql.PreparedStatement java.sql.CallableStatement java.sql.ResultSet java.sql.ResultSetMetaData java.sql.DatabaseMetaData Database url A JDBC URL consists of the following : jdbc:<subprotocol>:<subname> The first element is the resource protocol-in this case, a JDBC data source. The subprotocol is specific to the JDBC implementation. In many cases, it is the DBMS name and version. jdbc:msql://hostname:port/database Establishing Connection

Page 135: Java Complete Manual

135

The first thing you need to do is establish a connection with the DBMS you want to use. This involves following steps : First step involves loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ , you would load the driver with the following line of code: Class.forName("jdbc.OracleDriver"); You do not need to create an instance of a driver and register it with the DriverManager because calling Class.forName will do that for you automatically. When you have loaded a driver, it is available for making a connection with a DBMS. The second step in establishing a connection is to have the appropriate driver connect to the DBMS. Connection con =DriverManager.getConnection(url, "myLogin", "myPassword"); Connection A Connection is a single database session. It stores state information about the database session it manages and provides the application with objects for making calls during the session. Statement A Statement is is generally a simple UPDATE, DELETE, INSERT, or SELECT statement in which no columns must be bound to Java data. A Statement provides methods for making such calls and returns to the application the results of any SELECT statement ResultSet ResultSet object enables an application to retrieve sequential rows of data returned from a previous SELECT call. The ResultSet provides a multitude of methods that enable you to retrieve a given row as any data type to which it makes sense to convert it. ResulSetMetaData

Page 136: Java Complete Manual

136

ResultSetMetaData provides information on the number of columns in the result set, the name of a column, and its types etc. Before starting to write Java code, it is necessary to register it as an ODBC datasource. On Windows platforms it is possible to use the ODBC Administrator to achieve this task. Windows ODBC Administrator is in the Control Panel window. import java.io.*; public class JdbcDemo { public static void main (String args[]) throws Exception { java.sql.Connection conn; java.sql.ResultSetMetaData meta; java.sql.Statement stmt; java.sql.ResultSet result; int i; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); conn = java.sql.DriverManager.getConnection("jdbc:odbc:mydsn"); String sQuery = "SELECT * from emp"; stmt= conn.createStatement(); result = stmt.executeQuery(sQuery); meta = result.getMetaData(); int cols = meta.getColumnCount(); for (i=1; i <= cols; i++) { System.out.println("Column i:"+i+" "+meta.getColumnName(i)+ "," + meta.getColumnType(i) + "," + meta.getColumnTypeName(i)); } int cnt = 1; while(result.next()) { System.out.print("\nRow "+cnt+" : "); for (i=1; i <= cols; i++) { System.out.print(result.getString(i)+"\t"); } cnt++; } stmt.close(); conn.close(); }

Page 137: Java Complete Manual

137

} executeUpdate executeQuery() returns a ResultSet object containing the results of the query sent to the DBMS, the return value for executeUpdate is an int that indicates how many rows of a table were updated. When the method executeUpdate is used to execute a DDL statement, such as in creating a table, it returns the int 0 . The SQL statement to update one row might look like this: String updateString = "UPDATE EMP " + "SET SALARY = SALARY + 5000 " + "WHERE DEPTNO = 10"; Using the Statement object stmt , this JDBC code executes the SQL statement contained in updateString : stmt.executeUpdate(updateString); Prepared Statements Although PreparedStatement objects can be used for SQL statements with no parameters, you will probably use them most often for SQL statements that take parameters. The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it. You will see an example of this in the following sections. You create PreparedStatement objects with a Connection method. PreparedStatement updateEmp = con.prepareStatement("UPDATE EMP SET SALARY = ? WHERE DEPTN O= ?"); You will need to supply values to be used in place of the question mark placeholders, if there are any, before you can execute a PreparedStatement object. You do this by calling one of the setXXX methods defined in the class PreparedStatement . If the value you want to substitute for a question mark is a Java int , you call the method setInt. If the value you want to substitute for a question mark is a Java String , you call the method setString , and so on. In general, there is a setXXX method for each type in the Java programming language. Using the PreparedStatement object updateSales from the previous example, the following line of code sets the first question mark placeholder to a Java int with a value of 5000: updateEmp.setInt(1, 5000); As you might surmise from the example, the first argument given to a setXXX method indicates which question mark placeholder is

Page 138: Java Complete Manual

138

to be set, and the second argument indicates the value to which it is to be set. The next example sets the second placeholder parameter to "10 ": updateEmp.setString(2, 10); After these values have been set for its two input parameters, the SQL statement in updateSales will be equivalent to the SQL statement in the String object updateString that we used in the previous update example. Therefore, the following two code fragments accomplish the same thing: String updateString = "UPDATE EMP SET SALARY = 5000 " + "WHERE DEPTNO = 10"; stmt.executeUpdate(updateString); Stored Procedures Stored procedures and prepared statements are precompiled SQL calls sitting on the server. You call a stored procedure like a function, using its name and passing arguments. java.sql.PreparedStatement java.sql.CallableStatement The basic difference between these two classes is that PreparedStatement expects only input parameters; CallableStatement allows you to bind input and output parameters. Using stored procedures or prepared statements generally gives your application an added speed advantage, because such statements are stored in a precompiled format in most database engines. CallableStatement object allows java application and applets to request the execution of procedures stored in the DBMS. A CallableStatement object is instantiated through Connection's prepareCall() method. prepareCall() accepts as parameters escape clauses with the following form: {[? =] call <Procedure Name> [<?>,<?>, ...]} The first interrogative point ("?=") represents the output the java application will receive. It is called OUT parameter. The following interrogative points substitute called procedure's name and parameters. They are called "IN" parameters. It is necessary to specify the output type we are waiting for from the DBMS before starting the procedure. It is done through the registerOutParameter() method. If we are requesting a procedure execution whose result is of integer type, we'll write in our application:

Page 139: Java Complete Manual

139

StatementObject.registerOutParameter(1,java.sql.Types.INTEGER); It is important to remember we have to use the right method to handle results. So, if we registered the OUT parameters as integer we'll use the getInteger() method."IN" parameters has to be registered too before the procedure execution request. It is possible to set their type using setXXX() methods. XXX is the type of the parameter we'll send to the DBMS. setString(1,String); setInteger(2, Integer);

Page 140: Java Complete Manual

140

Chapter 17 Collections Collection A collection is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve and manipulate data, and to transmit data from one method to another. Collections typically represent data items that form a group. Collection Framework A collections framework is a unified architecture for representing and manipulating collections. Interfaces: Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages like Java, these interfaces generally form a hierarchy. Implementations: These are concrete implementations of the collection interfaces. Algorithms: These are methods that perform useful computations, like searching and sorting, on objects that implement collection interfaces. Enumerations The Enumeration interface provides a standard means of iterating through a list of sequentially stored elements, which is a common task of many data structures. Methods defined by the Enumeration interface: public abstract boolean hasMoreElements(); The hasMoreElements method is used to determine if the enumeration contains any more elements. You will typically call this method to see if you can continue iterating through an enumeration. public abstract Object nextElement(); The nextElement method is responsible for actually retrieving the next element in an enumeration. If no more elements are in the

Page 141: Java Complete Manual

141

enumeration, nextElement will throw a NoSuchElementException exception. // e is an object that implements the Enumeration interface while (e.hasMoreElements()) { Object o = e.nextElement(); System.out.println(o); } Stack The Stack class implements a last-in-first-out (LIFO) stack of elements. You can think of a stack literally as a vertical stack of objects; when you add a new element, it gets stacked on top of the others. When you pull an element off the stack, it comes off the top. In other words, the last element you added to the stack is the first one to come back off. You use this constructor to create a stack like this: Stack s = new Stack(); You add new elements to a stack using the push method, which pushes an element onto the top of the stack: s.push("Unix"); s.push("Oracle"); s.push("C"); s.push("Java"); s.push("VB"); s.push("Oracle"); This code pushes six strings onto the stack, with the last string ("Oracle") remaining on top. You pop elements back off the stack using the pop method: String s1 = (String)s.pop(); String s2 = (String)s.pop(); This code pops the last two strings off the stack, leaving the first four strings remaining. This code results in the s1 variable containing the "Oracle" string and the s2 variable containing the "VB" string. Vectors

Page 142: Java Complete Manual

142

The Vector class implements a growable array of objects. Since the Vector class is responsible for growing itself as necessary to support more elements, it has to decide when and by how much to grow as new elements are added. You can easily control this aspect of vectors upon creation. Before getting into that, however, take a look at how to create a basic vector: Vector v = new Vector(); That's about as simple as it gets! This constructor creates a default vector containing no elements. Actually, all vectors are empty upon creation. One of the attributes important to how a vector sizes itself is the initial capacity of a vector, which is how many elements the vector allocates memory for by default. The following code shows how to create a vector with a specified capacity: Vector v = new Vector(25); This vector is created to immediately support up to 25 elements. In other words, the vector will go ahead and allocate enough memory to support 25 elements. Once 25 elements have been added, however, the vector must decide how to grow itself to accept more elements. You can specify the value by which a vector grows using yet another Vector constructor: Vector v = new Vector(25, 5); This vector has an initial size of 25 elements, and will grow in increments of 5 elements whenever its size grows to more than 25 elements. This means that the vector will first jump to 30 elements in size, then 35, and so on. To add an element to a vector, you use the addElement method: v.addElement("Oracle"); v.addElement("VB"); v.addElement("JAVA"); The lastElement method retrieves the last element added to the vector. String s = (String)v.lastElement();

Page 143: Java Complete Manual

143

Example of using the elementAt method: String s1 = (String)v.elementAt(0); String s2 = (String)v.elementAt(2); Example of using the insertElementAt()/removeElementAt() method: v.insertElementAt(“VBScript", 1); v.insertElementAt("JavaScript", 0); v.removeElementAt(3); You can use the setElementAt method to change a specific element: v.setElementAt("New", 1); If you want to clear out the vector completely, you can remove all the elements with the removeAllElements method: v.removeAllElements(); The Vector class also provides some methods for working with elements without using indexes. These methods actually search through the vector for a particular element. The first of these methods is the contains method, which simply checks to see if an element is in the vector: boolean isThere = v.contains("VB"); Another method that works in this manner is the indexOf method, which finds the index of an element based on the element itself: int i = v.indexOf("Oracle"); The indexOf method returns the index of the element in question if it is in the vector, or -1 if not. The removeElement method works similarly in that it removes an element based on the element itself rather than on an index: v.removeElement("Java");

Page 144: Java Complete Manual

144

If you're interested in working with all the elements in a vector sequentially, you can use the elements method, which returns an enumeration of the elements: Enumeration e = v.elements(); Following code shows how to use the put method to add elements to a dictionary: dict.put("small", new Rectangle(0, 0, 5, 5)); dict.put("medium", new Rectangle(0, 0, 15, 15)); dict.put("large", new Rectangle(0, 0, 25, 25)); This code adds three rectangles to the dictionary, using strings as the keys. To get an element from the dictionary, you use the get method and specify the appropriate key: Rectangle r = (Rectangle)dict.get("medium"); You can also remove an element from the dictionary with a key using the remove method: dict.remove("large"); You can find out how many elements are in the dictionary using the size method, much as you did with the Vector class: int size = dict.size(); You can also check whether the dictionary is empty using the isEmpty method: boolean isEmpty = dict.isEmpty(); Finally, the Dictionary class includes two methods for enumerating the keys and values contained within: keys and elements. The keys method returns an enumeration containing all the keys contained in a dictionary, while the elements method returns an enumeration of all the key-mapped values contained. Enumeration keys = dict.keys(); Enumeration elements = dict.elements();

Page 145: Java Complete Manual

145

Hashtable The Hashtable class provides a means of organizing data based on some user-defined key structure. The Hashtable class is derived from Dictionary and provides a complete implementation of a key-mapped data structure. Similar to dictionaries, hash tables allow you to store data based on some type of key. Constructors Hashtable hash = new Hashtable(); Creates a default hash table. Hashtable hash = new Hashtable(20); Creates a hash table with the specified initial capacity. All the abstract methods defined in Dictionary are implemented in the Hashtable class.The Hashtable class implements a few others that perform functions specific to supporting hash tables. hash.clear() - Clears a hash table of all its keys and elements. boolean isThere = hash.contains(new Rectangle(0, 0, 5, 5)); The contains method is used to see if an object is stored in the hash table. This method searches for an object value in the hash table rather than a key. boolean isThere = hash.containsKey("Small"); containsKey method searches a hash table, but it searches based on a key rather than a value. Chapter 18 java.lang Java provides a rich set of pre-written classes, giving programmers an existing library of code to support files, networking, graphics, and general language routines; each major category being supported by a collection of classes known as a package. By default, each Java application/applet has access to the java.lang package. Inside java.lang are classes that represent

Page 146: Java Complete Manual

146

primitive data types (such as int & char), as well as more complex classes. It contains classes pertaining to strings, string buffers, threads, and even the System class from which we obtain out input and output streams. Basic data types Object Integer Long Float Double Character String StringBuffer Object Class In Java, all classes are actually subclasses of class Object. When we define a class, class MyClass { ..... } we are actually implicitly extending MyClass from class Object. Thus, we can replace the above sample with the following : class MyClass extends Object { ..... } Every class in Java shares the same properties, and methods of class Object. While there are several methods that might be of use, the most important of these is the toString() method. Every object can be explicitly converted into a string representation, by calling the toString() method which returns a string. Thus, we can explicitly convert objects, such as floating point numbers, integers, etc. double my_double = 3.14; String my_str = my_double.toString() Numerical data types

Page 147: Java Complete Manual

147

The numerical data types all share some common methods, which their inherit from class Number. All numbers are convertible to the basic numerical classes (int, long, float, double) using the following method calls : int intValue(); long longValue(); float floatValue(); double doubleValue(); Integer / Long Class Integer, and the longer form, long, represent whole number values. Integers and longs can be interchanged through the longValue() and intValue() methods, and can also be converted to floats and doubles using the floatValue() and doubleValue(). Integer my_integer = new Integer(256); Long my_long = my_integer.longValue(); FLOAT / DOUBLEB CLASS Floating point values, and the longer form, double, represent decimal fractional values. Floats and doubles can be interchanged through the doubleValue() and floatValue() methods, and can also be converted to integers and longs using the longValue() and intValue() methods. Float my_float = new Float(3.14); Double my_double = new Double (my_float.doubleValue()); System.out.println( "Double : " + my_double); System.out.println( "Integer: " + my_double.intValue() ); CHARACTER CLASS The character class contains a large set of character comparison routines, in the form of static methods. A static method is a method that is common to all objects of the type that class. In fact, you don't even need to instantiate an object from a class containing a static method to call it! if (Character.isLowerCase( 'H' )) { System.out.println ("Lowercase value detected"); }

Page 148: Java Complete Manual

148

else { System.out.println ("Uppercase value detected"); } The character class offers a wide range of character comparison routines : static boolean isDigit( char c ); static boolean isLetter( char c ); static boolean isLetterOrDigit( char c ); static boolean isLowerCase( char c ); static boolean isUpperCase( char c ); static char toUpperCase( char c ); static char toLowerCase( char c ); String Class A String is a unique object, which has its own set of methods. Some of the more useful routines are listed below : public char charAt(int index) - Returns the character at offset index public int compareTo(String anotherString) - Compares string with another, returning 0 if there's a match public String concat(String anotherString) - Returns a new string equal to anotherString appended to the current string public int length() - Returns the length of the current string public boolean startsWith(String prefix) - Returns true if the current string begins with prefix public boolean endsWith(String suffix) - Returns true if the current string ends in suffix public String substring(int beginIndex) - Returns the remainder of the string, starting from offset beginIndex public String substring(int beginIndex, int endIndex) - Returns a substring from offset beginIndex to offset endIndex public String toLowerCase() - Returns the current string, converted to lowercase public String toUpperCase() - Returns the current string, converted to uppercase STRINGBUFFER CLASS

Page 149: Java Complete Manual

149

StringBuffer class has an append method, which extends the capacity of the StringBuffer when required to accommodate varying lengths. The append method even allows you to add chars, booleans, integers, longs, floats & doubles. Some of the more useful StringBuffer methods are given below : public StringBuffer append(boolean b) - Appends the string version of a boolean to the buffer public StringBuffer append(char c) - Appends a character to the buffer public StringBuffer append(int i) - Appends the string version of a integer to the buffer public StringBuffer append(long l) - Appends the string version of a long to the buffer public StringBuffer append(float f) - Appends the string version of a float to the buffer public StringBuffer append(double d) - Appends the string version of a double to the buffer public StringBuffer append(Object obj) - Appends the string version (toString method) of an object to the buffer public StringBuffer append(String str) - Appends the string to the buffer public char charAt(int index) - Returns the character at offset index public int length() - Returns the current length of the string buffer public StringBuffer reverse() - Reverses the order of characters in the string buffer public void setLength(int newLength) - Truncates, or pads with null characters, the buffer to a certain length public String toString() - Returns a string, representing the string buffer System Class System class provides us with the input and output streams. public static InputStream in; public static PrintStream out; public static PrintStream err; There is one input stream, and two output streams (out/err). Normal messages should be passed to out, but exceptional cases and error conditions should be written to err (standard error on Unix systems). Since these attributes are static, we need not even

Page 150: Java Complete Manual

150

instantiate the System class to access them. To print, for example, we can simply use the statement System.out.println() Methods public static void exit(int status) public static String getProperty(String key); System.exit Exit allows a Java programmer to immediately terminate execution of the program, and to return a status code. By convention, a non-zero status code indicates an error has occurred, and on PC systems, should set the appropriate DOS errorlevel. If your Java application has been run from a batch file, you can actually test to see if it has executed correctly. Presented below is a test class, and a batch file that when executed will check for a status code of six. class test { public static void main(String args[]) { System.exit (6); } } test.bat @echo off if ERRORLEVEL 6 echo Errorlevel 1 detected REM Execute test.class java test if ERRORLEVEL 6 echo An error has occurred. Please restart A check is made, in two places, to see if errorlevel six has been set, so that the change in errorlevel can be seen. Its also important to note that an errorlevel will last longer than the duration of the batch file - running test.bat a second time will mean that the first error check returns true. SYSTEM.GETPROPERTY

Page 151: Java Complete Manual

151

ANOTHER USEFUL METHOD FROM THE SYSTEM CLASS IS GETPROPERTY. VIA THE GETPROPERTY METHOD, A JAVA APPLICATION CAN GAIN INFORMATION ABOUT THE OPERATING SYSTEM UNDER WHICH IT IS RUNNING, THE VENDOR AND VERSION OF THE JAVA VIRTUAL MACHINE, AND EVEN THE USER NAME AND HOME DIRECTORY PATH OF THE CURRENT USER UNDER UNIX BASED SYSTEMS. Some of the more common system properties :

Key Description java.version Java version number java.vendor Java-vendor-specific string java.vendor.url Java vendor URL java.home Java installation directory java.class.version Java class format version number java.class.path Java classpath os.name Operating system name os.arch Operating system architecture os.version Operating system version file.separator File separator ("/" on Unix) path.separator Path separator (":" on Unix) line.separator Line separator ("\n" on Unix) user.name User account name user.home User home directory user.dir User's current working directory

Accessing the system properties is as simple as calling the static getProperty method and passing a key from the table as a parameter. An example is shown below, which displays the operating system of the computer it is running on. class GetPropertyDemo { public static void main(String args[]) { // Display value for key os.name System.out.println ( System.getProperty("os.name") ); } }

Page 152: Java Complete Manual

152

Insert your company information in place of the sample text on the cover page, as well as the inside-cover page. If you plan to use Styles such as the “Icon Key” or Icon 1 Style, set them now (see instructions, page 1). Choose File Save As. In the menu, choose Document Template in the Save File as Type: box. (The filename extension should change from .doc to .dot.) Save the file under a new name to protect the original version, or use the same template name to replace the existing version. How to Create a Document To create a manual from your newly saved template, select File New to re-open your template as a document. Assuming you followed the steps above, your company information should appear in place. Now, simply type your manual. More Template Tips There are three ways to view the various Style names of the template sample text: � In Normal view, choose Tools Options. Click the View tab. In the Style Area Width box, dial up a number and click OK; or In Page Layout view, click on any paragraph and view the style name on the Formatting toolbar; or From the Format menu, choose Style Gallery. In the Preview section, click on Style Samples.

Page 153: Java Complete Manual

153

Indexa Index 1, 1 Index 1, 1 Index 1, 1 Index 2, 2 Index 3, 3 Index 1, 1 Index 1, 1 b Index 1, 1 Index 1, 1 Index 1, 1 Index 2, 2 c Index 1, 1 Index 1, 1 Index 1, 1 Index 2, 2 Index 1, 1 Index 1, 1 Index 1, 1 d Index 1, 1 Index 1, 1 Index 1, 1 Index 1, 1 e Index 1, 1 Index 1, 1 Index 1, 1 Index 2, 2 Index 1, 1 Index 1, 1 Index 1, 1 g Index 1, 1 Index 1, 1 Index 1, 1 Index 1, 1 Index 1, 1 Index 1, 1 h Index 1, 1

Index 1, 1 Index 1, 1 Index 1, 1 Index 2, 2 Index 1, 1 Index 1, 1 Index 1, 1 Index 1, 1 Index 1, 1 Index 1, 1 k Index 1, 1 L Index 1, 1 Index 2, 2 Index 1, 1 Index 1, 1 Index 2, 2 Index 1, 1 Index 1, 1 Index 1, 1 Index 1, 1 Index 1, 1 m Index 1, 1 Index 1, 1 Index 1, 1 Index 2, 2 n Index 1, 1 Index 1, 1 Index 1, 1 Index 2, 2 Index 1, 1 Index 1, 1 Index 1, 1 r Index 1, 1 Index 1, 1 s Index 1, 1 Index 1, 1 Index 1, 1

Index 2, 2 Index 1, 1 Index 1, 1 Index 1, 1 t Index 1, 1 Index 1, 1 Index 1, 1 Index 1, 1 Index 2, 2 w Index 1, 1 Index 1, 1 Index 1, 1 Index 2, 2 Index 1, 1 Index 1, 1 Index 1, 1 Index 1, 1

Page 154: Java Complete Manual

154