You are on page 1of 138

UNIT-I

INTRODUCTION TO JAVA Java programming language was originally developed by Sun Microsystems, which was initiated by James Gosling and released in 1995. Sun Microsystems has renamed the new J2 versions as Java SE, Java EE and Java ME respectively. Java is guaranteed to be Write Once, Run Anywhere JAVA FEATURES

Object Oriented: In java everything is an Object. Java can be easily extended since it is based on the Object model. Platform independent: Unlike many other programming languages including C and C++ when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run. Simple: Java is designed to be easy to learn. Secure: With Javas secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption. Architectural- neutral: Java compiler generates an architecture-neutral object file format which makes the compiled code to be executable on many processors, with the presence Java runtime system. Portable: being architectural neutral and having no implementation dependent aspects of the specification makes Java portable. Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking. Multi-threaded: With Javas multi-threaded feature it is possible to write programs that can do many tasks simultaneously. This design feature allows developers to construct smoothly running interactive applications. Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light weight process. High Performance: With the use of Just-In-Time compilers Java enables high performance. Distributed: Java is designed for the distributed environment of the internet.

BASIC CONCEPTS OF OOPS Object and classes Data abstraction and Encapsulation Inheritance Polymorphism Dynamic binding Message communication JAVA TOKENS Keywords

Identifiers Literals Operators Separators Identifiers All java components require names. Names used for classes, variables and methods are called identifiers. In java there are several points to remember about identifiers. They are as follows: All identifiers should begin with a letter (A to Z or a to z ), currency character ($) or an underscore (-). After the first character identifiers can have any combination of characters. A key word cannot be used as an identifier. Most importantly identifiers are case sensitive. Examples of legal identifiers: age, $salary, _value, _1_value Examples of illegal identifiers: 123abc, -salary Keywords Keywords are reserved words that are predefined in the language. There are few keywords in Java programming language. Remember, we cannot use these keywords as identifiers in the program and all the keywords are in lowercase.

Example: number, $$abc, _xyx // Legal Identifiers 12cc, ss-he // Illegal identifiers Operators Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Arithmetic Operators Relational Operators Bitwise Operators Logical Operators Assignment Operators

Literals A literal is the source code representation of a fixed value; literals are represented directly in our code without requiring computation. Integer Literals Any whole number value is an integer literal. Examples are 1, 2, 3, and 42. boolean result = true; char capitalC = 'C'; byte b = 100; Floating-Point Literals Floating-point numbers represent decimal values with a fractional component. They can be expressed in either standard or scientific notation. EX: Standard notation: 2.0, 3.14159, and 0.6667 scientific notation: 6.022E23, 314159E05, and 2e+100 Boolean Literals Boolean literals are simple. There are only two logical values that a boolean value can have, true and false Character Literals o Characters in Java are indices into the Unicode character set. String Literals String literals in Java are specified like they are in most other languagesby enclosing a sequence of characters between a pair of double quotes. Examples of string literals are Hello World. JAVA STATEMENTS Statements in java are like sentences in natural languages. A statement is an executable combination of tokens ending with a semicolon mark. Java statements are classified into eight types. Empty statement Labelled statement Expression statement Selection statement

Iteration statement Jump statement Synchronization statement Guarding statement

VARIABLES The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier, a type, and an optional initializer. In addition, all variables have a scope, which defines their visibility, and a lifetime. Declaring the variable In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here: type identifier [ = value][, identifier [= value] ...] ; The type is one of Javas atomic types, or the name of a class or interface. The identifier is the name of the variable. We can initialize the variable by specifying an equal sign and a value. To declare more than one variable of the specified type, use a comma-separated list. int a, b, c; // declares three ints, a, b, and c. int d = 3, e, f = 5; // declares three more ints, initializing d and f. byte z = 22; // initializes z. Variables can be classified into three categories:
Local variables: All the variables declared inside a method. Their scope is the

method. In other words, they can be accessed only from inside the method in which they are declared, and they are destroyed when the method completes. Local variables are also called stack variables because they live on the stack. Instances variables: The variables declared inside a class but outside of any method. Their scope is the instance of the class in which they are declared. These variables, for example, can be used to maintain a counter at instance level. Instance variables live on the heap. Static variables: The instance variables declared with the modifier static. Their scope is the class in which they are declared. These variables can be used to maintain a counter at class level, which is a variable shared by all the objects of the class. Their scope is the instance of the class in which they are declared. These Data Types Java defines eight simple (or elemental) types of data: byte, short, int, long, char, float, double, and boolean. These can be put in four groups:
Integers This group includes byte, short, int, and long, which are for wholevalued

signed numbers.
Floating-point numbers This group includes float and double, which represent

numbers with fractional precision.

Characters This group includes char, which represents symbols in a character set,

like letters and numbers. Boolean This group includes boolean, which is a special type for representing true/false values. byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). float: The float data type is a single-precision 32-bit of storage. It has an approximate range from 1.4e-045 to 3.4e+038 double: The double data type is a double-precision 64-bit of storage. It has an approximate range from 4.9e324 to 1.8e+308 boolean: The boolean data type has only two possible values: true and false. char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive). In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.String class. The following chart summarizes the default values for the above data types. Data Type Byte Short Int Long Float Double Char Default Value (for fields) 0 0 0 0L 0.0f 0.0d '\u0000'

String (or any object) Null Boolean False

Type Casting The process of storing a value of one data type into a variable of another data type is called as type casting. The syntax is Type variable1= (type) variable2; Examples: int m=50; byte n= (byte) m; There are two types of casting widening and narrowing. The process of assigning a smaller type to a larger one is known as widening or promotion. Java automatically does this. This is known as automatic type conversion. The process of assigning a larger type to a smaller one is known as narrowing. This may result in loss of information.

JAVA OPERATORS

Arithmetic Operators Relational Operators Bitwise Operators Logical Operators Assignment Operators Misc Operators

Arithmetic Operators: Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators. Assume integer variable A holds 10 and variable B holds 20 then: Operator Description + Addition - Adds values on either side of the operator Example A + B will give 30

* / % ++ --

Subtraction - Subtracts right hand operand from left hand operand Multiplication - Multiplies values on either side of the operator Division - Divides left hand operand by right hand operand Modulus - Divides left hand operand by right hand operand and returns remainder Increment - Increase the value of operand by 1 Decrement - Decrease the value of operand by 1

A - B will give -10 A * B will give 200 B / A will give 2 B % A will give 0 B++ gives 21 B-- gives 19

Relational Operators: There are following relational operators supported by Java language. Operator Description == Checks if the value of two operands are equal or not, if yes then condition becomes true. Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. Checks if the value of left operand is greater than or equal to the value of right operand, if yes , becomes true. Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. Example (A == B) is not true.

!=

(A != B) is true.

>

(A > B) is not true.

<

(A < B) is true.

>=

(A >= B) is not true.

<=

(A <= B) is true.

Bitwise Operators: Java defines several bitwise operators which can be applied to the integer types, long, int, short, char, and byte. Bitwise operator works on bits and perform bit by bit operation. Assume if a = 60; and b = 13; Now in binary format they will be as follows: a = 0011 1100 b = 0000 1101 a&b = 0000 1100 a|b = 0011 1101 a^b = 0011 0001 ~a = 1100 0011 The following table lists the bitwise operators: Assume integer variable A holds 60 and variable B holds 13 then: Operator Description & Binary AND Operator copies a bit to the result if it exists in both operands. Binary OR Operator copies a bit if it exists in either operand. Binary XOR Operator copies the bit if it is set in one operand but not both. Binary Ones Complement Operator is unary and has the efect of 'flipping' bits. Binary Left Shift Operator. The left << operands value is moved left by the number of bits specified by the right operand. >> Binary Right Shift Operator. The left A >> 2 will give 15 which is 1111 A << 2 will give 240 which is 1111 0000 Example (A & B) will give 12 which is 0000 1100

(A | B) will give 61 which is 0011 1101

(A ^ B) will give 49 which is 0011 0001

(~A ) will give -60 which is 1100 0011

operands value is moved right by the number of bits specified by the right operand. Shift right zero fill operator. The left operands value is moved right by the >>> number of bits specified by the right A >>>2 will give 15 which is 0000 1111 operand and shifted values are filled up with zeros. Logical Operators: The following table lists the logical operators: Assume boolean variables A holds true and variable B holds false then: Operator Description Called Logical AND operator. If both && the operands are non zero then (A && B) is false. condition becomes true. Called Logical OR Operator. If any of || the two operands are non zero then then (A || B) is true. condition becomes true. Called Logical NOT Operator. Use to ! reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is true. Example

Assignment Operators: There are following assignment operators supported by Java language:

Operator Description

Example

Simple =

assignment

operator,

Assigns values from right side operands to left side operand Add AND assignment operator, It

C = A + B will assigne value of A + B into C

+=

adds right operand to the left operand and assign the result to left operand Subtract AND assignment

C += A is equivalent to C = C + A

-=

operator, It subtracts right operand from the left operand and assign the result to left operand Multiply AND It assignment right

C -= A is equivalent to C = C - A

*=

operator,

multiplies

operand with the left operand and assign the result to left operand Divide AND assignment operator,

C *= A is equivalent to C = C * A

/=

It divides left operand with the right operand and assign the result to left operand Modulus AND assignment

C /= A is equivalent to C = C / A

%=

operator, It takes modulus using two operands and assign the result to left operand

C %= A is equivalent to C = C % A

<<=

Left

shift

AND

assignment

operator Right operator Bitwise AND assignment operator bitwise exclusive OR shift AND assignment

C <<= 2 is same as C = C << 2

>>= &= ^=

C >>= 2 is same as C = C >> 2 C &= 2 is same as C = C & 2

and C ^= 2 is same as C = C ^ 2

assignment operator |= bitwise inclusive OR and C |= 2 is same as C = C | 2

assignment operator

Misc Operators There are few other operators supported by Java Language. Conditional Operator ( ? : ): Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. The operator is written as : variable x = (expression) ? value if true : value if false instanceOf Operator: This operator is used only for object reference variables. The operator checks whether the object is of a particular type(class type or interface type). instanceOf operator is wriiten as: ( Object reference variable ) instanceOf (class/interface type) If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side then the result will be true. Expressions Arithmetic Expressions: An arithmetic expression is a combination of variables, constants, and operators arranged as per the syntax of the language. Example: (a*b)/(c+d)

Evaluation of Expressions: Exprssions are evaluated using an assignment statement of the form

Variable = expression; Example: x= : (a*b)/(c+d)

Precedence of Arithmetic operators: High priority: * / %

Low priority: + BRANCHING AND LOOPING Selection statements: 1. If Statement: This is a control statement to execute a single statement or a block of code, when the given condition is true and if it is false then it skips if block and rest code of program is executed. Syntax: if(conditional_expression){ <statements>; ...; ...; } Example: int n = 10; if(n%2 = = 0){ System.out.println("This is even number"); } 2. If-else Statement: The "if-else" statement is an extension of if statement that provides another option when 'if' statement evaluates to "false" i.e. else block is executed if "if" statement is false. Syntax: if(conditional_expression){ <statements>; ...; ...; } else{

<statements>; ....; ....; } Example: int n = 11; if(n%2 = = 0){ System.out.println("This is even number"); } else{ System.out.println("This is not even number"); } 3. Switch Statement: This is an easier implementation to the if-else statements. The keyword "switch" is followed by an expression that should evaluates to byte, short, char or int primitive data types ,only. In a switch block there can be one or more labeled cases. The expression that creates labels for the case must be unique. The switch expression is matched with each case label. Only the matched case is executed, if no case matches then the default statement (if present) is executed. Syntax: switch(control_expression){ case expression 1: <statement>; case expression 2: <statement>; ... ... case expression n: <statement>; default: <statement>; }//end switch Example:. int day = 5; switch (day) { case 1:

System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thrusday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; case 7: System.out.println("Sunday"); break; default: System.out.println("Invalid entry"); break; } Repetition Statements: 1. while loop statements:

This is a looping or repeating statement. It executes a block of code or a statement till the given condition is true. The expression must be evaluated to a boolean value. It continues testing the condition and executes the block of code. When the expression results to false control comes out of loop. Syntax: while(expression){ <statement>; ...; ...; } Example:. int i = 1; //print 1 to 10 while (i <= 10){ System.out.println("Num " + i); i++; } 2. do-while loop statements: This is another looping statement that tests the given condition past is do-while looping statement. First do block statements are executed then the condition given in while statement is checked. So in this case, even the condition is false in the first attempt, do block of code is executed at least once. Syntax: do{ <statement>; ...; ...; }while (expression); Example: int i = 1; do{ System.out.println("Num: " + i); i++; }while(i <= 10);

for loop statements: This is also a loop statement that provides a compact way to iterate over a range of values. From a user point of view, this is reliable because it executes the statements within this block repeatedly till the specified condition is true. Syntax: for (initialization; condition; increment or decrement){ <statement>; ...; ...; } initialization: The loop is started with the value specified. condition: It evaluates to either 'true' or 'false'. If it is false then the loop is terminated. increment or decrement: After each iteration, value increments or decrements. Example: for (int num = 1; num <= 10; num++){ System.out.println("Num: " + num); } Branching Statements:
1. Break statements:

The break statement is a branching statement that contains two forms: labeled and unlabeled. The break statement is used for breaking the execution of a loop (while, do-while and for). It also terminates the switch statements. Syntax: break; // breaks the break label; // breaks the Continue statements: innermost loop outermost loop in or switch statement. series of nested loops.

This is a branching statement that are used in the looping statements (while, do-while and for) to skip the current iteration of the loop and resume the next iteration . Syntax: continue; Return statements:It is a special branching statement that transfers the control to the caller of the method. This statement is used to return a value to the caller method and terminates execution of method. This has two forms: one that returns a value and the other that can not return. the returned value type must match the return type of method. Syntax: return; return values;

UNIT - II CLASSES The class is the basis for object-oriented programming. A class is a template that contains the data variables and the methods that operate on those data variables following some logic. The data variables and the methods in a class are called class members. Defining Classes A class is declared by using the keyword class. The general syntax for a class declaration is <modifier> class <className> { }

<className> specifies the name of the class, class is the keyword, and <modifier> specifies some characteristics of the class. The <modifier> specification is optional, but the other two elements in the declaration are mandatory. We can broadly group the modifiers into the following two categories:
Access modifiers: Determine from where the class can be accessed: private, protected,

and public. If you do not specify an access modifier, the default access is assumed.
Other modifiers: Specify how the class can be used: abstract, final, and strictfp.

CREATING OBJECTS When we write a class, we must keep in mind the objects that will be created from it, which correspond to the objects in the problem that is being solved by the program. We may also look upon the classes as data types. We can declare a variable (a reference variable) of a class and assign it a value with the following syntax: <className> <variableName> = new <classConstructor> <variableName> in this case is the name of the object reference that will refer to the object that we want to create, and we choose this name. <className> is the name of an existing class, and <classConstructor> is a constructor of the class. The right side of the equation creates the object of the class specified by <className> with the new operator, and assigns it

to <variableName> (i.e. <variableName> points to it). Creating an object from a class this way is also called instantiating the class. Methods A method is a self-contained block of code that performs specific operations on the data by using some logic. Using methods offer two main advantages: A method may be executed (called) repeatedly from different points in the program. Without the method, you would need to repeat that code at different points in the program, hence increasing the program size and making it more error prone. Also, if a change needs to be made in that piece of code, it must be made in several places, thereby increasing both the effort to maintain the code and the probability for an error. Methods help make the program logically segmented, or modularized. A modular program is less error prone, and easier to maintain. Defining a Method Defining a method in a program is called method declaration. A method consists of the following elements:

Name: The name identifies the method and is also used to call (execute) the method. Naming a method is governed by the same rules as those for naming a variable. Parameter(s): A method may have zero or more parameters defined in the parentheses immediately following the method name during the method declaration. Argument(s): The parameter values passed in during the method call are called arguments and correspond to the parameters defined during the method declaration. Return type: A method may optionally return a value as a result of a method call. The type of the data returned, such as int, is declared in the method declaration. Access modifier: Each method has a default or specified access modifier, such as public or private, which determines from where the method can be accessed (called).

The following is the syntax for writing a method in Java: <modifier> <returnType> <methodName> ( <Parameters>) { // body of the method. The code statements go here. }

The <modifier> specifies the method further, such as its visibility, and <returnType> defines the data type that will be returned by the method. While zero or more modifiers may be used, <returnType> and <methodName> are mandatory. The parameters are used to pass data into the method. For example, consider the following method: public int square (int number) { return number*number; } The name of the method is square. It will return a value of type int. The modifier public means it could be called from anywhere. CONSTRUCTORS A constructor initializes an object immediately upon creation. It has the same name as the class in which it resides and is syntactically similar to a method. Once defined, the constructor is automatically called immediately after the object is created, before the new operator completes. The key points about constructors are summarized here: A constructor of a class has the same name as the class, and has no explicit return type. A class may have more than one constructor. If the programmer defines no constructor in a class, the compiler will add the default constructor with no arguments. If there are one or more constructors defined in the class, the compiler will not provide any constructor. A constructor may have zero or more parameters. From outside the class, a constructor is always called with the new operator. From inside the class, it may be called from another constructor with the this or super operatorthis to call another constructor of the same class, super to call a constructor

of the superclass. The super or this call is always made in the beginning of the constructor body. Unlike other methods, the constructors are not inherited. If the superclass has constructors and the subclass does not, the compiler assumes that the subclass does not have any constructor and creates the default constructor. If there is no super call in a constructor, the default super call is placed by the compiler, that is, a call to the default constructor of the superclass. Program: Constructors /* Here, Box uses a constructor to initialize the dimensions of a box. */ class Box { double width; double height; LANGUAGE double depth; // This is the constructor for Box. Box() { System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } // compute and return volume double volume() { return width * height * depth; } } class BoxDemo6 {

public static void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } } When this program is run, it generates the following results: Constructing Box Constructing Box Volume is 1000.0 Volume is 1000.0 OVERLOADING METHODS In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Method overloading is one of the ways that Java implements polymorphism.

When an overloaded method is called, Java looks for a match between the arguments used to call the method and the methods parameters. However, this match need not always be exact. In some cases Javas automatic type conversions can play a role in overload resolution. Here is a simple example that illustrates method overloading: Program: Method Overloading class OverloadDemo { void test() { System.out.println("No parameters"); } void test(int a) { System.out.println("a: " + a); } void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } double test(double a) { System.out.println("double a: " + a); return a*a; } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); ob.test();

ob.test(10); ob.test(10, 20); double result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); } } This program generates the following output: No parameters a: 10 a and b: 10 20 double a: 123.25 Result of ob.test(123.25): 15190.5625 INHERITANCE Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. Inheritance is the mechanism through which we can derive classes from other classes. The derived class is called as child class or the subclass or we can say the extended class and the class from which we are deriving the subclass is called the base class or the parent class. To derive a class in java the keyword extends is used. The following kinds of inheritance are there in java.

Simple Inheritance Hierarchical inheritance

Multilevel Inheritance Hybrid inheritance

Simple Inheritance When a subclass is derived simply from it's parent class then this mechanism is known as simple inheritance. In case of simple inheritance there is only a sub class and it's parent class. It is also called single inheritance or one level inheritance.

class A { int x, y; void get(int p, int q){ x=p; y=q; } void Show(){ System.out.println(x); } } class B extends A{ public static void main(String args[]){ A a = new A(); a.get(5,6); a.Show(); } void display(){ System.out.println("B");} } Multilevel Inheritance It is the enhancement of the concept of inheritance. When a subclass is derived from a derived class then this mechanism is known as the multilevel inheritance. The derived class is called the subclass or child class for its parent class and this parent class works as the child class for it's just above (parent) class. Multilevel inheritance can go up to any number of levels. class A { int x,y; void get(int p, int q){ x=p; y=q; } void Show(){ System.out.println(x); } }

class B extends A{ void Showb(){ System.out.println("B"); } } class C extends B{ void display(){ System.out.println("C"); } public static void main(String args[]){ A a = new A(); a.get(5,6); a.Show(); } } Hierarchical Inheritance If a parent class having more than one child class then this mechanism is called as hierarchical inheritance. Hybrid Inheritance Combination of any two types of inheritance is called as hybrid inheritance. METHOD OVERRIDING A method defined in a super class is inherited by its subclass and is used by the objects created by the subclass Method inheritance enables us to define and use methods repeatedly in subclasses without having to define the methods again in subclass When the method is called, the method defined in the subclass is invoked and executed instead of the one in the subclass. This is known as overriding Example class Parent {

void display( ) { System.out.println(This is method in parent class) ; } } class Child extends Parent { void display( ) { System.out.println(This is method in child class ); } } class OverrideTest { public static void main(String args[ ]) { Child c = new Child( ); c.display( ); } OUTPUT: This is method in child class

FINALIZER METHODS A constructor method is used to initialize an object when it is declared. This process is known as initialization Java support a concept is called finalization Java run-time is an automatic garbage collection system Finalizer( ) { // Statements like closing a file } ABSTRACT METHODS We can indicate that a method must always be redefined in a subclass, thus making overriding compulsory This is done using the modifier keyword abstract in method definition. A method which does not have actual body of statements also called as abstract method. class Shape { .. abstract void draw( ); .. void display(); } VISIBILITY CONTROL

Using Access Modifiers Access modifiers, also called visibility modifiers, determine the accessibility scope of the Java elements they modify. If we do not explicitly use an access modifier with a Java element, the element implicitly has the default access modifier. The explicit access modifiers may be used with a class and its members (that is, instance variables and methods). They cannot be used with the variables inside a method. The Java language offers three explicit access modifiers, public, protected, and private, and a default modifier, which is enforced when we do not specify a modifier. The public Modifier The public modifier makes a Java element most accessible. It may be applied to classes and to their members (that is, instance variables and methods). A class, variable, or method, declared as public, may be accessed from anywhere in the Java application. The private Modifier A private member of a class may only be accessed from the code inside the same class in which this member is declared. It can be accessed neither from any other class nor from a subclass of the class in which it is declared. The public and private access modifiers are on the two extremes of access: access from everywhere and access from nowhere outside of the class. There is another access modifier called protected that covers the middle ground between these two extremes. The protected Modifier A class member declared protected is accessible to the following elements: All the classes in the same package that contains the class that owns the protected member. All the subclasses of the class that owns the protected member. These subclasses have access even if they are not in the same package as the parent class. The Default Modifier When we do not specify any access modifier for an element, it is assumed that the access is default. In other words, there is no keyword default for the default modifier. If an element does not explicitly use any modifier, the default access is implied. It may be applied to a class, a variable, or a method. A class or a class member declared default (no access modifier specified) is accessible from anywhere (classes or subclasses) in the same package in which the accessed class exists. These access modifiers are summarized in Table.

Table: Access Level that a Class Has Granted to Other Classes by Using Different Modifiers ARRAY

Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. Declaring Array Variables you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable: dataType[] arrayRefVar; // preferred way. dataType arrayRefVar[]; // works but not preferred way. Example: double[] myList; double myList[]; Creating Arrays We can create an array by using the new operator with the following syntax: arrayRefVar = new dataType[arraySize]; dataType[] arrayRefVar = new dataType[arraySize]; dataType[] arrayRefVar = {value0, value1, ..., valuek};

// preferred way. // works but not preferred way.

JAVA - STRING CLASS Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and manipulate strings. Creating Strings: The most direct way to create a string is to write: String greeting = "Hello world!"; Example: public class StringDemo{ public static void main(String args[]){ char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'}; String helloString = new String(helloArray); System.out.println( helloString ); } }

This would produce following result: hello String Methods: Here is the list methods supported by String class: SN Methods with Description 1 2 3 4 5 6 7 8 9 char charAt(int index) Returns the character at the specified index. int compareTo(Object o) Compares this String to another Object. int compareTo(String anotherString) Compares two strings lexicographically. int compareToIgnoreCase(String str) Compares two strings lexicographically, ignoring case differences. String concat(String str) Concatenates the specified string to the end of this string. boolean contentEquals(StringBuffer sb) Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer. boolean equals(Object anObject) Compares this string to the specified object. boolean equalsIgnoreCase(String anotherString) Compares this String to another String, ignoring case considerations. int length() Returns the length of this string.

String replace(char oldChar, char newChar) 10 Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. 11 12 13 String substring(int beginIndex) Returns a new string that is a substring of this string. String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string. char[] toCharArray() Converts this string to a new character array.

String toLowerCase() 14 Converts all of the characters in this String to lower case using the rules of the default locale. String toLowerCase(Locale locale) 15 Converts all of the characters in this String to lower case using the rules of the given Locale. 16 String toString() This object (which is already a string!) is itself returned.

String toUpperCase() 17 Converts all of the characters in this String to upper case using the rules of the default locale. String toUpperCase(Locale locale) 18 Converts all of the characters in this String to upper case using the rules of the given Locale. 19 20 String trim() Returns a copy of the string, with leading and trailing whitespace omitted. static String valueOf(primitive data type x) Returns the string representation of the passed data type argument.

STRINGBUFFER StringBuffer class is similar to String, but it has some extra methods, here we can change the length of a string object. Here is the list of important methods supported by StringBuffer class:

SN Methods with Description 1 2 3 4 5 public StringBuffer append(String s) Updates the value of the object that invoked the method. The method takes boolean, char, int, long, Strings etc. public StringBuffer reverse() The method reverses the value of the StringBuffer object that invoked the method. public delete(int start, int end) Deletes the string starting from start index until end index. public insert(int offset, int i) This method inserts an string s at the position mentioned by offset. replace(int start, int end, String str) This method replaces the characters in a substring of this StringBuffer with characters in the specified String.

VECTOR Vector implements a dynamic array. It is similar to ArrayList, but with two differences:

Vector is a group of heterogeneous elements. It will contain objects as elements.

Vector proves to be very useful if you don't know the size of the array in advance, or you just need one that can change sizes over the lifetime of a program. Vector defines following methods:

SN 1

Methods with Description void add(int index, Object element) Inserts the specified element at the specified position in this Vector. boolean add(Object o) Appends the specified element to the end of this Vector. void addElement(Object obj) Adds the specified component to the end of this vector, increasing its size by one. int capacity() Returns the current capacity of this vector. void clear() Removes all of the elements from this Vector. boolean contains(Object elem) Tests if the specified object is a component in this vector. boolean containsAll(Collection c) Returns true if this Vector contains all of the elements in the specified Collection. void copyInto(Object[] anArray) Copies the components of this vector into the specified array. Object elementAt(int index) Returns the component at the specified index. boolean equals(Object o) Compares the specified Object with this Vector for equality. Object firstElement() Returns the first component (the item at index 0) of this vector. Object get(int index) Returns the element at the specified position in this Vector.

10

11

12

int indexOf(Object elem) 13 Searches for the first occurence of the given argument, testing for equality using the equals method. 14 int indexOf(Object elem, int index) Searches for the first occurence of the given argument, beginning the search at index,

and testing for equality using the equals method. 15 void insertElementAt(Object obj, int index) Inserts the specified object as a component in this vector at the specified index. boolean isEmpty() Tests if this vector has no components. Object lastElement() Returns the last component of the vector. Object remove(int index) Removes the element at the specified position in this Vector. void removeElementAt(int index) removeElementAt(int index) int size() Returns the number of components in this vector.

16

17

18

19

20

String toString() 21 Returns a string representation of this Vector, containing the String representation of each element.

Wrapper classes: Wrapper classes are used to convert a primitive data types into object types. These are available in java.lang package. Data type boolean char double float Int long Wrapper class Boolean Character Double Float Integer Long

UNIT- III

Interfaces An interface in the Java programming language is an abstract type that is used to specify an interface (in the generic sense of the term) that classes must implement. Interfaces are declared using the interface keyword, and may only contain method signatures and constant declarations (variable declarations that are declared to be both static and final). An interface may never contain method definitions. The interface definition states the names of the methods and their return types and argument signatures. There is no executable body for any method - that is left to each class that implements the interface Once a class implements an interface, the Java compiler knows that an instance of the class will contain the specified set of methods. Therefore, it will allow us to call those methods for an object referenced by a variable whose type is the interface. Creating an Interface Definition To create an interface definition:

Define interface like a Java class, in its own file that matches the interface name Use the keyword interface instead of class Declare methods using the same approach as abstract methods
o

note the semicolon after each method declaration - and that no executable code is supplied(and no curly braces) the elements will automatically be public and abstract, and cannot have any other state; it is OK to specify those terms, but not necessary (usually public is specified and abstract is not - that makes it easy to copy the list of methods, paste them into a class, and modify them )

The access level for the entire interface is usually public


o

it may be omitted, in which case the interface is only available to other classes in the same package (i.e., in the same directory) note, for the sake of completeness, there are situations where the interface definition could be protected or private; these involve what are called inner classes

Syntax access interface name { return-type method-name1(parameter-list); return-type method-name2(parameter-list); type final-varname1 = value; type final-varname2 = value; // ... return-type method-nameN(parameter-list); type final-varnameN = value; } Variables can be declared inside of interface declarations. They are implicitly final and static, meaning they cannot be changed by the implementing class. They must also be initialized with a constant value. All methods and variables are implicitly public if the interface, itself, is declared as public. Here is an example of an interface definition. It declares a simple interface which contains one method called callback( ) that takes a single integer parameter. interface Callback { void callback(int param); } Implementing Interfaces Once an interface has been defined, one or more classes can implement that interface. To implement an interface, include the implements clause in a class definition, and then create the methods defined by the interface. The general syntax of a class that includes the implements clause looks like this: access class classname [extends superclass]

[implements interface [,interface...]] { // class-body } Here, access is either public or not used. If a class implements more than one interface, the interfaces are separated with a comma. If a class implements two interfaces that declare the same method, then the same method will be used by clients of either interface. The methods that implement an interface must be declared public. Also, the type signature of the implementing method must match exactly the type signature specified in the interface definition. Here is a small example class that implements the Callback interface shown earlier. class Client implements Callback { // Implement Callback's interface public void callback(int p) { System.out.println("callback called with " + p); } } Notice that callback( ) is declared using the public access specifier. Accessing Implementations through Interface References The following example calls the callback( ) method via an interface reference variable: class TestIface { public static void main(String args[]) { Callback c = new Client(); c.callback(42); } } Output:

callback called with 42

Marker Interface An interface with no methods. Example: Serializable, Remote, Cloneable Packages and interfaces Packages and interfaces are two of the basic components of a Java program. In general, a Java source file can contain any (or all) of the following four internal parts: A single package statement (optional) Any number of import statements (optional) A single public class declaration (required) Any number of classes private to the package (optional)

Packages Packages are containers for classes that are used to keep the class name space compartmentalized. For example, a package allows us to create a class named List, which we can store in our own package without concern that it will collide with some other class named List stored elsewhere. Packages are stored in a hierarchical manner and are explicitly imported into new class definitions. Defining a Package To create a package is quite easy: simply include a package command as the first statement in a Java source file. Any classes declared within that file will belong to the specified package. The package statement defines a name space in which classes are stored. If we omit the package statement, the class names are put into the default package, which has no name. While the default package is fine for short, sample programs, it is inadequate for real applications. Most of the time, we will define a package for our code. This is the general syntax of the package statement: package pkg; Here, pkg is the name of the package. For example, the following statement creates a package called MyPackage.

package MyPackage; Java uses file system directories to store packages. For example, the .class files for any classes you declare to be part of MyPackage must be stored in a directory called MyPackage. Remember that case is significant, and the directory name must match the package name exactly. More than one file can include the same package statement. The package statement simply specifies to which package the classes defined in a file belong. It does not exclude other classes in other files from being part of that same package. Most real-world packages are spread across many files. We can create a hierarchy of packages. To do so, simply separate each package name from the one above it by use of a period. The general syntax of a multileveled package statement is shown here: package pkg1[.pkg2[.pkg3]]; A package hierarchy must be reflected in the file system of our Java development system. For example, a package declared as package java.awt.image; Program: A simple package package MyPack; class Balance { String name; double bal; Balance(String n, double b) { name = n; bal = b; } void show() { if(bal<0)

System.out.print("--> "); System.out.println(name + ": $" + bal); } } class AccountBalance { public static void main(String args[]) { Balance current[] = new Balance[3]; current[0] = new Balance("K. J. Fielding", 123.23); current[1] = new Balance("Will Tell", 157.02); current[2] = new Balance("Tom Jackson", -12.33); for(int i=0; i<3; i++) current[i].show(); } } Access Protection Classes and packages are both means of encapsulating and containing the name space and scope of variables and methods. Packages act as containers for classes and other subordinate packages. Classes act as containers for data and code. The class is Javas smallest unit of abstraction. Because of the interplay between classes and packages, Java addresses four categories of visibility for class members: Subclasses in the same package Non-subclasses in the same package Subclasses in different packages Classes that are neither in the same package nor subclasses

The three access specifiers, private, public, and protected, provide a variety of ways to produce the many levels of access required by these categories. Table: sums up the interactions.

Table: Class Member Access

Java - Multithreading Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. A multithreading is a specialized form of multitasking. Multitasking threads require less overhead than multitasking processes. Process: A process consists of the memory space allocated by the operating system that can contain one or more threads. A thread cannot exist on its own; it must be a part of a process. A process remains running until all of the non-daemon threads are done executing. Multithreading enables us to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum. Life Cycle of a Thread A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread.

Above mentioned stages are explained here:

New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task. Waiting: Sometimes a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.

Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.

Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.

Thread Priorities Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled. Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).

Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependent. Creating a Thread Java defines two ways in which this can be accomplished:

We can implement the Runnable interface. We can extend the Thread class, itself.

Implementing Runnable interface The easiest way to create a thread is to create a class that implements the Runnable interface. To implement Runnable, a class need only implement a single method called run( ), which is declared like this: public void run( ) We will define the code that constitutes the new thread inside run() method. It is important to understand that run() can call other methods, use other classes, and declare variables, just like the main thread can. After we create a class that implements Runnable, we will instantiate an object of type Thread from within that class. Thread defines several constructors. The one that we will use is shown here: Thread(Runnable threadOb, String threadName); Here threadOb is an instance of a class that implements the Runnable interface and the name of the new thread is specified by threadName. After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. The start( ) method is shown here: void start( );

Example: Here is an example that creates a new thread and starts it running: // Create a new thread. class NewThread implements Runnable { Thread t; NewThread() { // Create a new, second thread t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); t.start(); // Start the thread } // This is the entry point for the second thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); // Let the thread sleep for a while. Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } } class ThreadDemo { public static void main(String args[]) { new NewThread(); // create a new thread try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i);

Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } } This would produce following result: Child thread: Thread[Demo Thread,5,main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread. Main Thread: 2 Main Thread: 1 Main thread exiting. Create Thread by Extending Thread: The second way to create a thread is to create a new class that extends Thread, and then to create an instance of that class. The extending class must override the run( ) method, which is the entry point for the new thread. It must also call start( ) to begin execution of the new thread. Example: Here is the preceding program rewritten to extend Thread:

// Create a second thread by extending Thread class NewThread extends Thread { NewThread() { // Create a new, second thread super("Demo Thread"); System.out.println("Child thread: " + this); start(); // Start the thread } // This is the entry point for the second thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); // Let the thread sleep for a while. Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } } class ExtendThread { public static void main(String args[]) { new NewThread(); // create a new thread try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted.");

} System.out.println("Main thread exiting."); } } This would produce following result: Child thread: Thread[Demo Thread,5,main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread. Main Thread: 2 Main Thread: 1 Main thread exiting. Thread Synchronization When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time.

The process by which this synchronization is achieved is called thread synchronization. The synchronized keyword in Java creates a block of code referred to as a critical section. Every Java object with a critical section of code gets a lock associated with the object. To enter a critical section, a thread needs to obtain the corresponding object's lock.

This is the general form of the synchronized statement:

synchronized(object) {

// statements to be synchronized }

Here, object is a reference to the object being synchronized. A synchronized block ensures that a call to a method that is a member of object occurs only after the current thread has successfully entered object's monitor.

Here is an example, using a synchronized block within the run( ) method:

// File Name : Callme.java // This program uses a synchronized block. class Callme { void call(String msg) { System.out.print("[" + msg); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Interrupted"); } System.out.println("]"); } }

// File Name : Caller.java class Caller implements Runnable { String msg;

Callme target; Thread t; public Caller(Callme targ, String s) { target = targ; msg = s; t = new Thread(this); t.start(); }

// synchronize calls to call() public void run() { synchronized(target) { // synchronized block target.call(msg); } } } // File Name : Synch.java class Synch { public static void main(String args[]) { Callme target = new Callme(); Caller ob1 = new Caller(target, "Hello"); Caller ob2 = new Caller(target, "Synchronized"); Caller ob3 = new Caller(target, "World");

// wait for threads to end try { ob1.t.join(); ob2.t.join(); ob3.t.join(); } catch(InterruptedException e) { System.out.println("Interrupted"); } } }

This would produce following result:

[Hello] [World] [Synchronized] Stopping and blocking a thread Consider the classic queuing problem, where one thread is producing some data and another is consuming it. To make the problem more interesting, suppose that the producer has to wait until the consumer is finished before it generates more data. In a polling system, the consumer would waste many CPU cycles while it waited for the producer to produce. Once the producer was finished, it would start polling, wasting more CPU cycles waiting for the consumer to finish, and so on. Clearly, this situation is undesirable.

To avoid polling, Java includes an elegant interprocess communication mechanism via the following methods:

wait( ): This method tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ). notify( ): This method wakes up the first thread that called wait( ) on the same object. notifyAll( ): This method wakes up all the threads that called wait( ) on the same object.c The highest priority thread will run first.

These methods are implemented as final methods in Object, so all classes have them. All three methods can be called only from within a synchronized context. These methods are declared within Object. Various forms of wait( ) exist that allow you to specify a period of time to wait. Java - Thread Deadlock A special type of error that you need to avoid that relates specifically to multitasking is deadlock, which occurs when two threads have a circular dependency on a pair of synchronized objects. Java - Thread Control While the suspend( ), resume( ), and stop( ) methods defined by Thread class seem to be a perfectly reasonable and convenient approach to managing the execution of threads, they must not be used for new Java programs and obsolete in newer versions of Java. The NewThread class contains a boolean instance variable named suspendFlag, which is used to control the execution of the thread. It is initialized to false by the constructor. The run( ) method contains a synchronized statement block that checks suspendFlag. If that variable is true, the wait( ) method is invoked to suspend the execution of the thread. The mysuspend( ) method sets suspendFlag to true. The myresume( ) method sets suspendFlag to false and invokes notify( ) to wake up the thread. Finally, the main( ) method has been modified to invoke the mysuspend( ) and myresume( ) methods.

UNIT IV

Managing Errors and Exceptions Syntax of Exception Handling Code Using Finally Statement Throwing Our Own Exceptions Applet Programming Applet Life Cycle Graphics Programming Managing Input/output Files Concept of Streams Stream Classes Byte Stream Classes Character Stream Classes Using Streams Using the File Class Creations of files Random Access Files Other stream classes

Managing Errors and Exceptions What Is an Exception? The term exception is shorthand for the phrase "exceptional event." Definition An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception. After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack (see the next figure).

The call stack. The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler. The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, as shown in the next figure, the runtime system (and, consequently, the program) terminates.

Searching the call stack for the exception handler. Using exceptions to manage errors has some advantages over traditional errormanagement techniques. You can learn more in the Advantages of Exceptions section.

The Catch or Specify Requirement Valid Java programming language code must honor the Catch or Specify Requirement. This means that code that might throw certain exceptions must be enclosed by either of the following:

A try statement that catches the exception. The try must provide a handler for the exception, as described in Catching and Handling Exceptions. A method that specifies that it can throw the exception. The method must provide a throws clause that lists the exception, as described in Specifying the Exceptions Thrown by a Method.

Code that fails to honor the Catch or Specify Requirement will not compile. Not all exceptions are subject to the Catch or Specify Requirement. To understand why, we need to look at the three basic categories of exceptions, only one of which is subject to the Requirement. The Three Kinds of Exceptions The first kind of exception is the checked exception. These are exceptional conditions that a well-written application should anticipate and recover from. For example, suppose an application prompts a user for an input file name, then opens the file by passing the name to the constructor for java.io.FileReader. Normally, the user provides the name of an existing, readable file, so the construction of the FileReader object succeeds, and the execution of the application proceeds normally. But sometimes the user supplies the name of a nonexistent file, and the constructor throws java.io.FileNotFoundException. A wellwritten program will catch this exception and notify the user of the mistake, possibly prompting for a corrected file name. Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses. The second kind of exception is the error. These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. For example, suppose that an application successfully opens a file for input, but is unable to read the file because of a hardware or system malfunction. The unsuccessful read will throw java.io.IOError. An application might choose to catch this exception, in order to notify the user of the problem but it also might make sense for the program to print a stack trace and exit. Errors are not subject to the Catch or Specify Requirement. Errors are those exceptions indicated by Error and its subclasses. The third kind of exception is the runtime exception. These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. These usually indicate programming bugs, such as logic errors or improper use of an API. For example, consider the application described previously that passes a file name to the constructor for FileReader. If a logic error causes a null to be passed to the constructor, the constructor will throw NullPointerException. The application can catch this exception, but it probably makes more sense to eliminate the bug that caused the exception to occur.

Runtime exceptions are not subject to the Catch or Specify Requirement. Runtime exceptions are those indicated by RuntimeException and its subclasses. Errors and runtime exceptions are collectively known as unchecked exceptions. Bypassing Catch or Specify Some programmers consider the Catch or Specify Requirement a serious flaw in the exception mechanism and bypass it by using unchecked exceptions in place of checked exceptions. In general, this is not recommended. The section Unchecked Exceptions The Controversy talks about when it is appropriate to use unchecked exceptions.
The try Block The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block. In general, a try block looks like the following: try { code } catch and finally blocks . . . The segment in the example labeled code contains one or more legal lines of code that could throw an exception. (The catch and finally blocks are explained in the next two subsections.) To construct an exception handler for the writeList method from the ListOfNumbers class, enclose the exception-throwing statements of the writeList method within a try block. There is more than one way to do this. You can put each line of code that might throw an exception within its own try block and provide separate exception handlers for each. Or, you can put all the writeList code within a single try block and associate multiple handlers with it. The following listing uses one try block for the entire method because the code in question is very short. private List<Integer> list; private static final int SIZE = 10;

PrintWriter out = null;

try { System.out.println("Entered try statement");

out = new PrintWriter(new FileWriter("OutFile.txt")); for (int i = 0; i < SIZE; i++) { out.println("Value at: " + i + " = " + list.get(i)); } } catch and finally statements . . . If an exception occurs within the try block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, you must put a catch block after it; the next section, The catch Blocks, shows you how.

The catch Blocks You associate exception handlers with a try block by providing one or more catch blocks directly after the try block. No code can be between the end of the try block and the beginning of the first catch block. try { } catch (ExceptionType name) { } catch (ExceptionType name) { } Each catch block is an exception handler and handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name. The catch block contains code that is executed if and when the exception handler is invoked. The runtime system invokes the exception handler when the handler is the first one in the call stack whose ExceptionType matches the type of the exception thrown. The system considers it a match if the thrown object can legally be assigned to the exception handler's argument. The following are two exception handlers for the writeList method one for two types of checked exceptions that can be thrown within the try statement: try { } catch (FileNotFoundException e) { System.err.println("FileNotFoundException: " + e.getMessage()); throw new SampleException(e); } catch (IOException e) {

System.err.println("Caught IOException: " + e.getMessage()); } Both handlers print an error message. The second handler does nothing else. By catching any IOException that's not caught by the first handler, it allows the program to continue executing. The first handler, in addition to printing a message, throws a user-defined exception. (Throwing exceptions is covered in detail later in this chapter in the How to Throw Exceptions section.) In this example, when the FileNotFoundException is caught it causes a user-defined exception called SampleException to be thrown. You might want to do this if you want your program to handle an exception in this situation in a specific way. Exception handlers can do more than just print error messages or halt the program. They can do error recovery, prompt the user to make a decision, or propagate the error up to a higherlevel handler using chained exceptions, as described in the Chained Exceptions section. Catching More Than One Type of Exception with One Exception Handler In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception. In the catch clause, specify the types of exceptions that block can handle, and separate each exception type with a vertical bar (|): catch (IOException|SQLException ex) { logger.log(ex); throw ex; } Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block. The finally Block The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
Note:

If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

The try block of the writeList method that you've been working with here opens a PrintWriter. The program should close that stream before exiting the writeList method. This poses a somewhat complicated problem because writeList's try block can exit in one of three ways.
1. The new FileWriter statement fails and throws an IOException. 2. The vector.elementAt(i) statement fails and throws ArrayIndexOutOfBoundsException. 3. Everything succeeds and the try block exits normally. an

The runtime system always executes the statements within the finally block regardless of what happens within the try block. So it's the perfect place to perform cleanup. The following finally block for the writeList method cleans up and then closes the PrintWriter.
finally {

if (out != null) { System.out.println("Closing PrintWriter"); out.close(); } else { System.out.println("PrintWriter not open"); } } In the writeList example, you could provide for cleanup without the intervention of a finally block. For example, you could put the code to close the PrintWriter at the end of the try block and again within the exception handler for ArrayIndexOutOfBoundsException, as follows. try { out.close(); //Don't do this; it duplicates code.

} catch (FileNotFoundException e) { out.close(); //Don't do this; it duplicates code. System.err.println("Caught: FileNotFoundException: " + e.getMessage()); throw new RuntimeException(e); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); }

However, this duplicates code, thus making the code difficult to read and error-prone should you modify it later. For example, if you add code that can throw a new type of exception to the try block, you have to remember to close the PrintWriter within the new exception handler.
Important:

The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resource is always recovered. If you are using Java SE 7 or later, consider using the try-with-resources statement in these situations, which automatically releases system resources when no longer needed. The next section has more information.

How to Throw Exceptions Before you can catch an exception, some code somewhere must throw one. Any code can throw an exception: your code, code from a package written by someone else such as the packages that come with the Java platform, or the Java runtime environment. Regardless of what throws the exception, it's always thrown with the throw statement. As you have probably noticed, the Java platform provides numerous exception classes. All the classes are descendants of the Throwable class, and all allow programs to differentiate among the various types of exceptions that can occur during the execution of a program. You can also create your own exception classes to represent problems that can occur within the classes you write. In fact, if you are a package developer, you might have to create your own set of exception classes to allow users to differentiate an error that can occur in your package from errors that occur in the Java platform or other packages. You can also create chained exceptions. For more information, see the Chained Exceptions section. The throw Statement All methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class. Here's an example of a throw statement. throw someThrowableObject; Let's look at the throw statement in context. The following pop method is taken from a class that implements a common stack object. The method removes the top element from the stack and returns the object. public Object pop() { Object obj;

if (size == 0) { throw new EmptyStackException(); } obj = objectAt(size - 1); setObjectAt(size - 1, null); size--; return obj; } The pop method checks to see whether any elements are on the stack. If the stack is empty (its size is equal to 0), pop instantiates a new EmptyStackException object (a member of java.util) and throws it. The Creating Exception Classes section in this chapter explains how to create your own exception classes. For now, all you need to remember is that you can throw only objects that inherit from the java.lang.Throwable class. Note that the declaration of the pop method does not contain a throws clause. EmptyStackException is not a checked exception, so pop is not required to state that it might occur. Throwable Class and Its Subclasses The objects that inherit from the Throwable class include direct descendants (objects that inherit directly from the Throwable class) and indirect descendants (objects that inherit from children or grandchildren of the Throwable class). The figure below illustrates the class hierarchy of the Throwable class and its most significant subclasses. As you can see, Throwable has two direct descendants: Error and Exception.

The Throwable class. Error Class When a dynamic linking failure or other hard failure in the Java virtual machine occurs, the virtual machine throws an Error. Simple programs typically do not catch or throw Errors.

Exception Class Most programs throw and catch objects that derive from the Exception class. An Exception indicates that a problem occurred, but it is not a serious system problem. Most programs you write will throw and catch Exceptions as opposed to Errors. The Java platform defines the many descendants of the Exception class. These descendants indicate various types of exceptions that can occur. For example, IllegalAccessException signals that a particular method could not be found, and NegativeArraySizeException indicates that a program attempted to create an array with a negative size. One Exception subclass, RuntimeException, is reserved for exceptions that indicate incorrect use of an API. An example of a runtime exception is NullPointerException, which occurs when a method tries to access a member of an object through a null reference. The section Unchecked Exceptions The Controversy discusses why most applications shouldn't throw runtime exceptions or subclass RuntimeException. Advantages of Exceptions Now that you know what exceptions are and how to use them, it's time to learn the advantages of using exceptions in your programs. Advantage 1: Separating Error-Handling Code from "Regular" Code Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code. For example, consider the pseudocode method here that reads an entire file into memory. readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } At first glance, this function seems simple enough, but it ignores all the following potential errors.

What What What What What

happens happens happens happens happens

if if if if if

the file can't be opened? the length of the file can't be determined? enough memory can't be allocated? the read fails? the file can't be closed?

To handle such cases, the readFile function must have more code to do error detection, reporting, and handling. Here is an example of what the function might look like. errorCodeType readFile { initialize errorCode = 0;

open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } } else { errorCode = -5; } return errorCode; } There's so much error detection, reporting, and returning here that the original seven lines of code are lost in the clutter. Worse yet, the logical flow of the code has also been lost, thus making it difficult to tell whether the code is doing the right thing: Is the file really being closed if the function fails to allocate enough memory? It's even more difficult to ensure that the code continues to do the right thing when you modify the method three months after writing it. Many programmers solve this problem by simply ignoring it errors are reported when their programs crash. Exceptions enable you to write the main flow of your code and to deal with the exceptional cases elsewhere. If the readFile function used exceptions instead of traditional errormanagement techniques, it would look more like the following. readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething;

} catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; } } Note that exceptions don't spare you the effort of doing the work of detecting, reporting, and handling errors, but they do help you organize the work more effectively. Advantage 2: Propagating Errors Up the Call Stack A second advantage of exceptions is the ability to propagate error reporting up the call stack of methods. Suppose that the readFile method is the fourth method in a series of nested method calls made by the main program: method1 calls method2, which calls method3, which finally calls readFile. method1 { call method2; } method2 { call method3; } method3 { call readFile; } Suppose also that method1 is the only method interested in the errors that might occur within readFile. Traditional error-notification techniques force method2 and method3 to propagate the error codes returned by readFile up the call stack until the error codes finally reach method1the only method that is interested in them. method1 { errorCodeType error; error = call method2; if (error) doErrorProcessing; else proceed; } errorCodeType method2 { errorCodeType error; error = call method3; if (error) return error; else proceed;

} errorCodeType method3 { errorCodeType error; error = call readFile; if (error) return error; else proceed; } Recall that the Java runtime environment searches backward through the call stack to find any methods that are interested in handling a particular exception. A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it. Hence, only the methods that care about errors have to worry about detecting errors. method1 { try { call method2; } catch (exception e) { doErrorProcessing; } } method2 throws exception { call method3; } method3 throws exception { call readFile; } However, as the pseudocode shows, ducking an exception requires some effort on the part of the middleman methods. Any checked exceptions that can be thrown within a method must be specified in its throws clause. Advantage 3: Grouping and Differentiating Error Types Because all exceptions thrown within a program are objects, the grouping or categorizing of exceptions is a natural outcome of the class hierarchy. An example of a group of related exception classes in the Java platform are those defined in java.io IOException and its descendants. IOException is the most general and represents any type of error that can occur when performing I/O. Its descendants represent more specific errors. For example, FileNotFoundException means that a file could not be located on disk. A method can write specific handlers that can handle a very specific exception. The FileNotFoundException class has no descendants, so the following handler can handle only one type of exception. catch (FileNotFoundException e) { ... }

A method can catch an exception based on its group or general type by specifying any of the exception's superclasses in the catch statement. For example, to catch all I/O exceptions, regardless of their specific type, an exception handler specifies an IOException argument. catch (IOException e) { ... } This handler will be able to catch all I/O exceptions, including FileNotFoundException, EOFException, and so on. You can find details about what occurred by querying the argument passed to the exception handler. For example, use the following to print the stack trace. catch (IOException e) { e.printStackTrace(); //Output goes to System.err. e.printStackTrace(System.out); //Send trace to stdout. } You could even set up an exception handler that handles any Exception with the handler here. catch (Exception e) { ... } //A (too) general exception handler

The Exception class is close to the top of the Throwable class hierarchy. Therefore, this handler will catch many other exceptions in addition to those that the handler is intended to catch. You may want to handle exceptions this way if all you want your program to do, for example, is print out an error message for the user and then exit. In most situations, however, you want exception handlers to be as specific as possible. The reason is that the first thing a handler must do is determine what type of exception occurred before it can decide on the best recovery strategy. In effect, by not catching specific errors, the handler must accommodate any possibility. Exception handlers that are too general can make code more error-prone by catching and handling exceptions that weren't anticipated by the programmer and for which the handler was not intended. As noted, you can create groups of exceptions and handle exceptions in a general fashion, or you can use the specific exception type to differentiate exceptions and handle exceptions in an exact fashion. What is an Applet Introduction Applet is java program that can be embedded into HTML pages. Java applets runs on the java enables web browsers such as mozila and internet explorer. Applet is designed to run remotely on the client browser, so there are some restrictions on it. Applet can't access system resources on the local computer. Applets are used to make the web site more dynamic and entertaining. Advantages of Java Applet:

Applets are cross platform and can run on Windows, Mac OS and Linux platform Applets can work all the version of Java Plugin Applets runs in a sandbox, so the user does not need to trust the code, so it can work without security approval Applets are supported by most web browsers Applets are cached in most web browsers, so will be quick to load when returning to a web page User can also have full access to the machine if user allows

Disadvantages of Java Applet:


Java plug-in is required to run applet Java applet requires JVM so first time it takes significant startup time If applet is not already cached in the machine, it will be downloaded from internet and will take time Its difficult to designing and build good user interface in applets compared to HTML technology

Overview Applets are used to provide interactive features to web applications that cannot be provided by HTML alone. They can capture mouse input and also have controls like buttons or check boxes. In response to the user action an applet can change the provided graphic content. This makes applets well suitable for demonstration, visualization and teaching. There are online applet collections for studying various subjects, from physics[12] to heart physiology.[3] Applets are also used to create online game collections that allow players to compete against live opponents in real-time. An applet can also be a text area only, providing, for instance, a cross platform command-line interface to some remote system.[13] If needed, an applet can leave the dedicated area and run as a separate window. However, applets have very little control over web page content outside the applet dedicated area, so they are less useful for improving the site appearance in general (while applets like news tickers[14] or WYSIWYG editors[15] are also known). Applets can also play media in formats that are not natively supported by the browser[16] HTML pages may embed parameters that are passed to the applet. Hence the same applet may appear differently depending on the parameters that were passed. As applets have been available before CSS, they were also widely used for trivial effects like navigation buttons. This use is criticized and declining[17]. A Java applet example Here it is: Hello, world! To minimize download time, applets are usually delivered in a form of compressed zip archive (having jar extension). If all needed classes (only one in our case) are placed in compressed archive example.jar, the embedding code would look different: <P>Here it is: <APPLET code="HelloWorld" ARCHIVE="example.jar"> This is where HelloWorld.class runs.</APPLET></P> WIDTH="200" HEIGHT="40"

Applet inclusion is described in detail in Sun's official page about the APPLET tag.[26] Additional advantages A Java applet can have any or all of the following advantages:[27]

It is simple to make it work on Linux, Microsoft Windows and Mac OS X i.e. to make it cross platform. Applets are supported by most web browsers. The same applet can work on "all" installed versions of Java at the same time, rather than just the latest plug-in version only. However, if an applet requires a later version of the Java Runtime Environment (JRE) the client will be forced to wait during the large download. Most web browsers cache applets, so will be quick to load when returning to a web page. Applets also improve with use: after a first applet is run, the JVM is already running and starts quickly (the JVM will need to restart each time the browser starts afresh). It can move the work from the server to the client, making a web solution more scalable with the number of users/clients. If a standalone program (like Google Earth) talks to a web server, that server normally needs to support all prior versions for users which have not kept their client software updated. In contrast, a properly configured browser loads (and caches) the latest applet version, so there is no need to support legacy versions. The applet naturally supports the changing user state, such as figure positions on the chessboard. Developers can develop and debug an applet direct simply by creating a main routine (either in the applet's class or in a separate class) and calling init() and start() on the applet, thus allowing for development in their favorite Java SE development environment. All one has to do after that is re-test the applet in the AppletViewer program or a web browser to ensure it conforms to security restrictions. An untrusted applet has no access to the local machine and can only access the server it came from. This makes such an applet much safer to run than a standalone executable that it could replace. However, a signed applet can have full access to the machine it is running on if the user agrees. Java applets are fast - and can even have similar performance to native installed software.

Additional Disadvantages A Java applet may have any of the following disadvantages:

It requires the Java plug-in. Some browsers, notably mobile browsers running Apple iOS or Android do not run Java applets at all.[28][29]

Some organizations only allow software installed by the administrators. As a result, some users can only view applets that are important enough to justify contacting the administrator to request installation of the Java plugin. As with any client-side scripting, security restrictions may make it difficult or even impossible for an untrusted applet to achieve the desired goals. Some applets require a specific JRE. This is discouraged.[30] If an applet requires a newer JRE than available on the system, or a specific JRE, the user running it the first time will need to wait for the large JRE download to complete. Java automatic installation or update may fail if a proxy server is used to access the web. This makes applets with specific requirements impossible to run unless Java is manually updated. The Java automatic updater that is part of a Java installation also may be complex to configure if it must work through a proxy. Unlike the older applet tag, the object tag needs workarounds to write a cross-browser HTML document.

APPLET LIFE CYCLE

The Applet Life Cycle Applets follow a set life cycle during their execution. They are initialized, started, stopped, and destroyed. Initially, the Java bytecodes are run through a security check by an object running in the browser. Then, to start execution, the Java runtime calls the init() method of your applet.

The init() Method


The init() method is where your applet does much of its setup, such as defining its layout, parsing parameters, or setting the background colors. As with all of these methods, if you do not override the default methods provided in the java.applet.Applet class, they are called and do their normal duty. In the case of the init() method, if it isn't overridden, nothing goes on. In any case, it is still called. If you noticed in the supersimple example discussed earlier, you utilized the init() method to set the initial layout for the applet. For the other three methods standard in the life cycle of Java applets, you simply used the default methods in the Applet class.

The start() Method


The start() method is used mainly when implementing threads in Java. You will learn more about threading in Java in Chapter 16, "Multithreading with Java," which covers threading and multithreading. If you have no clue as to what threads are, it might be helpful to glance at the beginning of that chapter.

In Java, threading is most helpful when performing audio playing or animation. In these cases, or if you want your program to be able to stop and restart, it is helpful to override the start() method and implement your own. But if this isn't the case, you can just utilize the start() method in the Applet class.

The stop() Method


The stop() method is used to do what its name suggests: stop what is going on. In it, you usually stop() the threads that you initiated in the start() method. As is the case with the start() method, if you aren't doing anything that is threaded, you do not have to worry about implementing this method in your applet.
Tip: When a viewer leaves a page, by default, the applet continues running. Utilizing the stop() method ensures that whatever you have started in your applet stops to free up system resources.

The destroy() Method


As with the previous three methods, the destroy() method is as simple as its name. When it is called, the applet is told to free up system resources. In most general cases, you probably won't need to override this method, although there are some very special cases in which you might want more control on applet shutdowns. The life cycle of applets. It is important to note that applet design should include multiple calls to start() and stop(); init() and destroy(), however, are never called more than once.
Note: Different browsers act differently when reloading applets. Netscape Navigator 2.0 simply recalls the start() method of an applet when a viewer returns to a page that he or she has already visited. The AppletViewer included in the Java Developer's Kit instead reloads the entire applet from scratch. (This was a frustrating lesson learned late in one night of programming.) For this reason, you will probably always use the AppletViewer utility when testing your applets. You will need to use trial and error to figure out how your specific browser functions.

Ideally, I would have liked to include an example demonstrating the life cycle of a Java applet. However, to do so would mean incorporating threading, and that would complicate things more than helping. For the present time, keep these applet characteristics in mind as you develop the Order Entry System in the chapters to come.

Adding Applets to Web Pages This section covers the HTML codes specific to Java applets and how to include them in your Web pages. You should have a small amount of familiarity with the way HTML works before going through this section. If you don't, it would be best if you looked at one of the many books or Web documents available to teach HTML. A good source of information is Laura Lemay's Teach Yourself HTML in a Week. Many good Web documents teach HTML. Many of them are available on-line. This section familiarizes you with how two browsers utilize Java: Netscape Navigator version 2.0 and above, and Sun's HotJava. This section covers the tags for declaring an applet in a Web page, parameters, and other features of HTML code for implementing applets. You will be, if nothing else, entirely comfortable with the process of putting not only your own applets into your pages, but also those written by programmers (those who give you permission, of course). Netscape Navigator and Applets Netscape has pushed long and hard to continue developments above and beyond its competition in the Web browser arena. By releasing its software for free, Netscape has attracted millions of new users and continues doing so through technical advances. The 1.0.2 version of Java is included in the JDK on the CD-ROM with this book. Most surveys report that the Navigator is far and away the dominant browser on the market today.
Graphics Programming One of the most important features of java is its ability to draw graphics. We can write java applets that draw lines, figures of different shapes, images, and text in different fonts and styles. We can also incorporate different colours in display. Every applet has its own area of the screen known as canvas, where it creates its display. The size of an applets space is decided by the attributes of the <APPLET>tag. A java applet draws graphical image inside its space using the coordinate system.

The Canvas class Displaying graphics on a component Drawing lines Drawing rectangles Drawing ovals Drawing images

The Canvas class The first thing you will need is the Canvas class. This class is used to create an area in a frame to be used for displaying graphics.

NOTE: All the classes you will need to display graphics (as well as frames) are located in the java.awt package.

Canvas class methods:


void setSize(width, height) - Sets the size of the canvas void setBackground(Color c) - Sets the background color of the canvas void setForeground(Color c) - Sets the text color of the canvas

Add a canvas to a frame just like you would any other component: Canvas C1 = new Canvas(); C1.setSize(120,120); C1.setBackground(Color.white); Frame F1 = new Frame(); F1.add(C1); F1.setLayout(new FlowLayout()); F1.setSize(250,250); F1.setVisible(true);

Displaying graphics on a component Now that you have a Canvas (an area to display graphics on) how do you actually display those graphics? With the paint() method of the Frame class. The paint() method takes one attribute - an instance of the Graphics class. The Graphics class contain methods which are used for displaying graphics. The Graphics class lets a component draw on itself.
Syntax: public void paint(Graphics g){ //methods for drawing graphics here; }

Drawing lines To draw lines, the drawLine() method of the Graphics class is used. This method takes four numeric attributes - the first two indicating the x/y starting point of the line, the last two indicating the x/y ending point of the line.
Example: public void paint(Graphics g){ //draw a line starting at point 10,10 and ending at point 50,50. g.drawLine(10, 10, 50, 50); }

Drawing rectangles To draw rectangles, the drawRect() method is used. This method takes four numeric attributes - the first two indicating the x/y starting point of the rectangle, the last two indicating the width and height of the rectangle.
Example: public void paint(Graphics g){ //draw a rectangle starting at 100,100 width a width and height of 80 g.drawRect(100, 100, 80, 80); }

Filling a rectangle
By default a rectangle will have no color on the inside (it will just look like a box). You can use the fillRect() method to fill a rectangle. The fillRect() method has four numeric attributes indicating the x/y starting position to begin filling and the height and width. Set these values the same as you did for the drawRect() method to properly fill the rectangle.
Example: public void paint(Graphics g){ //draw a rectangle starting at 100,100 width a width and height of 80 g.drawRect(100, 100, 80, 80); g.fillRect(100, 100, 80, 80); }

Drawing ovals To draw ovals, the drawOval() method is used. This method takes four numeric attributes the first two indicating the x/y starting point of the oval, the last two indicating the width and height of the oval. Fill an oval with the fillOval() method which also takes four numeric attributes indicating the starting position to begin filling and the height and width. Set these values the same as you did for the drawOval() method to properly fill the oval.
Example: public void paint(Graphics g){ g.setColor(Color.gray); //draw an oval starting at 20,20 with a width and height of 100 and fill it g.drawOval(20,20, 100, 100); g.fillOval(20,20, 100, 100); }

Displaying images To display images, the Image class is used together with the Toolkit class. Use these classes to get the image to display. Use the drawImage() method to display the image.
Example: public void paint(Graphics g){ Image img1 = Toolkit.getDefaultToolkit().getImage("sky.jpg"); //four attributes: the image, x/y position, an image observer g.drawImage(img1, 10, 10, this); } An entire Java graphics program: import java.awt.*; class GraphicsProgram extends Canvas{ public GraphicsProgram(){ setSize(200, 200); setBackground(Color.white); } public static void main(String[] argS){ //GraphicsProgram class is now a type of canvas //since it extends the Canvas class //lets instantiate it GraphicsProgram GP = new GraphicsProgram(); //create a new frame to which we will add a canvas Frame aFrame = new Frame(); aFrame.setSize(300, 300); //add the canvas aFrame.add(GP); aFrame.setVisible(true); } public void paint(Graphics g) { g.setColor(Color.blue); g.drawLine(30, 30, 80, 80); g.drawRect(20, 150, 100, 100); g.fillRect(20, 150, 100, 100); g.fillOval(150, 20, 100, 100); Image img1 = Toolkit.getDefaultToolkit().getImage("sky.jpg"); g.drawImage(img1, 140, 140, this); } }

Overview
To bring data into a program, a Java program opens a stream to a data source, such as a file or remote socket, and reads the information serially. On the flip side, a program can open a stream to a data source and write to it in a serial fashion. Whether you are reading from a file or from a socket, the concept of serially reading from, and writing to different data sources is the same. For that very reason, once you understand the top level classes (java.io.Reader, java.io.Writer), the remaining classes are straightforward to work with. Character Streams versus Byte Streams Prior to JDK 1.1, the input and output classes (mostly found in the java.io package) only supported 8-bit byte streams. The concept of 16-bit Unicode character streams was introduced in JDK 1.1. While byte streams were supported via the java.io.InputStream and java.io.OutputStream classes and their subclasses, character streams are implemented by the java.io.Reader and java.io.Writer classes and their subclasses. Most of the functionality available for byte streams is also provided for character streams. The methods for character streams generally accept parameters of data type char parameters, while byte streams, you guessed it, work with byte data types. The names of the methods in both sets of classes are almost identical except for the suffix, that is, character-stream classes end with the suffix Reader or Writer and byte-stream classes end with the suffix InputStream and OutputStream. For example, to read files using character streams, you would use the java.io.FileReader class; for reading it using byte streams you would use java.io.FileInputStream. Unless you are working with binary data, such as image and sound files, you should use readers and writers (character streams) to read and write information for the following reasons:

They can handle any character in the Unicode

character set (while the byte streams are limited to ISO-Latin-1 8-bit bytes). They are easier to internationalize because they are not dependent upon a specific character encoding. They use buffering techniques internally and are therefore potentially much more efficient than byte streams.

Bridging the Gap between Byte and Character Streams To bridge the gap between the byte and character stream classes, JDK 1.1 and JDK 1.2 provide the java.io.InputStreamReader and java.io.OutputStreamWriter classes. The only purpose of these classes is to convert byte data into character-based data according to a specified (or the platform default) encoding. For example, the static data member "in" in the "System" class is essentially a handle to the Standard Input (stdin) device. If you want to wrap this inside the java.io.BufferedReader class that works with character-streams, you use InputStreamReader class as follows: BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

Various Stream Classes


As you might have guessed, thejava.io package contains the Java I/O stream classes. These classes are either the top level abstract classes or the specialized descendant implementation classes, both types are described below. Top Level Classes: java.io.Reader and java.io.Writer and Writer are the abstract parent classes for characterstream based classes in the java.io package. As discussed above, Reader classes are used to read 16-bit character streams and Writer classes are used to write to 16-bit character streams. The methods for reading and writing to streams found in these and their descendent classes (discussed in the next section) are:
Reader

int read() int read(char cbuf[]) int read(char cbuf[], int offset, int length) int write(int c) int write(char cbuf[]) int write(char cbuf[], int offset, int length)

Consider the following simple example program that demonstrates how the read and write methods can be used (this program is similar

to the MS-DOS type and Unix cat commands, that is, it displays the contents of a file):

import java.io.*; // Displays contents of a file //(e.g. java Type app.ini) public class Type { public static void main( String args[]) throws Exception { // Open input/output and setup variables FileReader fr = new FileReader(args[0]); PrintWriter pw = new PrintWriter( System.out, true); char c[] = new char[4096]; int read = 0; // Read (and print) till end of file while ((read = fr.read(c)) != -1) pw.write(c, 0, read); // Close shop fr.close(); pw.close(); } }

The following code fragment from the above program, opens the input and output streams: FileReader fr = new FileReader(args[0]); PrintWriter pw = new PrintWriter(System.out, true); The program reads the input file and displays its contents until it reaches an end-of-file condition (-1), as shown here: while ((read = fr.read(c)) != -1) pw.write(c, 0, read);

Notice the "(char cbuf[])" version of the read method. This is used here because in most cases reading a single character at a time can be approximately five times slower than reading chunks of data (array) at a time. Other Notable Methods Some other notable methods in the top-level classes include skip(int), mark(int), reset(), available(), ready() and flush(), these are described below.
skip() mark()

as the name implies, allows you to skip over characters.

and reset() provide a book-marking feature that allows you to read ahead in a stream to inspect the upcoming data but not necessarily process it. Not all streams support "marking." To determine if a stream supports marking, use the markSupported() method. tells you how many bytes are available to be read before the next read() will block. Reader.ready() is similar to the available() method, except it does not indicate how many characters are available.
InputStream.available()

The flush() method simply writes out any buffered characters (or bytes) to the destination (for example, file, or socket). Specialized Descendent Stream Classes There are several specialized stream classes that subclass from the Reader and Writer classes to provide additional functionality. For example, the BufferedReader not only provides buffered reading for efficiency but also provides methods such as "readLine()" to read a line of input. The following class hierarchy shows a few of the specialized classes found in the java.io package:
Reader

BufferedReader o LineNumberReader FilterReader o PushbackReader InputStreamReader o FileReader StringReader

The above hierarchy simply demonstrates how stream classes extend their parent classes (for example, LineNumberReader) to add more

specialized functionality. The following three tables provide a more comprehensive list of the various descendent classes found in the java.io and other packages, along with a brief description for each class. These descendent classes are divided into two categories: those that read from, or write to data sinks, and those that perform some sort of processing on the data this distinction is merely to group the classes into two logical sections, you do not have to know one way or the other when using them. Note: to give you a general idea of the various types of descendant classes provided in the JDK, these tables only show a subset of the classes found in the java.io package. The byte counterparts to the char-based classes and a few others have been intentionally skipped. Please refer to the Java Platform 1.2 API Specification (java.io) for a complete list.
Table 1. Data Sink Streams CharArrayReader and CharArrayWriter For reading from or writing to character buffers in memory For reading from or writing to files Used to forward the output of one thread as the input to another thread For reading from or writing to strings in memory

FileReader and FileWriter

PipedReader and PipedWriter

StringReader and StringWriter

Table 2. Processing Streams BufferedReader and BufferedWriter For buffered reading/writing to reduce disk/network access for more

efficiency InputStreamReader OutputStreamWriter and Provide a bridge between byte and character streams. Concatenates multiple input streams. and Use for object serialization. and For reading/writing Java native data types. For reading while keep tracking of the line number. Allows to "peek" ahead in a stream by one character. Streams (java.util.zip

SequenceInputStream

ObjectInputStream ObjectOutputStream DataInputStream DataOutputStream

LineNumberReader

PushbackReader

Table 3. package)

Miscellaneous

CheckedInputStream CheckedOutputStream

and For reading/writing and maintaining a checksum for verifying the integrity of the data. and For reading/writing data using GZIP compression/decompre ssion scheme. and For reading/writing ZIP archive files.

GZIPInputStream GZIPOutputStream

ZipInputStream ZipOutputStream

Stream Chaining

One of the most convenient features of the I/O stream classes is that they are designed to work together via stream chaining. Stream chaining is a way of connecting several stream classes together to get the data in the form required. Each class performs a specific task on the data and forwards it to the next class in the chain. Stream chaining can be very handy. For example, Divya Incorporated's 100% Pure Java backup software, BackOnline, chains several stream classes to compress, encrypt, transmit, receive, and finally store the data in a remote file. The following figure portrays chaining three classes to convert raw data into compressed and encrypted data that is stored in a local file. This is how it works: the data is written to GZIPOutputStream, which compresses the input data and sends it to CryptOutputStream. CryptOutputStream encrypts the data prior to forwarding it to FileOutputStream, which writes it out to a file. The result is a file that contains encrypted and compressed data.

The source code for the stream chaining shown in the above figure would look something like this: FileOutputStream fos = new FileOutputStream("myfile.out"); CryptOutputStream cos = new CryptOutputStream(fos); GZIPOutputStream gos = new GZIPOutputStream(cos); or simply: GZIPOutputStream gos = new GZIPOutputStream(new CryptOutputStream(new FileOutputStream("myfile.out"))); To write to chained streams, you simply call the write() method on the outermost class as follows: gos.write('a');

Similarly, when closing chained streams, you only need to close the outermost stream class because the close() call is automatically trickled through all the chained classes; in the example above, you would simply call the close() method on the GZIPOutputStream class.

This page describes the basics of reading and writing data one character at a time or one line at a time in Java

Basic Input and Output Concepts Opening a Stream for Output Writing to an Output Stream Closing a Stream A Complete Output Example Output with System.out Opening a Stream for Input Reading from an Input Stream A Complete Input Example A Complete Input/Output Example Testing I/O-based Operations Dealing with Exceptions

Basic Input and Output Concepts Java provides an extensive library of classes for managing input and output of all forms of data. These classes are built around a stream model. You can think of a stream as a sequence of characters (in the case of textual data) or bytes (in the case of binary data) that can be accessed in order. Input operations are framed in terms of reading from a stream in a three-step process: 1. open the stream, 2. read data items from the stream front to back in sequence, and 3. close the stream. Output operations are framed in terms of writing to a stream in a three-step process: 1. open the stream, 2. write data onto the end of the stream in sequence, and 3. close the stream. To use Java's input/output classes, make sure that in addition to importing any other necessary packages, also import the java.io package and the java.util package : import
java.io.*; import java.util.*;

Opening a Stream for Output In this class, we will only deal with textual, human-readable output. The main class we will use for generating output is Java's PrintWriter class, from the java.io package. To create a PrintWriter, we'll use a utility method in the IOHelper class from the cs1705 package: PrintWriter outStream = IOHelper.createPrintWriter("output.txt"); This line declares a new name, outStream and creates a new PrintWriter object that sends output to a brand new file in the file system. If a file with the name already exists in the project directory it will be deleted before a new empty file with the same name is created. The PrintWriter object provides formatting and conversion operations. A PrintWriter object is designed to send its output to a stream. It does not know (or care) whether the stream is connected to a disk file or a network connection or other device. The IOHelper class provides a few other methods for creating PrintWriter objects, including methods that append to an existing file instead of overwriting it, or streams that are connected to the console for output. Writing to an Output Stream Three basic methods provided by PrintWriter objects provide virtually all of the output capabilities you will need in this course:

writes the specified <value> to the given <stream>. There are actually many versions of this method that support every possible type of <value> you might want to print. <stream>.println(<value>); writes the specified <value> to the given <stream>, and then follows it by writing a "line terminator" to mark the end of the current line (Java writes an appropriate line termination character sequence based on the current operating system's text file format conventions). As with print(), you can provide any type of value to println(). You can even call println() without giving any argument at all, for example, to terminate the current line after several previous print() messages. <stream>.write(<value>); writes a single character specified by an integer <value>. This operation is most often used when you are producing output one character at a time, rather than in larger chunks. However, If you pass an entire String value to write() instead on an int value, then the entire string will be written to the PrintWriter() just as if you had used print().
<stream>.print(<value>);

For example: outStream.print("This is a message, and "); outStream.println("these words appear on the same line as those above"); outStream.println(100 / 2); // prints the value "50" outStream.write(65); // writes the letter 'A', whose ASCII code is 65 Closing a Stream Once you have completed all of the operations you intend to carry out on a given stream, the stream should be closed. Closing the stream frees up operating system resources used to

connect to and communicate with the stream, and makes sure that any buffered data you have written to the stream is flushed out to the physical device involved (if any). Closing a stream is easy: outStream.close(); You should close both input streams and output streams this way. In many simple programs, a good rule of thumb is to make sure that the method that creates the stream should also be the one responsible for closing it. Also, note that in some cases, close() may throw an exception. If you write a call to close() and the compiler complains about a possible IOException, refer to the section on "Dealing with Exceptions" below. A Complete Output Example We can put all these pieces together to show how to generate output to a file, for example. Let's say we want to create a file called output.txt containing some output from our program. We can do it in one method like this (don't forget to import java.io.* in your class): public void printResultFile(int result) { PrintWriter out = IOHelper.createPrintWriter("output.txt"); out.println("This is the first line of output."); out.print("The result is: "); out.print(result); out.println(); out.close(); } If called with a specific argument, like printResultFile(42);, the method will produce a file called output.txt in your BlueJ project directory containing these lines: This is the first line of output. The result is: 42 At other times, when there is a lot of output to produce, you may want to place all the println() calls in one or more other methods. Then you can pass a PrintWriter object as a parameter, as in this example: public void printResultFile() { PrintWriter out = IOHelper.createPrintWriter("output.txt"); printHeader(out); printData(out); out.close(); } public void printHeader(PrintWriter outStream) {

outStream.println("This is the output for ..."); // other output commands go here. } public void printData(PrintWriter outStream) { outStream.print(/* ... */); // more, as needed ... } Output with System.out It turns out that printing to the terminal is such a common action that Java provides a preinitialized output stream just for that purpose, called System.out. The advantage of System.out is that it is already declared and always ready for use, and your program is not responsible for closing it. As a result, you can directly call print(), println(), or write() on System.out anywhere you like. This is often used as a simple but effective debugging technique, allowing you to print out information as your program executes: System.out.println("beginning the code ..."); ... if (someCondition()) { System.out.println("someCondition() is true"); x = ...; System.out.println("x = " + x); } else { System.out.println("someCondition() is false"); y = ...; System.out.println("y = " + y); } Above, notice the way the plus operator (+) was used to combine a textual string with another value to make a larger message. This is a nice feature of Java--the plus operator works to "concatenate" two strings into a larger string by placing one after the other. Further, when you concatenate a string with any other value, the other value is converted into a humanreadable string representation first. Try it, you'll like it! The advantages of System.out are that it is always ready and available, and it is so easy to use. Creation and setup of this object is already provided for you by Java's virtual machine, and cleanup is handled automatically as well. Further, since the print(), println(), and write() methods do not throw any exceptions (whether called on System.out, or on any PrintWriter you create yourself), you do not need to include a try/catch block around your output messages. There are also a few disadvantages to using System.out, however. First, when your code writes directly to System.out, it is difficult to change the "destination," say, in order to make the code write to one or more named files, or make the code write into an internal data structure so that the information can be used elsewhere in the program. Second, System.out is not actually a PrintWriter object. Instead, it is a Java.io.PrintStream, which supports virtually all of the same methods, but is not quite the same.

As a result, here are some recommendations for output in this course:


When you just want to produce simple messages in the terminal window to help debug a problem with your code, use System.out. When you just want to interactively prompt the user for some value(s), use System.out. When your program is supposed to produce a series of output lines in a file, use a PrintWriter. When your program is supposed to produce a series of output lines that may go either to the terminal window or to a file, write one or more methods that use a PrintWriter provided as a parameter. You can always call such a method and provide it with a PrintWriter produced with a System.out stream in order to produce output on the screen (see the IOHelper.createConsoleWriter() method). Alternatively, you can pass in a PrintWriter connected to a file instead (or even one connected to an internet socket for communicating with another program on another machine!).

Opening a Stream for Input The main class we will use for reading input is Java's Scanner class, from the java.io package, (the Scanner class is a new util class that was added to Java 1.5). Creating a Scanner is simple: Scanner inStream = IOHelper.createScanner("input.txt"); This line declares a new name, inStream and creates a Scanner object that reads characters from the file. The createScanner() method opens files using path names relative to your BlueJ project directory, so the file called input.txt should be located there. You can provide a fully qualified path name instead of a relative path name if you desire. The java.io package offers a rich inheritance hierarchy of classes for reading from text files. The Scanner class was added to simplify text input and is thus preferred over the other classes. Reading from an Input Stream Several methods provided by Scanner objects provide virtually all of the input capabilities you will need in this course:
<scanner>.hasNext(); Returns true if this <scanner>.next(); Finds and returns the

scanner has another token in its input. next complete token (i.e., by default the next whitespace delimited string as a String object) from this scanner. A NoSuchElementException is thrown if no more tokens are available, (i.e., you have reached the end of input). <scanner>.hasNextLine(); Returns true if this scanner has another line in its input. <scanner>.nextLine(); Finds and returns the next complete line A NoSuchElementException is thrown if no more tokens are available, (i.e., you have reached the end of input). <scanner>.hasNext<PrimitiveType>(); The <PrimitiveType> can be replaced by Double, Float, Int, etc. Returns true if this scanner has another token in its input and it can be interpreted as a value of the <PrimitiveType>.

The <PrimitiveType> can be replaced by Double, Float, Int, etc. The method scans the next token of the input as an <PrimitiveType> and returns back the corresponding <PrimitiveType> value. It throws a InputMismatchException exception if the next token does not match the <PrimitiveType>, or if the value scanned is out of range. It also throws a NoSuchElementException if no more tokens are available. <scanner>.useDelimiter(String pattern); by default whitespace (spaces, tabs & new line characters) are used as delimiters for separating the input into tokens to return. This method allows the user to set the delimiter characters to whatever they wish for breaking up the input. <scanner>.close(); closes the scanner to release system resources being used by the scanner.
<scanner>.next<PrimitiveType>();

To use these methods, normally you will process the input by scanning one line at a time and then scanning the line for the desired tokens. For example: Scanner inStream = IOHelper.createScanner("input.txt"); if (inStream.hasNextLine()) // NOT at the end of the stream, more input is available { String thisLine = inStream.nextLine(); // Get an entire line Scanner line = new Scanner(thisLine); // Create a scanner to process the line if (line.hasNextInt()) // Check for the next whitespace delimited int { System.out.println(line.nextInt()); } } inStream.close(); Notice how the existence of each input is checked before it is extracted to avoid exceptions. Also, if you have programmed in another language before, note that characters in Java are encoded using unicode, a 16-bit character code. Programmers in other languages are probably more familiar with ASCII, the American Standard Code for Information Interchange, which is a 7-bit character code. Fortunately, the first 128 codes in unicode are equivalent to the entire ASCII character set. For American users, ASCII values may thus be freely used when reading and writing character-by-character without error, although this approach does not directly extend to programs written for an international audience. The Scanner class can be used to read from any input stream, including files, the keyboard through the terminal window, or even URLs. To read from the keyboard, for example: Scanner keyBoard = IOHelper.createKeyboardScanner(); keyBoard.useDelimiter("\n"); System.out.print("Enter your name: "); // Prompt the user String name = keyBoard.next(); System.out.println("Hello " + name); // Echo input When performing interactive keyboard input there is no need to check for the existence of the next token. The scanner will automatically block (i.e., wait) for the user to enter input. Scanners can also be used to read from a file that is publicly available on the Web if you know the URL: Scanner inWebFile "http://server.subdomain.domain/dir/file.txt"); while (inWebFile.hasNextLine()) = IOHelper.createScannerForURL(

{ String line = inWebFile.nextLine(); System.out.println(line); // Echo input } inWebFile.close(); A Complete Input Example We can put all these pieces together to show how to read input from a file one character at a time, for example. Let's say we want to read the characters from a file called input.txt. We can do it in one method like this (don't forget to import java.io.* and java.util.* in your class): public void readChars() { Scanner in = IOHelper.createScanner("input.txt"); while (in.hasNextLine()) // NOT at the end of the stream, more input is available { String thisLine = in.nextLine(); // Get an entire line for (int index=0; index < thisLine.length(); index++) { char ch = thisLine.charAt(index); System.out.print(ch); } System.out.println(); } in.close(); } At other times, when there is a lot of output to produce, you may want to place all the read() calls in one or more other methods. Then you can pass a Scanner object as a parameter: public void processInputFile() { Scanner in = IOHelper.createScanner("input.txt"); readHeader(in); readData(in); in.close(); } public void readHeader(Scanner inStream) { String nextLine = null; if (inStream.hasNextLine()) { nextLine = inStream.nextLine(); // other input commands go here. } } public void readData(Scanner inStream) { String nextLine = null; if (inStream.hasNext() ) { nextLine = inStream.nextLine(); // more, as needed ... } }

A Complete Input/Output Example Often, it is necessary to combine the processes of reading from some source and writing to some destination. Here is a simple example that copies an input file character by character: import cs1705.*; import java.io.*; import java.util.*; // ------------------------------------------------------------------------/** * Shows how to read/write a file one character at a time. * @author Dwight Barnette * @version 2006.03.09 */ public class CopyFileByLine { // ---------------------------------------------------------/** * Copy the source file to the specified destination file. * @param fromFile the name of the file to copy from * @param toFile the name of the file to copy to */ public void copyFile(String fromFile, String toFile) { Scanner source = IOHelper.createScanner(inFile); PrintWriter dest = IOHelper.createPrintWriter(toFile); while (source.hasNextLine()) { String thisLine = source.nextLine(); for (int index = 0; index < thisLine.length(); index++) { char ch = thisLine.charAt(index); dest.print(ch); } } source.close(); dest.close(); } } Testing I/O-based Operations When it comes to testing, remember to write one or more test cases for each method that your write in your solution. Preferably, you should write these tests before (or as) you write the method itself, rather than saving testing until your code works. As you work on larger and larger programs, it is important to build skills in convincing yourself that the parts you have already written work as you intend, even if the full solution has not been completed. For testing programs that read input or produce output, it seems difficult when the program operates directly on the console, since it is hard to "assert" what should come out on the screen. Plus you would always need to be present to "type in" the required input sequence. To

make these tests fully automated, however, don't write tests that use System.out or that read from an external source. Instead, simply create a Scanner to read from a fixed input string as part of your test case. For output, create a PrintWriter that can write to a String object instead of the console.
To make these tasks easy, the TestCase base class from which all your test cases inherit provides a few helper methods for you:

takes a string and uses it to create a Scanner for your test to use as input. The scanner gets cleared automatically before each test case, so you can call this in setUp() if you want to use the same input sequence for all your tests. in(); returns the current Scanner being used for input. You can use this, in combination with setIn() to set up an input stream for your own input-based methods inside test cases. The scanner gets cleared automatically at the start of each test case. out(); returns a PrintWriter that you can use for output. This print writer captures all of its own output for later use in assertions, and its contents are reset before each test case.
setIn(<contents>);

As an example, consider the following test method (which assumes your text fixture includes a doIt object created from some DoIt class that provides a method called processSomeInput()): public void testProcessSomeInput() { // set up the input stream setIn("some test input"); // run the method to get results doIt.processSomeInput(in()); // test that the result is what was expected assert...( ... ); } Suppose there was a produceOutput() method that wrote to a PrintWriter: public void testProcessSomeInput() { // run the method to get results doIt.produceOutput(out()); // test that the result is what was expected assertEquals("what I expect", out().getHistory()); } Finally, you can even deal with both input and output at the same time: public void testProcessSomeInput() { setIn("some test input"); // run the method to get results doIt.processSomeStuff(in(), out()); // test that the result is what was expected assertEquals("output I want", out().getHistory()); } The TestCase base class provides similar methods for setting System.in or retrieving the history from System.out. See the javadoc for TestCase for more details.

Dealing with Exceptions When your program deals with external factors, like files on disk, sometimes errors or other conditions that cannot be predicted in advance may arise. For example:

A person may type in incorrect information for your program to read. A file that was around before may have accidentally been deleted. There may not be enough hard disk space remaining to write all the data you intend. A person may enter an incorrect file name for your program to use--one for a file that does not exist.

As a result, java uses exceptions to indicate when something goes wrong. An exception is an object "thrown" into the middle of your program that interrupts the normal flow of execution. Normally, an exception causes the remainder of what you were doing to be aborted and skipped, and program execution instead picks up with an exception handler that has a chance to take appropriate action. While we are not going to study exceptions extensively in this course, they are a fact of life embedded deep in some parts of Java's I/O library. Often, you can write code that reads or writes data that will not throw exceptions. However, if you try to call an I/O method that may produce an exception, the compiler will complain: unreported exception java.io.IOException; must be caught or declared to be thrown Fortunately, there is a simple way to deal with this issue when it happens. If you get this message, you can wrap the three-step process (open stream, read or write, close) in the following Java syntax: try { // open stream ... // operate on stream contents ... // close stream } catch (Exception e) { e.printStackTrace();

CONCEPTS OF STREAMS IN JAVA Overview


To bring data into a program, a Java program opens a stream to a data source, such as a file or remote socket, and reads the information serially. On the flip side, a program can open a stream to a data source and write to it in a serial fashion. Whether you are reading from a file or from a socket, the concept of serially reading from, and writing to different data sources is the same. For that very reason, once you understand the top level classes (java.io.Reader, java.io.Writer), the remaining classes are straightforward to work with. Character Streams versus Byte Streams Prior to JDK 1.1, the input and output classes (mostly found in the java.io package) only supported 8-bit byte streams. The concept of 16-bit Unicode character streams was introduced in JDK 1.1. While byte streams were supported via the java.io.InputStream

and java.io.OutputStream classes and their subclasses, character streams are implemented by the java.io.Reader and java.io.Writer classes and their subclasses. Most of the functionality available for byte streams is also provided for character streams. The methods for character streams generally accept parameters of data type char parameters, while byte streams, you guessed it, work with byte data types. The names of the methods in both sets of classes are almost identical except for the suffix, that is, character-stream classes end with the suffix Reader or Writer and byte-stream classes end with the suffix InputStream and OutputStream. For example, to read files using character streams, you would use the java.io.FileReader class; for reading it using byte streams you would use java.io.FileInputStream. Unless you are working with binary data, such as image and sound files, you should use readers and writers (character streams) to read and write information for the following reasons:
They can handle any character in the Unicode character set (while the byte streams are limited to ISO-Latin-1 8-bit bytes). They are easier to internationalize because they are not dependent upon a specific character encoding. They use buffering techniques internally and are therefore potentially much more efficient than byte streams.

Bridging the Gap Between Byte and Character Streams To bridge the gap between the byte and character stream classes, JDK 1.1 and JDK 1.2 provide the java.io.InputStreamReader and java.io.OutputStreamWriter classes. The only purpose of these classes is to convert byte data into character-based data according to a specified (or the platform default) encoding. For example, the static data member "in" in the "System" class is essentially a handle to the Standard Input (stdin) device. If you want to wrap this inside the java.io.BufferedReader class that works with character-streams, you use InputStreamReader class as follows: BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

Various Stream Classes


As you might have guessed, thejava.io package contains the Java I/O stream classes. These classes are either the top level abstract classes or the specialized descendant implementation classes, both types are described below. Top Level Classes: java.io.Reader and java.io.Writer
Reader and Writer are the abstract parent classes for character-stream based classes in the java.io package. As discussed above, Reader classes are used to read 16-bit character streams and Writer classes are used to write to 16-bit character streams. The methods for

reading and writing to streams found in these and their descendent classes (discussed in the next section) are:

int read() int read(char cbuf[]) int read(char cbuf[], int offset, int length) int write(int c) int write(char cbuf[]) int write(char cbuf[], int offset, int length)

Consider the following simple example program that demonstrates how the read and write methods can be used (this program is similar to the MS-DOS type and Unix cat commands, that is, it displays the contents of a file):

import java.io.*;

// Displays contents of a file //(e.g. java Type app.ini) public class Type { public static void main( String args[]) throws Exception { // Open input/output and setup variables FileReader fr = new FileReader(args[0]); PrintWriter pw = new PrintWriter( System.out, true); char c[] = new char[4096]; int read = 0;

// Read (and print) till end of file while ((read = fr.read(c)) != -1) pw.write(c, 0, read);

// Close shop fr.close(); pw.close(); } }

The following code fragment from the above program, opens the input and output streams: FileReader fr = new FileReader(args[0]); PrintWriter pw = new PrintWriter(System.out, true); The program reads the input file and displays its contents until it reaches an end-of-file condition (-1), as shown here: while ((read = fr.read(c)) != -1) pw.write(c, 0, read); Notice the "(char cbuf[])" version of the read method. This is used here because in most cases reading a single character at a time can be approximately five times slower than reading chunks of data (array) at a time. Other Notable Methods Some other notable methods in the top-level classes include skip(int), mark(int), reset(), available(), ready() and flush(), these are described below.
skip() mark()

as the name implies, allows you to skip over characters.

and reset() provide a book-marking feature that allows you to read ahead in a stream to inspect the upcoming data but not necessarily process it. Not all streams support "marking." To determine if a stream supports marking, use the markSupported() method.
InputStream.available() tells you how many bytes next read() will block. Reader.ready() is similar to

are available to be read before the the available() method, except it

does not indicate how many characters are available. The flush() method simply writes out any buffered characters (or bytes) to the destination (for example, file, or socket).

Specialized Descendent Stream Classes There are several specialized stream classes that subclass from the Reader and Writer classes to provide additional functionality. For example, the BufferedReader not only provides buffered reading for efficiency but also provides methods such as "readLine()" to read a line of input. The following class hierarchy shows a few of the specialized classes found in the java.io package:
Reader BufferedReader LineNumberReader FilterReader o PushbackReader InputStreamReader o FileReader StringReader
o

The above hierarchy simply demonstrates how stream classes extend their parent classes (for example, LineNumberReader) to add more specialized functionality. The following three tables provide a more comprehensive list of the various descendent classes found in the java.io and other packages, along with a brief description for each class. These descendent classes are divided into two categories: those that read from, or write to data sinks, and those that perform some sort of processing on the datathis distinction is merely to group the classes into two logical sections, you do not have to know one way or the other when using them. Note: to give you a general idea of the various types of descendant classes provided in the JDK, these tables only show a subset of the classes found in the java.io package. The byte counterparts to the char-based classes and a few others have been intentionally skipped. Please refer to the Java Platform 1.2 API Specification (java.io) for a complete list.
Table 1. Data Sink Streams CharArrayReader and CharArrayWriter For reading from or writing to character buffers in memory For reading from or writing to files Used the one the to forward output of thread as input to

FileReader and FileWriter

PipedReader and PipedWriter

another thread StringReader and StringWriter For reading from or writing to strings in memory

Table 2. Processing Streams BufferedReader and BufferedWriter For buffered reading/writing to reduce disk/network access for more efficiency and Provide a bridge between byte and character streams. Concatenates multiple input streams. and Use for object serialization. and For reading/writing Java native data types. For reading while keep tracking of the line number. Allows to "peek" ahead in a stream by one character. Streams (java.util.zip

InputStreamReader OutputStreamWriter

SequenceInputStream

ObjectInputStream ObjectOutputStream DataInputStream DataOutputStream

LineNumberReader

PushbackReader

Table 3. package)

Miscellaneous

CheckedInputStream CheckedOutputStream

and For reading/writing and maintaining a checksum for verifying

the integrity data. GZIPInputStream GZIPOutputStream

of

the

and For reading/writing data using GZIP compression/decompre ssion scheme. and For reading/writing ZIP archive files.

ZipInputStream ZipOutputStream

Stream Chaining
One of the most convenient features of the I/O stream classes is that they are designed to work together via stream chaining. Stream chaining is a way of connecting several stream classes together to get the data in the form required. Each class performs a specific task on the data and forwards it to the next class in the chain. Stream chaining can be very handy. For example, Divya Incorporated's 100% Pure Java backup software, BackOnline, chains several stream classes to compress, encrypt, transmit, receive, and finally store the data in a remote file. The following figure portrays chaining three classes to convert raw data into compressed and encrypted data that is stored in a local file. This is how it works: the data is written to GZIPOutputStream, which compresses the input data and sends it to CryptOutputStream. CryptOutputStream encrypts the data prior to forwarding it to FileOutputStream, which writes it out to a file. The result is a file that contains encrypted and compressed data.

The source code for the stream chaining shown in the above figure would look something like this: FileOutputStream fos = new FileOutputStream("myfile.out"); CryptOutputStream cos = new CryptOutputStream(fos); GZIPOutputStream gos = new GZIPOutputStream(cos); or simply:

GZIPOutputStream gos = new GZIPOutputStream(new CryptOutputStream(new FileOutputStream("myfile.out"))); To write to chained streams, you simply call the write() method on the outermost class as follows: gos.write('a'); Similarly, when closing chained streams, you only need to close the outermost stream class because the close() call is automatically trickled through all the chained classes; in the example above, you would simply call the close() method on the GZIPOutputStream class. Reading, Writing, and Creating Files This page discusses the details of reading, writing, creating, and opening files. There are a wide array of file I/O methods to choose from. To help make sense of the API, the following diagram arranges the file I/O methods by complexity.

File I/O Methods Arranged from Less Complex to More Complex

On the far left of the diagram are the utility methods readAllBytes, readAllLines, and the write methods, designed for simple, common cases. To the right of those are the methods used to iterate over a stream or lines of text, such as newBufferedReader, newBufferedWriter, then newInputStream and newOutputStream. These methods are interoperable with the java.io package. To the right of those are the methods for dealing with ByteChannels, SeekableByteChannels, and ByteBuffers, such as the newByteChannel method. Finally, on the far right are the methods that use FileChannel for advanced applications needing file locking or memory-mapped I/O.
Note: The methods for creating a new file enable you to specify an optional set of initial attributes for the file. For example, on a file system that supports the POSIX set of standards (such as UNIX), you can specify a file owner, group owner, or file permissions at the time the file is created. The Managing Metadata page explains file attributes, and how to access and set them.

This page has the following topics:


The OpenOptions Parameter Commonly Used Methods for Small Files Buffered I/O Methods for Text Files Methods for Unbuffered Streams and Interoperable with java.io APIs Methods for Channels and ByteBuffers Methods for Creating Regular and Temporary Files

The OpenOptions Parameter Several of the methods in this section take an optional OpenOptions parameter. This parameter is optional and the API tells you what the default behavior is for the method when none is specified. The following StandardOpenOptions enums are supported:

WRITE Opens the file for write access. APPEND Appends the new data to the end of the file. This option is used with the WRITE or CREATE options. TRUNCATE_EXISTING Truncates the file to zero bytes. This option is used with the WRITE option. CREATE_NEW Creates a new file and throws an exception if the file
already exists. CREATE Opens the file if it exists or creates a new file if it does not. DELETE_ON_CLOSE Deletes the file when the stream is closed. This option is useful for temporary files. SPARSE Hints that a newly created file will be sparse. This advanced option is honored on some file systems, such as NTFS, where large files with data "gaps" can be stored in a more efficient manner where those empty gaps do not consume disk space. SYNC Keeps the file (both content and metadata) synchronized with the underlying storage device. DSYNC Keeps the file content synchronized with the underlying storage device.

Commonly Used Methods for Small Files

Reading All Bytes or Lines from a File


If you have a small-ish file and you would like to read its entire contents in one pass, you can use the readAllBytes(Path) or readAllLines(Path, Charset) method. These methods take care of most of the work for you, such as opening and closing the stream, but are not intended for handling large files. The following code shows how to use the readAllBytes method: Path file = ...; byte[] fileArray; fileArray = Files.readAllBytes(file);

Writing All Bytes or Lines to a File

You can use one of the write methods to write bytes, or lines, to a file.

write(Path, byte[], OpenOption...) write(Path, Iterable< extends CharSequence>, Charset, OpenOption...)

The following code snippet shows how to use a write method. Path file = ...; byte[] buf = ...; Files.write(file, buf); Buffered I/O Methods for Text Files The java.nio.file package supports channel I/O, which moves data in buffers, bypassing some of the layers that can bottleneck stream I/O.

Reading a File by Using Buffered Stream I/O


The newBufferedReader(Path, Charset) method opens a file for reading, returning a BufferedReader that can be used to read text from a file in an efficient manner. The following code snippet shows how to use the newBufferedReader method to read from a file. The file is encoded in "US-ASCII." Charset charset = Charset.forName("US-ASCII"); try (BufferedReader reader = Files.newBufferedReader(file, charset)) { String line = null; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException x) { System.err.format("IOException: %s%n", x); }

Writing a File by Using Buffered Stream I/O


You can use the newBufferedWriter(Path, Charset, OpenOption...) method to write to a file using a BufferedWriter. The following code snippet shows how to create a file encoded in "US-ASCII" using this method: Charset charset = Charset.forName("US-ASCII"); String s = ...; try (BufferedWriter writer = Files.newBufferedWriter(file, charset)) { writer.write(s, 0, s.length()); } catch (IOException x) { System.err.format("IOException: %s%n", x); }

Methods for Unbuffered Streams and Interoperable with java.io APIs

Reading a File by Using Stream I/O


To open a file for reading, you can use the newInputStream(Path, OpenOption...) method. This method returns an unbuffered input stream for reading bytes from the file. Path file = ...; try (InputStream in = Files.newInputStream(file); BufferedReader reader = new BufferedReader( new InputStreamReader(in))) { String line = null; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException x) { System.err.println(x); }

Creating and Writing a File by Using Stream I/O


You can create a file, append to a file, or write to a file by using the newOutputStream(Path, OpenOption...) method. This method opens or creates a file for writing bytes and returns an unbuffered output stream. The method takes an optional OpenOption parameter. If no open options are specified, and the file does not exist, a new file is created. If the file exists, it is truncated. This option is equivalent to invoking the method with the CREATE and TRUNCATE_EXISTING options. The following code snippet opens a log file. If the file does not exist, it is created. If the file exists, it is opened for appending. import static java.nio.file.StandardOpenOption.*; Path logfile = ...; // Convert the string to a // byte array. String s = ...; byte data[] = s.getBytes(); try (OutputStream out = new BufferedOutputStream(logfile.newOutputStream(CREATE, APPEND))) { ... out.write(data, 0, data.length); } catch (IOException x) { System.err.println(x); }

Methods for Channels and ByteBuffers

Reading and Writing Files by Using Channel I/O


While stream I/O reads a character at a time, channel I/O reads a buffer at a time. The ByteChannel interface provides basic read and write functionality. A SeekableByteChannel is a ByteChannel that has the capability to maintain a position in the channel and to change that position. A SeekableByteChannel also supports truncating the file associated with the channel and querying the file for its size. The capability to move to different points in the file and then read from or write to that location makes random access of a file possible. See Random Access Files for more information. There are two methods for reading and writing channel I/O.

newByteChannel(Path, OpenOption...) newByteChannel(Path, Set<? extends OpenOption>, FileAttribute<?>...)

Note: The newByteChannel methods return an instance of a SeekableByteChannel. With a default file system, you can cast this seekable byte channel to a FileChannel providing access to more advanced features such mapping a region of the file directly into memory for faster access, locking a region of the file so other processes cannot access it, or reading and writing bytes from an absolute position without affecting the channel's current position.

Both newByteChannel methods enable you to specify a list of OpenOption options. The same open options used by the newOutputStream methods are supported, in addition to one more option: READ is required because the SeekableByteChannel supports both reading and writing. Specifying READ opens the channel for reading. Specifying WRITE or APPEND opens the channel for writing. If none of these options is specified, the channel is opened for reading. The following code snippet reads a file and prints it to standard output: // Defaults to READ try (SeekableByteChannel sbc = Files.newByteChannel(file)) { ByteBuffer buf = ByteBuffer.allocate(10); // Read the bytes with the proper // encoding for this platform. If // you skip this step, you might // see something that looks like // Chinese characters when you // expect Latin-style characters. String encoding = System.getProperty("file.encoding"); while (sbc.read(buf) > 0) { buf.rewind();

System.out.print(Charset.forName(encoding).decode(buf)); buf.flip(); } } catch (IOException x) { System.out.println("caught exception: " + x); The following code snippet, written for UNIX and other POSIX file systems, creates a log file with a specific set of file permissions. This code creates a log file or appends to the log file if it already exists. The log file is created with read/write permissions for owner and read only permissions for group. import static java.nio.file.StandardCopyOption.*; // Create the set of options // for appending to the file. Set<OpenOptions> options = new HashSet<OpenOption>(); options.add(APPEND); options.add(CREATE); // Create the custom permissions attribute. Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-r------"); FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms); // Convert the string to a ByteBuffer. String s = ...; byte data[] = s.getBytes(); ByteBuffer bb = ByteBuffer.wrap(data); try (SeekableByteChannel sbc = Files.newByteChannel(file, options, attr)) { sbc.write(bb); } catch (IOException x) { System.out.println("exception thrown: " + x); } Methods for Creating Regular and Temporary Files

Creating Files
You can create an empty file with an initial set of attributes by using the createFile(Path, FileAttribute<?>) method. For example, if, at the time of creation, you want a file to have a particular set of file permissions, use the createFile method to do so. If you do not specify any attributes, the file is created with default attributes. If the file already exists, createFile throws an exception. In a single atomic operation, the createFile method checks for the existence of the file and creates that file with the specified attributes, which makes the process more secure against malicious code.

The following code snippet creates a file with default attributes: Path file = ...; try { // Create the empty file with // default permissions, etc. Files.createFile(file); } catch (FileAlreadyExistsException x) { System.err.format("file named %s" + " already exists%n", file); } catch (IOException x) { // Some other sort of failure, // such as permissions. System.err.format("createFile error: %s%n", x); } POSIX File Permissions has an example that uses createFile(Path, FileAttribute<?>) to create a file with pre-set permissions. You can also create a new file by using the newOutputStream methods, as described in Creating and Writing a File using Stream I/O. If you open a new output stream and close it immediately, an empty file is created.

Creating Temporary Files


You can create a temporary file using one of the following createTempFile methods:

createTempFile(Path, String, String, FileAttribute<?>) createTempFile(String, String, FileAttribute<?>)

The first method allows the code to specify a directory for the temporary file and the second method creates a new file in the default temporary-file directory. Both methods allow you to specify a suffix for the filename and the first method allows you to also specify a prefix. The following code snippet gives an example of the second method: try { Path tempFile = Files.createTempFile(null, ".myapp"); System.out.format("The temporary file" + " has been created: %s%n", tempFile) ; } catch (IOException x) { System.err.format("IOException: %s%n", x); } The result of running this file would be something like the following: The temporary file has been created: /tmp/509668702974537184.myapp The specific format of the temporary file name is platform specific. RANDAM ACCESS FILES IN JAVA

java.io Class RandomAccessFile java.lang.Object java.io.RandomAccessFile

All Implemented Interfaces: DataInput, DataOutput public class RandomAccessFile extends Object implements DataOutput, DataInput

Instances of this class support both reading and writing to a random access file. A random access file behaves like a large array of bytes stored in the file system. There is a kind of cursor, or index into the implied array, called the file pointer; input operations read bytes starting at the file pointer and advance the file pointer past the bytes read. If the random access file is created in read/write mode, then output operations are also available; output operations write bytes starting at the file pointer and advance the file pointer past the bytes written. Output operations that write past the current end of the implied array cause the array to be extended. The file pointer can be read by the getFilePointer method and set by the seek method. It is generally true of all the reading routines in this class that if end-of-file is reached before the desired number of bytes has been read, an EOFException (which is a kind of IOException) is thrown. If any byte cannot be read for any reason other than end-of-file, an IOException other than EOFException is thrown. In particular, an IOException may be thrown if the stream has been closed.
Since: JDK1.0

Constructor Summary RandomAccessFile(File file, String mode) Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument. RandomAccessFile(String name, String mode) Creates a random access file stream to read from, and optionally to write to, a file with the specified name.

Method Summary

void

close()

Closes this random access file stream and releases any system resources associated with the stream. FileChanne getChannel() l Returns the unique FileChannel object associated with this file. FileDescrip getFD() tor Returns the opaque file descriptor object associated with this stream.

long

getFilePointer() Returns the current offset in this file. length() Returns the length of this file. read() Reads a byte of data from this file. read(byte[] b) Reads up to b.length bytes of data from this file into an array of bytes. read(byte[] b, int off, int len) Reads up to len bytes of data from this file into an array of bytes. readBoolean() Reads a boolean from this file. readByte() Reads a signed eight-bit value from this file. readChar() Reads a Unicode character from this file. readDouble() Reads a double from this file. readFloat() Reads a float from this file. readFully(byte[] b) Reads b.length bytes from this file into the byte array, starting at the current file pointer.

long

int

int

int

boolean

byte

char

double

float

void

void

readFully(byte[] b, int off, int len) Reads exactly len bytes from this file into the byte array, starting at the current file pointer. readInt() Reads a signed 32-bit integer from this file. readLine() Reads the next line of text from this file. readLong() Reads a signed 64-bit integer from this file. readShort() Reads a signed 16-bit number from this file. readUnsignedByte() Reads an unsigned eight-bit number from this file. readUnsignedShort() Reads an unsigned 16-bit number from this file. readUTF() Reads in a string from this file. seek(long pos) Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs. setLength(long newLength) Sets the length of this file. skipBytes(int n) Attempts to skip over n bytes of input discarding the skipped bytes. write(byte[] b) Writes b.length bytes from the specified byte array to this file, starting at the current file pointer. write(byte[] b, int off, int len) Writes len bytes from the specified byte array starting at offset off to this file. write(int b) Writes the specified byte to this file.

int

String

long

short

int

int

String

void

void

int

void

void

void

void

writeBoolean(boolean v) Writes a boolean to the file as a one-byte value. writeByte(int v) Writes a byte to the file as a one-byte value. writeBytes(String s) Writes the string to the file as a sequence of bytes. writeChar(int v) Writes a char to the file as a two-byte value, high byte first. writeChars(String s) Writes a string to the file as a sequence of characters. writeDouble(double v) Converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the file as an eight-byte quantity, high byte first. writeFloat(float v) Converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the file as a four-byte quantity, high byte first. writeInt(int v) Writes an int to the file as four bytes, high byte first. writeLong(long v) Writes a long to the file as eight bytes, high byte first. writeShort(int v) Writes a short to the file as two bytes, high byte first. writeUTF(String str) Writes a string to the file using UTF-8 encoding in a machineindependent manner.

void

void

void

void

void

void

void

void

void

void

Methods inherited from class java.lang.Object clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

RandomAccessFile
public RandomAccessFile(String name, String mode) throws FileNotFoundException
Creates a random access file stream to read from, and optionally to write to, a file with the specified name. A new FileDescriptor object is created to represent the connection to the file.

The mode argument specifies the access mode with which the file is to be opened. The permitted values and their meanings are as specified for the RandomAccessFile(File,String) constructor. If there is a security manager, its checkRead method is called with the name argument as its argument to see if read access to the file is allowed. If the mode allows writing, the security manager's checkWrite method is also called with the name argument as its argument to see if write access to the file is allowed.
Parameters:

name - the system-dependent filename mode - the access mode


Throws: IllegalArgumentException - if the mode argument is not equal to one of "r", "rw", "rws", or "rwd" FileNotFoundException - if the file exists but is a directory rather than a regular file, or cannot be opened or created for any other reason SecurityException - if a security manager exists and its checkRead method denies read access to the file or the mode is "rw" and the security manager's checkWrite method denies write access to the file

RandomAccessFile
public RandomAccessFile(File file, String mode) throws FileNotFoundException
Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument. A new FileDescriptor object is created to represent this file connection.

The mode argument specifies the access mode in which the file is to be opened. The permitted values and their meanings are: Value Meaning "r" Open for reading only. Invoking any of the write methods of the

resulting object will cause an IOException to be thrown.

"rw"

Open for reading and writing. If the file does not already exist then an attempt will be made to create it. every update to the file's content or metadata be written synchronously to the underlying storage device.

"rws" Open for reading and writing, as with "rw", and also require that

"rwd" Open for reading and writing, as with "rw", and also require that
every update to the file's content be written synchronously to the underlying storage device. The "rws" and "rwd" modes work much like the force(boolean) method of the FileChannel class, passing arguments of true and false, respectively, except that they always apply to every I/O operation and are therefore often more efficient. If the file resides on a local storage device then when an invocation of a method of this class returns it is guaranteed that all changes made to the file by that invocation will have been written to that device. This is useful for ensuring that critical information is not lost in the event of a system crash. If the file does not reside on a local device then no such guarantee is made.

The "rwd" mode can be used to reduce the number of I/O operations performed. Using "rwd" only requires updates to the file's content to be written to storage; using "rws" requires updates to both the file's content and its metadata to be written, which generally requires at least one more low-level I/O operation. If there is a security manager, its checkRead method is called with the pathname of the file argument as its argument to see if read access to the file is allowed. If the mode allows writing, the security manager's checkWrite method is also called with the path argument to see if write access to the file is allowed.
Parameters:

file - the file object mode - the access mode, as described above
Throws: IllegalArgumentException - if the mode argument is not equal to one of "r", "rw", "rws", or "rwd" FileNotFoundException - if the file exists but is a directory rather than a regular file, or cannot be opened or created for any other reason SecurityException - if a security manager exists and its checkRead method denies read access to the file or the mode is "rw" and the security manager's checkWrite method denies write access to the file See Also:

SecurityManager.checkRead(java.lang.String), SecurityManager.checkWrite(java.lang.String), FileChannel.force(boolean)

getFD
public final FileDescriptor getFD() throws IOException
Returns the opaque file descriptor object associated with this stream. Returns: the file descriptor object associated with this stream. Throws: IOException - if an I/O error occurs. See Also:

FileDescriptor

getChannel
public final FileChannel getChannel() Returns the unique FileChannel object associated with this file. The position of the returned channel will always be equal to this object's file-pointer offset as returned by the getFilePointer method. Changing this object's file-pointer offset, whether explicitly or by reading or writing bytes, will change the position of the channel, and vice versa. Changing the file's length via this object will change the length seen via the file channel, and vice versa.
Returns: the file channel associated with this file Since: 1.4

read
public int read() throws IOException
Reads a byte of data from this file. The byte is returned as an integer in the range 0 to 255 (0x00-0x0ff). This method blocks if no input is yet available.

Although RandomAccessFile is not a subclass of InputStream, this method behaves in exactly the same way as the InputStream.read() method of InputStream.

Returns: the next byte of data, or -1 if the end of the file has been reached. Throws: IOException - if an I/O error occurs. Not thrown if end-of-file has been reached.

read
public int read(byte[] b, int off, int len) throws IOException Reads up to len bytes of data from this file into an array of bytes. This
method blocks until at least one byte of input is available.

Although RandomAccessFile is not a subclass of InputStream, this method behaves in the exactly the same way as the InputStream.read(byte[], int, int) method of InputStream.
Parameters:

b - the buffer into which the data is read. off - the start offset of the data. len - the maximum number of bytes read.
Returns: the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached. Throws: IOException - if an I/O error occurs.

read
public int read(byte[] b) throws IOException Reads up to b.length bytes of data from this file into an array of bytes. This
method blocks until at least one byte of input is available.

Although RandomAccessFile is not a subclass of InputStream, this method behaves in the exactly the same way as the InputStream.read(byte[]) method of InputStream.
Parameters:

b - the buffer into which the data is read.


Returns: the total number of bytes read into the buffer, or -1 if there is no more data because the end of this file has been reached. Throws: IOException - if an I/O error occurs.

readFully
public final void readFully(byte[] b) throws IOException Reads b.length bytes from this file into the byte array, starting at the
current file pointer. This method reads repeatedly from the file until the requested number of bytes are read. This method blocks until the requested number of bytes are read, the end of the stream is detected, or an exception is thrown. Specified by: readFully in interface DataInput Parameters:

b - the buffer into which the data is read.


Throws: EOFException - if this file reaches the end before reading all the bytes. IOException - if an I/O error occurs.

readFully
public final void readFully(byte[] b, int off, int len) throws IOException Reads exactly len bytes from this file into the byte array, starting at the
current file pointer. This method reads repeatedly from the file until the requested number of bytes are read. This method blocks until the requested number of bytes are read, the end of the stream is detected, or an exception is thrown. Specified by: readFully in interface DataInput Parameters:

b - the buffer into which the data is read. off - the start offset of the data. len - the number of bytes to read.
Throws: EOFException - if this file reaches the end before reading all the bytes. IOException - if an I/O error occurs.

skipBytes
public int skipBytes(int n) throws IOException
Attempts to skip over n bytes of input discarding the skipped bytes.

This method may skip over some smaller number of bytes, possibly zero. This may result from any of a number of conditions; reaching end of file before n bytes have been skipped is only one possibility. This method never throws an EOFException. The actual number of bytes skipped is returned. If n is negative, no bytes are skipped.
Specified by: skipBytes in interface DataInput Parameters:

n - the number of bytes to be skipped.


Returns: the actual number of bytes skipped. Throws: IOException - if an I/O error occurs.

write
public void write(int b) throws IOException
Writes the specified byte to this file. The write starts at the current file pointer. Specified by: write in interface DataOutput Parameters:

b - the byte to be written.


Throws: IOException - if an I/O error occurs.

write
public void write(byte[] b) throws IOException Writes b.length bytes from the specified byte array to this file, starting at
the current file pointer. Specified by: write in interface DataOutput Parameters:

b - the data.
Throws: IOException - if an I/O error occurs.

write
public void write(byte[] b, int off, int len) throws IOException Writes len bytes from the specified byte array starting at offset off to this
file. Specified by: write in interface DataOutput Parameters:

b - the data. off - the start offset in the data. len - the number of bytes to write.
Throws: IOException - if an I/O error occurs.

getFilePointer

public long getFilePointer() throws IOException


Returns:

Returns the current offset in this file.

the offset from the beginning of the file, in bytes, at which the next read or write occurs. Throws: IOException - if an I/O error occurs.

seek
public void seek(long pos) throws IOException
Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs. The offset may be set beyond the end of the file. Setting the offset beyond the end of the file does not change the file length. The file length will change only by writing after the offset has been set beyond the end of the file. Parameters:

pos - the offset position, measured in bytes from the beginning of the file,
at which to set the file pointer. Throws: IOException - if pos is less than 0 or if an I/O error occurs.

length
public long length() throws IOException
Returns the length of this file. Returns: the length of this file, measured in bytes. Throws: IOException - if an I/O error occurs.

setLength
public void setLength(long newLength) throws IOException

Sets the length of this file.

If the present length of the file as returned by the length method is greater than the newLength argument then the file will be truncated. In this case, if the file offset as returned by the getFilePointer method is greater then newLength then after this method returns the offset will be equal to newLength. If the present length of the file as returned by the length method is smaller than the newLength argument then the file will be extended. In this case, the contents of the extended portion of the file are not defined.
Parameters:

newLength - The desired length of the file


Throws: IOException - If an I/O error occurs Since: 1.2

close
public void close() throws IOException

Closes this random access file stream and releases any system resources associated with the stream. A closed random access file cannot perform input or output operations and cannot be reopened.

If this file has an associated channel then the channel is closed as well.
Throws: IOException - if an I/O error occurs.

readBoolean
public final boolean readBoolean() throws IOException Reads a boolean from this file. This method reads a single byte from the file, starting at the current file pointer. A value of 0 represents false. Any other value represents true. This method blocks until the byte is read, the
end of the stream is detected, or an exception is thrown. Specified by: readBoolean in interface DataInput Returns:

the boolean value read. Throws: EOFException - if this file has reached the end. IOException - if an I/O error occurs.

readByte
public final byte readByte() throws IOException

Reads a signed eight-bit value from this file. This method reads a byte from the file, starting from the current file pointer. If the byte read is b, where 0 <= b <= 255, then the result is:

(byte)(b) This method blocks until the byte is read, the end of the stream is detected, or an exception is thrown.
Specified by: readByte in interface DataInput Returns: the next byte of this file as a signed eight-bit byte. Throws: EOFException - if this file has reached the end. IOException - if an I/O error occurs.

readUnsignedByte
public final int readUnsignedByte() throws IOException
Reads an unsigned eight-bit number from this file. This method reads a byte from this file, starting at the current file pointer, and returns that byte.

This method blocks until the byte is read, the end of the stream is detected, or an exception is thrown.
Specified by: readUnsignedByte in interface DataInput Returns:

the next byte of this file, interpreted as an unsigned eight-bit number. Throws: EOFException - if this file has reached the end. IOException - if an I/O error occurs.

readShort
public final short readShort() throws IOException
Reads a signed 16-bit number from this file. The method reads two bytes from this file, starting at the current file pointer. If the two bytes read, in order, are b1 and b2, where each of the two values is between 0 and 255, inclusive, then the result is equal to:

(short)((b1 << 8) | b2) This method blocks until the two bytes are read, the end of the stream is detected, or an exception is thrown.
Specified by: readShort in interface DataInput Returns: the next two bytes of this file, interpreted as a signed 16-bit number. Throws: EOFException - if this file reaches the end before reading two bytes. IOException - if an I/O error occurs.

readUnsignedShort
public final int readUnsignedShort() throws IOException
Reads an unsigned 16-bit number from this file. This method reads two bytes from the file, starting at the current file pointer. If the bytes read, in order, are b1 and b2, where 0 <= b1, b2 <= 255, then the result is equal to:

(b1 << 8) | b2 This method blocks until the two bytes are read, the end of the stream is detected, or an exception is thrown.

Specified by: readUnsignedShort in interface DataInput Returns: the next two bytes of this file, interpreted as an unsigned 16-bit integer. Throws: EOFException - if this file reaches the end before reading two bytes. IOException - if an I/O error occurs.

readChar
public final char readChar() throws IOException
Reads a Unicode character from this file. This method reads two bytes from the file, starting at the current file pointer. If the bytes read, in order, are b1 and b2, where 0 <= b1, b2 <= 255, then the result is equal to:

(char)((b1 << 8) | b2) This method blocks until the two bytes are read, the end of the stream is detected, or an exception is thrown.
Specified by: readChar in interface DataInput Returns: the next two bytes of this file as a Unicode character. Throws: EOFException - if this file reaches the end before reading two bytes. IOException - if an I/O error occurs.

readInt
public final int readInt() throws IOException
Reads a signed 32-bit integer from this file. This method reads 4 bytes from the file, starting at the current file pointer. If the bytes read, in order, are b1, b2, b3, and b4, where 0 <= b1, b2, b3, b4 <= 255, then the result is equal to:

(b1 << 24) | (b2 << 16) + (b3 << 8) + b4

This method blocks until the four bytes are read, the end of the stream is detected, or an exception is thrown.
Specified by: readInt in interface DataInput Returns: the next four bytes of this file, interpreted as an int. Throws: EOFException - if this file reaches the end before reading four bytes. IOException - if an I/O error occurs.

readLong
public final long readLong() throws IOException
Reads a signed 64-bit integer from this file. This method reads eight bytes from the file, starting at the current file pointer. If the bytes read, in order, are b1, b2, b3, b4, b5, b6, b7, and b8, where:

0 <= b1, b2, b3, b4, b5, b6, b7, b8 <=255, then the result is equal to: ((long)b1 << 56) + ((long)b2 << 48) + ((long)b3 << 40) + ((long)b4 << 32) + ((long)b5 << 24) + ((long)b6 << 16) + ((long)b7 << 8) + b8 This method blocks until the eight bytes are read, the end of the stream is detected, or an exception is thrown.
Specified by: readLong in interface DataInput Returns: the next eight bytes of this file, interpreted as a long. Throws: EOFException - if this file reaches the end before reading eight bytes.

IOException - if an I/O error occurs.

readFloat
public final float readFloat() throws IOException Reads a float from this file. This method reads an int value, starting at the current file pointer, as if by the readInt method and then converts that int to a float using the intBitsToFloat method in class Float. This method blocks until the four bytes are read, the end of the stream is detected, or an exception is thrown.
Specified by: readFloat in interface DataInput Returns: the next four bytes of this file, interpreted as a float. Throws: EOFException - if this file reaches the end before reading four bytes. IOException - if an I/O error occurs. See Also:

readInt(), Float.intBitsToFloat(int)

readDouble
public final double readDouble() throws IOException Reads a double from this file. This method reads a long value, starting at the current file pointer, as if by the readLong method and then converts that long to a double using the longBitsToDouble method in class Double. This method blocks until the eight bytes are read, the end of the stream is detected, or an exception is thrown.
Specified by: readDouble in interface DataInput Returns: the next eight bytes of this file, interpreted as a double. Throws:

EOFException - if this file reaches the end before reading eight bytes. IOException - if an I/O error occurs. See Also:

readLong(), Double.longBitsToDouble(long)

readLine
public final String readLine() throws IOException

Reads the next line of text from this file. This method successively reads bytes from the file, starting at the current file pointer, until it reaches a line terminator or the end of the file. Each byte is converted into a character by taking the byte's value for the lower eight bits of the character and setting the high eight bits of the character to zero. This method does not, therefore, support the full Unicode character set.

A line of text is terminated by a carriage-return character ('\r'), a newline character ('\n'), a carriage-return character immediately followed by a newline character, or the end of the file. Line-terminating characters are discarded and are not included as part of the string returned. This method blocks until a newline character is read, a carriage return and the byte following it are read (to see if it is a newline), the end of the file is reached, or an exception is thrown.
Specified by: readLine in interface DataInput Returns: the next line of text from this file, or null if end of file is encountered before even one byte is read. Throws: IOException - if an I/O error occurs.

USING THE FILE CLASSES IN JAVA Files and directories are accessed and manipulated via the java.io.File class. The File class does not actually provide for input and output to files. It simply provides an identifier of files and directories. Always remember that just because a File object is created, it does not mean there actually exists on the disk a file with the identifier held by that File object.

The File class includes several overloaded constructors. For example, the following instance of File refers to a file named myfile.txt in the current directory of the program that the JVM is running:
File file = new File ("myfile.txt");

Again, the file myfile.txt may or may not exist in the file system. An attempt to use File object that refers to a file that does not exist will cause a FileNotFoundException to be thrown. The File instance can also created with a filename that includes path:
File fileA = new File("/tmp/filea.txt");

Another overloaded constructor allows separate specification of the path and the file name: File fileA = new File("/tmp", "filea.txt"); Directories can also be specified: File direc = new File("/tmp"); There are a number of useful methods in File, e.g.: Boolean exist(); does the file Boolean canWrite(); can the file be written Boolean canRead(); can the file be Boolean isFile(); does it represent a Boolean isDirectory(); - or a directory exist to read file

There are also methods to get the file name and path components, to make a directory, to get a listing of the files in a directory, etc. String getName () - get the name of the file (no path included) String getPath () get the abstract file path String getCanonicalPath () - get the name of the file with path String getAbsolutePath () - get the absolute file path Note that path names use different separator characters on different hosts. Windows uses "\", Unix"/", Macintosh ":". The static variables:
File.separator string with File.separatorChar char with File.pathSeparator string with File.pathSeparatorChar - char with path separator separator file separator path separator file

can be used to insure that your programs are platform independent. For example, this snippet shows how to build a platform independent path:

String dirName = String filename = File filData = new File(dirName + File.separator + filename);

"dataDir"; "data.dat";

Other talents of the File class include the method


boolean mkdir ()

This method will create a directory with the abstract path name represented by the File object if that File object represents a directory. The method returns true if the directory creation succeeds and false if not. A situation in which the directory cannot be created is, for example, when the File object refers to an actual file that already exists in the file system.

UNIT - V
Networking Basics Java AWT Windows, Text, & Graphics
INTRODUCTION Java was designed from the start with networking in mind. Java became famous because of? applets, which were invented to provide dynamic content to web pages. Many other features of Java, however, extend Java network programming far beyond simple applets. Some of these include:

1. java.net package in the core language includes numerous network related

classes.
2. Remote Method Invocation (RMI) packages allow a Java program running on

one machine to invoke methods on another machine.


3. Streaming I/O architecture provides a uniform structure in that I/O over a

network is treated the same as I/O to a disk or the console.


4. Serialization allows objects to be sent over a network and reconstructed on

another machine.
5. Threading allows easier creation of server programs where threads can be

easily spin off to serve new clients as they connect. 6. java.security and other packages allow for secure interactions over networks. 7. Portability of java means that Java networking programs developed on one type of platform can also run and communicate with each other when used on other platforms. NETWORKING BASICS

Computers running on the Internet communicate to each other using either the 1. Transmission Control Protocol (TCP) or 2. User Datagram Protocol (UDP). TCP (Transmission Control Protocol) is a connection-based protocol that provides a reliable flow of data between two computers. (Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples ) UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival. UDP is not connection-based like TCP.

CLIENT / SERVER SERVER: A server is anything that has some source that can be shared there are Computer servers, which provide computing power. Printer Servers, which manage a collection of printers. Disk Servers, which provide networked disk space. Web Servers, which store web pages. CLIENT : A client is simply any other entity that wants to gain access to a particular server. SOCKET

A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent. Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request.

On the client-side: The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. To make a connection request, the client tries to make contact with the server on the server's machine and port

. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection. This is usually assigned by the system. If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client.

PROXY SERVER A proxy server speaks the client side of protocol to another server. This is often required when clients have certain restrictions on which servers they can connect to. Thus a client would connect to proxy server, which did not have such restrictions and the proxy server would in turn communicate for the client. A caching proxy HTTP server can help reduce the bandwidth demands on a local networks connection to the internet. When a popular web site is being hit by hundreds of users, a proxy server can get the contents of the web servers popular pages once, saving expensive internetwork transfers while providing faster access to those pages to the client. INTERNET ADDRESSING Ever computer on the internet has an address. An internet address is a number that uniquely identifies each computer on the

There are 32 bits in an IP address, and we often refer to them as a sequence of four numbers between 0 and 255 separated by dots. The first five bits define which class of network lettered A,B,C,D, or E, the address represent. Most Internet users are on a class c network between(192 to 224)

DNS ( Domain Naming Server)

Is very difficult to remember a set of numbers(IP address) to connect to the internet. DNS is used to overcome this problem. It maps one particular IP address to a string of characters. For examplewww.alpha.edu implies edu is the domain name reserved for education commercial sites.

THE NETWORKING CLASSES AND INTERFACES Authenticator ContentHandler DatagramPacket DatagramSocket DatagramSocketImpl HttpURLConnection InetAddress InetAddress InetAddress is one such class which is used to encapsulate the IP address and DNS. To create an instance InetAddress class, factor methods are used as there are not visible constructors available for this class Factor methods are conventions where static methods return an instance of the class JarURLConnection MulticastSocket NetPermission PasswordAuthentication ServerSocket Socket SocketImpl SocketPermission URL URLClassLoader URLConnection URLDecoder URLEncoder URLStreamHadler

METHODS

Static InetAddress getLocalHost()

Return InetAddress object representing local host

Static InetAddress getByName(string Returns InetAddress for the host passed to it HostName)

DATAGRAM

Datagram is a type of packet that represents an entire communication. There is no necessity to have connection or disconnection stages when communicating using datagrams. This is less reliable than communication using TCP/IP There are two classes in Java, which enable communication using datagram. DatagramPacket : is the class acts as the data container . DatagramSocket : is a mechanism used to send or receive DatagramPackets.

DatagramPacket A datagramPacket object can be created as follows Constructors :DatagramPacket(byte data[], int size InetAddress I, int port) The above constructor takes a byte array and its size as its parameter, the InetAddress and the port as its parameters. DatagramSocket The DatagramPacket does not provide methods to send or receive data.This job is taken up by the DatagramSocket class. Constructor :The creation of a DatagramSocket object throws a SocketException, which must be handled.There are two constructors of DatagramSocket class. The first constructor does not take any parameters and is created as given below: DatagramSocket s = new DatagramSocket(); The next constructor is given as follow DatagramSocket s = new DatagramScoket(int port);

Methods Send (DatagramPacket d)

Dispatches the given DatagramPacket Object

Receive(DatagramPacket p) Close()

Receives the given DatagramPacket object Closes the socket connection

The send and receive methods of the Datagramsocket class throw an IOException which must be caught.

TCP / IP TCP/IP sockets are the most reliable, bi-directional, stream protocols. It is possible to send random amounts of data using TCP/IP.

Socket are used for data communication using this protocol. There are two kinds of sockets in Java 1. Server 2. Client

ServerSocket Class is used by the server to wait for the client and the client connects to the server using socket class. Socket Class A Socket object establishers connection between the client and the server. Constructor The first constructor takes the hostname and port as its parameters to create a socket object. Creation of a Socket object throws an UnKnownHostException or an IoException, which must be caught . Socket s = new Socket(String hostName, int port);

The next constructor takes the InetAddress and port number as its parameters to create a Socket object. The constructor throws an IoException or an UnknownHostException, which must be caught and handle. Socket s = new Socket(InetAddress a, int port)

Methods InetAddress getInetAddress() Int getPost() Returns InstAddress associated with socket object Return remote port to which this socket object is connected. Returns the local port to which the Socket object is connected Return the OutputStream associated with this socket Closes both InputStream and OutputStream

Int getLocakPort()

OutputStream getoutputStream() Void close()

ServerSocket Class The serversocket object waits for the client to make a connection. Accept() method which is used to wait for a client to initiate communication. The normal socket object is used for further transfer of data. There are two type of constructor available The first constructor accepts a port number as parameter to create a ServerSocket object on that port. ServerSocket ss = new ServerSocket(int port); The next constructor accepts a port and maximum queue length as parameters. This queue length indicates the maximum number of client connection that the system can have before refusing connection ServerSocket ss = new ServerSocket(int port, int maxqu); URL

constructor

URL stands for Uniform Resource Locator and it points to resource files on the internet. the web is a collection of higher level protocols and file formats. The URL helps in locating such files using their addresses on the Net. Java provide URL class that provides an API to access information across the internet.

Components of URL The URL has four components they Protocol - http, smpt, ftp etc IP address or the hostname - // Port numbed - optional Actual file path actual path http://www.freeway.com:80/root/htmlfile/index.html Methods getPort() getHost() getFile() Openstream() URLConnection

Return specified port number in URL / return 1 if port is not explicitly set Returns host name specified in URL Returns the path Opens file specified in the URL

URLConnection is a general purpose class for accessing the attributes of a remote resource.

Once you make a connection to a remote server you can use URLConnection to inspect the properties of the remote object before actually transporting it locally. Returns a URLconnection object associated with URL object Return content type & returns null if not know. Return last modified date of object & 0 if not known.

Methods openConnection getContentType() getLastModified()

getContentLength() Returns length of content &-1 if not known

AWT

The Abstract Windows Toolkit (AWT) contains numerous classes and methods that allow you to create and manage applet windows and standard windows that run in a GUI environment, such as Windows 95/NT. The AWT classes are contained in the java.awt package.

Window Fundamentals

The AWT defines windows based on a class hierarchy that adds functionality at each level. The two most common windows are those derived from Panel used by applets and Frame that creates standard windows.

AWT class Hierarchy

Component is an abstract class that encapsulates all of the user interface elements that are displayed on the screen and that interact with the user. Container class is an abstract subclass of Component. The class is responsible for laying out any components it contains through using various layout managers. Panel class is a concrete subclass of Container. When screen output is directed to an applet, it is drawn on the surface of a Panel object. In essence, a Panel is a window that does not contain a title bar, menu bar, or border. Frame

encapsulates what is commonly thought of as a window. It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners. When a Frame window is created from within an applet window, warning message will produced. When a Frame window is created by a program, a normal window is created. Canvas : Canvas encapsulates a blank window upon which you can draw.

Frame Windows Frame supports two constructors: Frame() & Frame(String title) You cannot specify the dimensions of the window. Instead, you must set the size after the window has been created by using the following two methods: void resize(int newWidth, int newHeight) void resize(Dimension newSize)

Once a Frame window is created, it will not be visible until you call show(). To hide a window, call hide(). To set new title, use setTitle(String newTitle). All events related to your window are routed through handleEvent(): boolean handleEvent(Event evtObj) Each time handleEvent() is called, evtObj contains a Event object that describes the event. Each time an event is generated, its ID is put in id. When a window is closed, the evtObj id is WINDOW_DESTROY. For top-level windows, you must exit the Java run-time system by calling System.exit().

Creating Windowed Program

To create a stand-alone AWT-based application, simply create an instance of the window or windows you need inside main(). (AWTWindow1.java)

Graphics in Windows Drawing a line: Lines are drawn by means of the drawLine() method drawLine(int startX, int startY, int endX, int endY) Drawing and filling a rectangle: The drawRect() and fillRect() methods display an outlined and filled rectangle respectively. drawRect(int top, int left, int width, int height) drawRect(int top, int left, int width, int height) Drawing a circle/ellipse: To draw an ellipse, use drawOval(). To fill an ellipse use fillOval(). drawOval(int top, int left, int width, int height) fillOval(int top, int left, int width, int height) Drawing an arc: Arcs can be drawn with drawArc() and fillArc() drawArc(int top, int left, int width, int height, int startAngle, int sweepAngle) Drawing a polygon: It is possible to draw arbitrarily shaped figures using drawPolygon() and fillPolygon() drawOval(int x[], int y[], int numPoints)

Working with Color

Java supports color in a portable, device-independent fashion. AWT color system allows you to specify any color you want. Color is encapsulated by the Color class. Color defines several constants to specify a number of common color.

Color constants: Color.colorConstant Customized colors constructor:

Color colorObj = new Color(int red, int green, int blue) Set current graphics color: setColor(Color newColor) AWTColor1.java Fonts

The AWT supports multiple fonts encapsulated by the Font class. To know that fonts are available on the machine, use the getFontList() method defined by the Toolkit class. This method returns an array of strings that store the names of the available fonts. Since getFontList() is a member of ToolKit, you need a Toolkit reference. The reference can be obtained by using the getToolkit() method. The getToolkit() is defined both in Component and Window. AWTFont1.java

To select a new font, construct a Font object with font parameters font(String fontName, int fontStyle, int fontSize)

All Java environment support 4 font types (Dialog (default), Helvetica, Times Roman, and Courier) and 3 font styles (PLAIN, BOLD, ITALIC). To use a font that has been created setFont(fontObj) (AWTFont2.java)

FontMetrics Java provides the FontMetrics class to encapsulate various information about a font. For example: height, baseline, ascent, descent, and leading. FontMetrics also defines several methods that help you manage text output. For example, to display multiple lines of text, your program must manually keep track of the current output position by using getLeading(), getAscent(), getDescent(), and/or getHeight() methods. The stringWidth() method returns the length, in pixels, of the current output. AWTFon3.java & AWTFont4.java AWT CONTROLS Controls are components that allow a user to interact with your application in various ways. ( for example a commonly used to control is the push button). A layout manager automatically positions components within a container. In addition to the controls a frame window can also include a standard style menu bar.

Control Fundamentals The AWT supports the following types of control Labels Push buttons Check boxes Choice lists Lists Scroll bars Text editing Adding and Removing control

To include a control in a window, you must add it to the window. first create an instance of the desired control and then add it to a window by calling add(), which is defined by container. The add() method has several forms. The following form is the one that is used Component add(Component compobj)

Sometimes you will want to remove a control from a window when the control is no longer needed. To do this, call remove(). This method is also defined by Container void remove(Component obj) Here obj is a reference to the control you want to remove, You can remove all controls by calling removeAll()

Labels A label is an object of type Label and it contains a string which it displays, which it displays. Label are passive controls that do not support any interaction with the user. Label defines the following constructors. Label() : Create a blank space Label(String str) : Create a label that contains the string specified by str Label(String str, int how) : Create a label that contains the string specified by str using the alignment specified by how. Buttons The mostly widely used control is the push button. A push button is a component that contains a label and the generates an event when it is pressed. Push button are objects of type Button. Button defines these two constructors: Button( ) : Create an empty button Button(String str): Creates a button that contains str as a label. Check Box A check box is a control that is used to turn an option on or off.

It consists of a small box that can either contain a check mark or not. You can change the state of a check box by clicking on it. Checkbox supports these constructors they are Checkbox() : label is initially blank the state of the check box is unchecked Checkbox(String str): check box whose label is specified by str the state of the check box is unchecked is true, box Checkbox(String str, boolean on) : set the initial state of the check box. If on the check box is initially checked otherwise it is cleared. Checkbox(String str, boolean on, CheckboxGroup cbGroup) : create a check whose label is specified by str and whose group is specified by cbGroup. Checkbox(String str, CheckboxGroup cbGroup, boolean on)

CheckboxGroup

It is possible to create set of mutually exclusive check boxes in which one and only one check box in the group can be checked at any one time. These check boxes are often called radio button. To create a set of mutually exclusive check boxes you must first define the group to which they will belong and then specify that group when you construct the check boxes. Checkbox getSelectedCheckbox

Choice controls The choice class is used to create a pop-up list of items from which the user may choose. Choice control is a form of menu. Choice component takes up only enough space to show the currently selected item. when the user clicks on it the whole list of choice pops up and new selection can be made. To add a selection to the list, call addItem() or add(). They have these general forms void addItem(String name) void add(String name) To determine which item is currently selected you may call either getSelectedItem() or getSelectedIndex(). These methods are shown here: String getSelectedItem() int getSelectedIndex() Using List The List class provides a compact, multiple-choice, scrolling selection list. A List object can be constructed to show any number of choices in the visible window.

It is also be created to allow multiple selection. List provides these constructors List( ) - Allows only one item to be selected at any one time List( int numRows) - the value of numRows specifies the number of entries in the list that will always be visible. List(int numRows,boolean multipleSelect) - if multipleSelect is true then the user may select two or more items at a time.

To add a selection to the list, call add( ). It has the following two forms. void add(String name) void add(String name, int index)

For lists that allow only single selection, you can determine which item is currently selected by calling either getSelectedItem( ) or getSelectedIndex( ). String getSelectedItem( ) int getSelectedIndex( )

Managing Scroll Bar Scroll bar are used to select continuous values between a specified minimum and maximum. Scroll bar may be oriented horizontally or vertically. Each end has an arrow that you can click to move the current value of the scroll bar one unit in the direction of the arrow. The current value of the scroll bar relative to its minimum or maximum values is indicated by the slider box for the scroll bar. Scrollbar defines the following constructors Scrollbar( ) - Creates a vertical scroll bar Scrollbar( int style) - allows you to specify the orientation of the scrollbar. Scrollbar( int style, int initialValue, int thumsize, int min, int max) - allows you to specify the orientation of the scrollbar Using TextField The TextField class implements a single-line text entry area, usually called an edit control. Text fields allow the user to enter strings and to edit the txt using the arrow keys,cut and paste keys and mouse selections. Textfields defines the following constructors TextField() - Creates a default text fields TextField(int numChars) - Creates a text field that is numChars characters wide. TextField(String Str) - initializes the text field an sets its width. TextField(String str, int numchars) TextField provides several methods that allow you to utilize a text field. They are String getText( )

void setText(String str) The user can select a portion of the text in a text field. Also you can select a portion of text under program control by using select( ). String getSelectedText() void select(int startIndex, int endIndex) Using a TextArea The AWT includes a simple multiline editor called TextArea. The constructors for TextArea TextArea() TextArea(int numLines, int numChars) TextArea(String str) TextArea(String str,int numLines,int numChars) TextArea(String str, int numLines,int numChars, int sBars) Here numLines specifies the height, in lines, of the text area, and numChars specifies its width in characters. Initial text can be specified by str. sBars specifies the scroll bars. SCROLLBARS_BOTH SCROLLBARS_NONE SCROLLBARS_HORIZONTAL_ONLY SCROLLBARS_VERTICAL_ONLY TextArea adds the following methods

void append(String str) - appends the string specified by str to the end of the current text. void insert(String str, int index)- inserts the string passed in str at the specified index. void replaceRange(String str,int startIndex, int endIndex) - to replace text, call replaceRanger(). It replaces the characters from startIndex to endIndex-1, with replacement text passed in str. LAYOUT MANAGERS

The layout manager classes are a set of classes that implement the Java.AWT.LayoutManger interface and help to position the components in a container. The interface takes the task of laying out the child components in the container.

The basic Layout Manager FlowLayout BoarderLayout GridLayout

GridBagLayout CardLayout

FlowLayout FlowLayout is the default layout manager. Which is similar to how words flow in a text editor Components are laid out from the upper left corner, left to right and top to bottom. The constructors for FlowLayout FlowLayout() FlowLayout( int how) FlowLayout(int how, int horz, intvert) The first form creates the default layout, which centers components and leaves five pixels of space between each component. The second form lets you specify how each line is aligned. FlowLayout.LEFT FlowLayout.CENTER FlowLayout.RIGHT The third form allows you to specify the horizontal and vertical space left between components in horz and vert respectively.

BorderLayout BorderLayout class implements a common layout style for top-level windows. It has four narrow, fixed-width components at the edges and one large area in the center. The four sides are referred to as north, south, east and west. The middle area is called center. BoarderLayout() BoarderLayout(int horz, int vert)

The first form creates a default border layout. The second allows you to specify the horizontal and vertical space left between components in horz and vert, respectively BoarderLayout.CENTER , BoarderLayout.NORTH, BoarderLayout.EAST, BoarderLayout.SOUTH,WEST.

GridLayout GridLayout lays out components in a two-dimensional grid. When you instantiate a GridLayout you define the number of rows and columns. The constructors supported by GridLayout are GridLayout() : creates a single-column grid layout

GridLayout(int numRows, int numColumns) - creates a grid layout with the specified number of row and columns. GridLayout(int numRows,int numColumns, int horz,int vert) - third form allows you to specify the horizontal and vertical space left between components in horz and vert respectively. CardLayout CardLayout be useful for user interfaces with optional components that can be dynamically enabled and disabled upon user input. You can prepare the other layouts and have them hidden ready to be activated when needed. CardLayout provides these two constructors. CardLayout() : creates a default card layout CardLayout(int horz, int vert) : the form allows you to specify the horizontal and vertical space left between components in horz and vert respectively. The cards are typically held in an object of type panel. This panel must have CardLayout selected as its layout manager. when adding cards to a panel add() method is used. void add(Components panelObj, Object name); Here name is a string that specifies the name of the card whose panel is specified by panelObj. After you have created a deck, your program activates a card by calling one of the following methods defined by CardLayout. deck is refer to the container, and cardName is the name of a card. void first(Container deck)- calling first() causes the first card in the deck to be shown. void last(Container deck)- to show the last card(). void next(Container deck)- to show the next card, call next() void previous(Container deck)- to show the previous card call previous() void show(Container deck, String cardName)- the show() method displays the card whose name is passed in cardName. Menu Bars and Menus A top level window can have a menu bar associated with it. A menu bar displays a list of top-level menu choice. Each choice is associated with a drop-down menu. This concept is implemented in java by the following classes : MenuBar, Menu and MenuItem. A menu bar contains one or more Menu objects. Each Menu object contains a list of MenuItem Object. Each Menu object represents something that can be selected by the user. Since Menu is a subclass of MenuItem, a hierarchy of nested submenus can be created.

To create a menu bar, first create a instance of MenuBar. This class only defines the defaultconstrctor. Next create instances of Menu that will define the selection displayed on the bar. The following are the constructors for Menu Menu() Menu(String optionName) Menu(String optionName, boolena removable) optionalName specifies the name of the menu selection. If removable is true the popup menu can be removed and allowed to flat free. Individual menu item are of type MenuItem. It defines these constructors MenuItem() MenuItem(String itemName) MenuItem(String itemName, MenuShotcut keyAccel) Here, itemName is the name shown in the menu, and KeyAccel is the menu shortcut for this item You can disable or enable a menu item by using the setEnable() method. its form is shown here void setEnabled(boolean enabledFalg) If the argument enableFlag is true, the menu item is enable. If false the menu item is disabled. you can determine an item's status by calling isEnable(). This method is boolean isEnable()

You might also like