You are on page 1of 149

Java Programming

Syllabus for Java


1. Overview of Java
What is java ? java Platform, What is OOPs,Intro. Class & Objects, Characteristics of OOPS, Types of inheritance

2. Introduction to java Programming


Features of Java , Sample Java program

3. Data Types, variables and Arrays, Operators, control statements


Variables and Datatypes, Operators, Constructs, Modifiers, Exception handling, Array and Strings.

4. Introducing classes & Objects


Class Fundamental, Type of Constructers, this Keyword

5. Inheritance
Inheritance Basics, Constructer behaviour under inheritance, overiddern methods, super keyword, Abstract Class.

6. Package and Interfaces


Defining Interface,Implementing interface,Package, Implementing Nested classes

7. Exploring java.Lang
Exploring String and StringBuffer,Wrapper Class

8. Command line Arguments


Java Command Line Arguments, System Properties, Collection framework

9. Exception Handling
Exception Handling, trycatch, throw, throws, Userdefined Exception

10. Applet & AWT


Life Cycle,Basic Controls,Panels,Event handing.

11. Containers
Component, Container, Panel, window,Frame

12. Layout Manager


Layouts and its usage, type of layout.

13. Graphics Object


Graphics, Working with Image

14. I/O Streams & Threading


IOStreams,Serialization,Threading

15. Networking & Java Database Connectivity


Networking basics,Tcp/ip,udp,sockets, JDBC

1 of 149

Java Programming

Overview of JAVA 1.3


What Is Java?
Java is a Internet programming language and in which we can develop platform independent programs. The Java Programming Language Java is a high-level programming language that is all of the following: Simple neutral Architecture-

Object oriented Distributed Interpreted Robust Secure

Portable High-performance Multithreaded Dynamic

Java is also unusual in that each Java program is both compiled and interpreted. With a compiler, you translate a Java program into an intermediate language called Java bytecodes--the platform-independent codes interpreted by the Java interpreter. With an interpreter, each Java bytecode instruction is parsed and run on the computer. Compilation happens just once; interpretation occurs each time the program is executed. This figure illustrates how this works.

You can think of Java bytecodes as the machine code instructions for the Java Virtual Machine (Java VM). Every Java interpreter, whether it's a Java development tool or a Web browser that can run Java applets, is an implementation of the Java VM. The Java VM can also be implemented in hardware. Java bytecodes help make "write once, run anywhere" possible. You can compile your Java program into bytecodes on any platform that has a Java compiler. The bytecodes can then 2 of 149

Java Programming be run on any implementation of the Java VM. For example, the same Java program can run on Windows NT, Solaris, and Macintosh.

The Java Platform

A platform is the hardware or software environment in which a program runs. The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other, hardware-based platforms. Most other platforms are described as a combination of hardware and operating system. The Java platform has two components: The Java Virtual Machine (Java VM) The Java Application Programming Interface (Java API)

You've already been introduced to the Java VM. It's the base for the Java platform and is ported onto various hardware-based platforms. The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets. The Java API is grouped into libraries (packages) of related components. The next section, What Can Java Do?, highlights each area of functionality provided by the packages in the Java API. The following figure depicts a Java program, such as an application or applet, that's running on the Java platform. As the figure shows, the Java API and Virtual Machine insulates the Java program from hardware dependencies.

3 of 149

Java Programming

As a platform-independent environment, Java can be a bit slower than native code. However, smart compilers, well-tuned interpreters, and just-in-time bytecode compilers can bring Java's performance close to that of native code without threatening portability.

What is OOPS?
Programming in an object-oriented language means creating new types of data (called classes) and "teaching" those data types how to handle messages. You teach a class what to do with a message by creating a method. The user creates variables of a data type(objects) or instances and sends messages to those objects. Why OOPS? OOPS FEATURES: OOPS has several features as follows: Data Independence Inheritance Polymorphism Data Abstraction The principal advantages of Object oriented programming are: Through inheritance, we can eliminate redundant code and extend the use of existing class. It is possible to have multiple instances of an object to co-exist without interference It is possible to map objects in the problem domain to those objects in the program. Software complexity can be easily managed. It is easy to partition the work in project-based objects. Object Oriented systems can be easily upgraded from small to large systems.

Classes and Objects

4 of 149

Java Programming
What is an object?

An object is an instance of the class Objects are the runtime entities in an objectoriented system. Once the class has been declared, we can create variables of that type by using the class-name (like any other built-in type variable ). For example : item y ; creates a variable y of type item. These class variable are known as objects. Therefore, y is called an object of type item. Benefits: Objects provides the benefit of modularity and information hiding. What is a class? A class is a way to bind the data and its associated functions together. It allows data (and functions)to be hidden, if necessary from the external use. When defining a class , we are creating a new abstract data type that can be treated like any other built-in datatype. Generally, a class specification has two parts: Class declaration. Class function definitions.

The class declaration describes the type and scope of its members. The class function definitions describe how the class function are implemented. The general form of a class declaration is: class class_name { private: variable declarations; function declarations; public: variable declarations; function declarations; } The class declaration is similar to a struct declaration. The keyword class specifies that what follows is an abstract data of type class_name. The body of the class is enclosed within braces and terminated by a semicolon. The class body contains the declaration of variables and functions. These functions and variables are collectively called members. They are usually grouped under two sections, namely, private and public denote which of the members are private and which of them are public. Note that a colon follows these keywords scope of the variables ie. public and private are discussed later. Benefits: 5 of 149

Java Programming

Classes provide the benefit of reusability for example we can use the same class, and thus the same code, over and over again to create many objects. Characteristics of OOPs Encapsulation Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps them both safe from outside interference and its misuse. One way to think about encapsulation is as a protective wrapper that prevents the code defined outside the wrapper. Access to the code and data inside the wrapper is tightly controlled through a well-defined interface. Abstraction Abstraction refers to the act of representing essential features without including the background details or expressions. Classes use the concept of abstraction and are and are defined as a list of a list of abstract attributes such as size, weight and cost, and functions to operate on these attributes. They encapsulate all the essential properties of the objects that are to be created. Since the class use the concept of data abstraction, they are known as Abstract Data Type(ADT). Polymorphism (static, dynamic) Polymorphism is another important OOP concept. Polymorphism means the ability to take more than one form. Polymorphism plays an important role in allowing objects having different internal structures to share the same external interface. This means that a general class of operations may be accessed in the same manner even though specific actions associated with each operation may differ. Polymorphism is extensively used in implementing inheritance. Shape Draw()

Circle object Draw(circle)

Box object Draw(box)

Square object Draw(square)

6 of 149

Java Programming Polymorphism Static Polymorphism Static polymorphism refers to an entity existing in different physical forms simultaneously. Static polymorphism involves binding of functions on the basis of number, type and sequence of their arguments. The various types of parameters are specified in the function declaration, and therefore the function can be bound to the calls at the compile time. This form of association is called early binding. The term early binding stems from the fact that when the program is executed, the calls are already bound to the appropriate functions. The resolution is on the basis of number, type, and sequence of arguments declared for each form of the function. Consider the following function declaration: void add(int,int); void add(float,float); Now, if the function add() is invoked , the parameters passed to it will determine which version of the function will be executed. This resolution is done at compile time. Dynamic Polymorphism Dynamic Polymorphism refers to an entity changing its form depending on the circumstances. A function is said to exhibit dynamic polymorphism when it exists in more than one form, and calls to its various forms are resolved dynamically when the program is executed. The term late binding refers to the resolution of the function to their associated methods at runtime instead of compile time. This feature increases the flexibility of the program by allowing the appropriate method to be invoked, depending on the context. The compiler is unable to bind a call to a method since resolution depends on the context of the call. Inheritance (types and benefits of inheritance) Inheritance is the process by which one object acquires the properties of another object. This is important because it supports the concept of hierarchical classification. Without the use of hierarchies, each object would need to define all of its characteristics explicitly. However, the use of inheritance, an object need only define those qualities that make it unique within its class. It can inherit its general attributes from its parent. Thus, it is the inheritance mechanism that makes it possible for one object to be a specific instance of a more general case. If you wanted to describe a more specific class of animals, such as mammals they would have more specific attributes, such as type of teeth, and mammary glands. This is known as a subclass of animals, where animals are referred to as mammals super class. Since mammals are simply more precisely animals, they inherit all of the attributes from animals. Inheritance interacts with encapsulation as well. If a given class encapsulates 7 of 149

Java Programming some attributes, then any subclass will have same attributes plus any that it adds as part of its specialization. A new subclass inherits all the attributes of its ancestors. Types of Inheritance : Single Inheritance Multiple Inheritance Hierarchical Inheritance Multilevel Inheritance

8 of 149

Java Programming

Single Inheritance A derived class with only one base class is called single inheritance. Let us consider a simple diagram: A

B Multiple Inheritance A derived class with several base classes is called Multiple Inheritance. For example, see the following diagram: A B

C Hierarchical Inheritance The traits of one class may be inherited by more than one class. This process is known as hierarchical inheritance. A

B Multilevel Inheritance

This is a mechanism of deriving a class from another derived class is known as multilevel inheritance. A

9 of 149

Java Programming B C Benefits of inheritance are as follows: Subclasses provide specialized behaviors form the basis of common elements provided by the superclass. Through the use of inheritance, programmers can reuse the code in the superclass many times. Programmers can implement superclass called abstract classes that define generic behaviors. The abstract superclasses defines and partially implement the behavior but much of the class is undefined and unimplemented. Other programmers fill in the details with specialized classes.

Introduction to Java Programming Language


What is Java? Java is an object oriented programming language that can be used to create a wide range of programs that run under any platforms. It was conceived by James Gosling, Patrick Naughton and his team at Sun Microsystems, Inc. in 1991. The trouble with C and C++ was that they were designed to be compiled for a specific target. While it is possible to compile a C++ program for just about any type of CPU, to do so requires a full C++ compiler targeted for that CPU. The problem is that compilers are expensive and time consuming to create. Gosling and others began work on a portable, platform neutral language that could be used to produce code that would run on a variety of CPUs under different environments. This effort ultimately led to the creation of Java. With the emergence of the World Wide Web, Java was propelled to the forefront of computer language design, because the Web, too, demanded portable programs. Though Java is used for programming on the Net it is very much different from HTML for HTML is a means of defining the logical organization of information and providing links, called hypertext links, to related information. The only connection that HTML has to Java is that it provides the applet tag, which executes a Java applet. Thus, it is possible to embed instructions in a hypertext document that cause a Java applet to execute. Java Applets and Applications

10 of 149

Java Programming Java can be used to create two types of programs: applications and applets. An application is a program that is specific to your computer, under the operating system of that computer. An applet is an application that can run any where on the Net and can be executed by a Java compatible Web browser. Security As you are already aware, every time you download a normal program, you are risking a viral infection. Java provides a firewall between a networked application and your compiler so that you can download Java applets without fear of viral infection or malicious intent. Java achieves this by confining a Java program to the Java execution environment and not allowing it access to other parts of the computer. Portability You have innumerable computers with different operating systems connected to the Internet. You need to have some means of generating portable executable code for programs to be dynamically downloaded to all of the various types of platforms connected to the Internet. Indeed, Javas solution to these two problems is both elegant and efficient. The following features help in achieving this task. Byte Codes Bytecodes are a highly optimized set of instructions designed to be executed by a virtual machine that the Java run time system emulates ie. the Java runtime system is an interpreter for bytecode. As you know, modern languages are compiled to executable code but Java programs are interpreted rather than compiled and therefore it is much easier to run them in a wide variety of environments. You need to implement only the Java run time system for each platform. Once the run time package exists for a given system, any Java program can run on it.

11 of 149

Java Programming FEATURES OF JAVA Simple If you already understand the basic concepts of object oriented programming, learning Java will be even easier Object oriented Java was not designed to be source code compatible with any other language. The object model in Java is simple and easy to extend, while simple types, such as integers, are kept as high performance non objects. Robust The multi platform environment of the Web demands that the program must work reliably in a variety of systems. Reliability is given a higher priority in the design of JAva. To achieve reliability, Java restricts you in a few key areas to force you to find your mistakes early in program development. Multithreaded Java supports multithreaded programming, which allows you to write programs that do many things at once. Javas easy to use approach to multithreading allows you to think about the specific behavior of your program, not multitasking subsystem. Architecture-Neutral A main issue for the Java designers was that of code longevity and portability. Operating system upgrades, processor upgrades, and changes in core system resources can all combine to make a program malfunction. The Java designers made several hard decisions in the Java language and run time in an attempt to alter this situation. Their goal was write once ;run time, forever .To a great extent the goal was accomplished. Interpreted And High Performance Java enables the creation of cross-platform programs by compiling into an intermediate representation called Java byte code which can be interpreted on any system that provides a Java runtime. Java was designed to perform well on very low-power CPUs. It is true that Java is interpreted, the Java byte code was carefully designed so that it would be easy to translate directly into native machine code for losing none benefits of the platform-neutral code. Distributed 12 of 149

Java Programming Java was designed for the distributed environment of the Internet because it handles TCP\IP protocols. In fact, accessing a resource using a URL is not much different from accessing a file. The original version of Java included features for intra- address-space messaging. This allowed objects on two different computers to execute procedures remotely. Java has recently revived these interfaces in a package called remote method invocation (RMI) .This feature brings an unparalleled level of abstraction to client\server programming. Dynamic Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run time. This makes it possible to dynamically link code in a safe and expedient manner. This is crucial to the robustness of the applet environment, where small fragments of byte code may be dynamically updated on a running system. The new features added by Java: The JDK 1.2 is a major upgrade of the Core and standard Extension APIs of the Java development Kit. It includes version 1.1 of the Java Foundation classes (JFC), CORBA support, a more secure and flexible security model, improvements to the APIs of JDK 1.1 and performance enhancements. The Java Foundation Classes, probably the single most important new feature added to JDK 1.2 is version 1.1 of the Java Foundation Classes(JFC). JFC is a set of APIs for building the GUI-related components of Java applets and applications. APIs included with JFC include the following: Swing Java 2D Drag and Drop The Java platform Java being platform independent can run all hardware and software platforms including Windows 98, 95 and NT ,Macintosh and UNIX. Both Netscape and Internet Explorer support Java applets. Create a Java source file Let us know the basic features of a Java Program by writing a simple program. Example : Lets start by compiling and running the short sample program shown here. /* This is a simple Java program. 13 of 149

Java Programming Call this fileMyfirst.java. */ class Myfirst { // The program begins with a call to main( ). public static void main(String args[]) { System.out.println (This is my first Java Program ); } } Entering the Program In this example, the name of the source file should be Myfirst.java In Java, a source file is officially called a compilation unit. It is a text file that contains one or more class definitions. The Java compiler requires that a source file use the .java filename extension A Closer Look at the First Sample Program Although Myfirst.java program appears to be quite short, it includes several key features which are common to all Java programs. The program begins with the following lines: Defining a class Let us examine the line of code as shown here: class Myfirst{ This line uses the keyword class to declare that a new class is being defined. Myfirst is an identifier that is the name of the class. The entire class definition ,including all of its members, will be between the opening curly brace( { )and the closing curly brace( }). The main method Now we come to the major part of a Java Application. public static void main(String args[]) This line begins the main() method. The public keyword is an access specifier, which allows the programmers to control the visibility of class members. When a class is preceded by public, then that member may be accessed by code outside the class in which it is declared. (The opposite of public is private ,which prevents a member from being used 14 of 149

Java Programming by the code defined outside of its class.) In this case, main( ) must be declared as public, since it must be called by code outside of its class when program is started. The key word static allows main( ) to be called without having to instantiate a particular instance of a class. This is necessary since main is called by the Java interpreter before any objects are made. The keyword void simply tells the compiler that main does not return a value. As stated, main is the method called when a java application begins. Remember that Java is casesensitive and therefore, Main is different from main. It is important to understand that the Java compiler will compile classes that do not contain a main( ) method. But the Java interpreter has no way to run these classes. So if you have typed Main instead of main, the compiler would still compile your program. However, Java interpreter would report an error because it would not be able to find the main( ) method. Any information that you need to pass to a method is received by variables specified within a set of parentheses that follow the name of the method. These variables are called parameters. In main( ) there is only one parameter, albeit a complicated one. String args[] declares a parameter named args which is an array of instances of the class. Objects of type String store character strings. In this case args receives any command line arguments present when the program is executed. Comments in Java code The following lines of code are Java Comments. /* This is a sample Java program. Call this file Myfirst.java. */ Java supports three styles of comments. The one shown at the top of the program is called a multiline comment. This type of comment must begin with /* and end with */. Anything between two comment symbols is ignored by the compiler. You find another line that is a comment. //Your program begins with a call to main( ) This is the second type of comment supported by java. A single-line comment begins with a // and ends at the end of the line. Programmers use multiline comments for brief and lineby line descriptions. 15 of 149

Java Programming The third comment style is used by the javadoc documentation generation tool. All text between the /** and */ is treated as a javadoc comment.

16 of 149

Java Programming Compile the source file To compile the Myfirst program, execute the compiler, javac, by specifying the name of the source file on the command line, as shown here: C:\>javac Myfirst.java The javac compiler creates a file called Myfirst.class that contains the bytecode version of the program. The Java bytecode is the intermediate representation of your program that contains instructions that the Java interpreter executes. Thus the output of javac is not code that can be directly executed. Run the application To actually run the program, you must use the Java interpreter, called java. To do so, pass the class name Myfirst as a command-line argument, as shown here: C:\>java Myfirst When the program is run, the following output is displayed: This is my first Java Program.

Variable and Data Types


All variables in the java language must have a data type. Types identifies the information stored in variables and returned by methods, on those occasions that a method does in fact return data when called. The information stored in a variable, or returned by a method, is know as the value of the variable or return. Data Types Java being a programming language, allows to define variable of the following data types : boolean char byte short int long float double 17 of 149

Java Programming

The sizes of these types are a defined in the java languages specification and are listed in the table. Data Types and Their Sizes Representation Size Type bits Boolean 8 Byte 8 Int 32 Float 32 Representation Size Type (bits) char 16 short 16 long 64 double 64

Variables of type boolean may only take the values true and false . The four signed integral data types are byte short int long Variables of these types are twos complement numbers. Their ranges are given in Table 1.3 Notice that for each type. the exponent of 2 in the minimum and maximum is one less than the size of the type type Byte size 8 bits Minimum Maximum -2 2-1 2-1 2-1 2-1

Short 16bits -2 Int 32 bits -2 Long 64 bits -2

The char type is integral but unsigned. The range of a variable of type char is from 0 through 2-1. Java characters are in Unicode , which is a 16 bit encoding . If the most significant nine bits of char are a110, then the encoding is the same as seven bit ASCII. The two floating point types are float double

Variable name A program refers to a variables value by its name. For example, when the character counting program wants to refer to the value of the count variable, it simply uses the name 18 of 149

Java Programming count. By convention, variable names begin with a lowercase letter and class names begin with and uppercase letter. Scope A variable s scope is the block of code within which the variable is accessible. Also a variables scope determines when the variable is created and destroyed. Scope of the variable is established when it is declared. Scope places a variable into one of these four categories. Member variable Local variable Method parameter Exception handler parameter

A member variable is a member of a class or an object and is declared within a class (but not within any of the classs methods) The character counting program declares no member variables . Local variables are not declared within a method or within a block of code in a method. Method parameters are formal arguments to methods and constructors and are used to pass values into methods and constructors Exception handler parameters are similar to method parameters but are arguments to an exception handler rather than to a method or a constructor. Variable Initialization Local variables and member variables can be initialized when they are declared. The character counting program provides an initial value for count when declaring it. int count = 0; The value assigned to the variable must match the variables type. Method parameters are exception handler parameters cannot be initialized in this way. The value for a parameter is set by the caller. Final Variable

19 of 149

Java Programming A variable can be declared as final. Doing so prevents its contents from being modified. This means that you must initialize a final variable when it is declared. (In this usage, final is similar to const in C/C++.) For example : final int FILE_NEW = 1;

OPERATORS Java operators are divided into these categories: Arithmetic, Relational an conditional , Bitwise ,Logical , Assignment. Arithmetic Operators Javas binary arithmetic operations: Operator + * / % Use opl+op2 op1+op2 op1*op2 op1/op2 op1%op2 Description Adds opl and op2 Subtracts opl from op2 Multiplies op 1 by op2 Divides op1 by op2 Computes the remainder of dividing op1by op2

Note: the java language extends the definition of the operator + to include string concatenation. The example program uses + to concatenate Input has, the value of count, to a string. System.out.printIn (Input has + count+chars); The + and operators have unary versions which set the sign of the operand: Operator Use Description + +op Indicates a positive value -op Arithmetically negates op Youll learn more about flow control in control Flow Statements. Similarly also has prefix and postfix versions which function in the same way as ++. Operator ++ use op++ Description Increments op by 1; evaluate to value incrementing 20 of 149 before

Java Programming ++ --++op op --op Increments of by 1; evaluates to value after incrementing Decrements op by 1; evaluates to value before Decrementing Decrements op by 1; evaluate to value after Decrementing

Relational and Conditional Operators


Relational operators compare two values and determine the relationship between them. For example , != returns true if the two operands are unequal . The character counting program uses != to determine whether the value returned by System.in read is not equal to 1. This table summarizes Javas relational operators operator > >= < <= == != use op1>op2 op1>=op2 op1<op2 op1<=op2 op1==op2 op1!= op2 Return true if op1 is greater than op2 op1 is greater than equal to op2 op1 is less than op2 op1 is less than equal to op2 op1 and op2 are equal op1 and op2 are not equal

These are three conditional operators: Operator && || ! Use op1&&op2 op1 || op2 !top Returns true of op1 and op2 are both true either op1 and op2 is true op is false

The operator & can be used as a synonym for && if both of its operands are boolean. Similarly, ! is synonym for || if both of its operands are boolean.

Control Flow Statements Java supports several control flow statements. These are similar to their C and C++ counterparts, so they look and act as you would expect if youre already familiar with one (or both) of these languages.

21 of 149

Java Programming If statements Java supports two types of if statements, both of which require the use of a boolean expression. This is the syntax for the most basic if statement: if (boolean expression) { ... } Depending on the value of the boolean expression, the body of the if statement may or may not be executed. If the expression evaluates to true, the body is executed. If the expression evaluates to false, the body of code is skipped. The second form of if statement makes use of the keyword else, directing program execution along one of two distinct routes : if (boolean expression) { ... } else { ... } If the boolean value evaluates to true, the block of code immediately following is executed. If the expression evaluates to false, the else block is executed. If-then-else statement, since it follows the logic of If the expression is true, then execute this body of code, or else execute this one. You can use the else-if construct to add another aspect of control to the if statement : if (boolean expression ) { ... } else if (boolean expression) { ... } else { ... } Java if statement expressions must return a boolean value. In C, a value of 0 (zero) is treated as false and a value of 1 is treated as true. This is not the case with Java, where only boolean expressions can be used in an if statement. 22 of 149

Java Programming Switch Statement The Switch statement is similar in nature to the if -then-else statement, although it makes the programmers job a lot easier when a number of else clauses are needed: switch (expression) { case constant1: ... break ; case Constant2; ... break ; case Constant3; ... break; . . . default; ... break; } The data type of the expression must be either char, byte, short, or int. Boolean expressions arent allowed, although they are used in all other control flow mechanisms.

Loops
Control flow statements include a number of loops : while loops, do-while loops, for loops, while and do-while loops

while (boolean expression) { ... } do { ... } while (boolean expression); In the while loop, the boolean expression is evaluated. The value of this expression determines whether or not the body of the loop is executed. If the expression evaluates to true, the loop is executed. If expression value is false, it does not execute. Each time 23 of 149

Java Programming through the body of the while loop, the expression is re-evaluated. The loop continues until the expression evaluates to false: int x = 0; while (x++ < 10) { System.out.println (The while loop is being executed.); System.out.println (And the value of x is : + x); } In the preceding example, the body of the loop continues executing as long as x is less than 10. Since we increment the value of x by one (x++) in the expression itself, the loop is executed 10 times. Note that the increment could also have taken place in the body of the loop itself, as follows: while (x < 10) { x++; System.out.println (The while loop is being executed.); System.out.println. (And the value of x is: + x); } With the do while loop, the body of the loop executes once before the expression is ever evaluated. This ensures that your loop code is executed atleast once, regardless of how the expression evaluates: do { System.out.println (The while loop is being executed.); System.out.println (And the value of x is: + x); } while (x++ < 10); As with the while loop, we could have incremented our expression inside the loop body, rather than inside the expression : do { System.out.println (The while loop is being executed.); System. Out.println (And the value of x is : + x); x++; while (x < 10);

The while loop is by far the more popular of the two, although the do while loop has the advantage of executing your code atleast once, no matter what the expression evaluates to. Be sure to change your expression value either inside the body of the while or do while loop, or in the expression itself. If the value never changes, the expression always remains true and the loop execute indefinitely! 24 of 149

Java Programming

For loop The for loop repeats program execution as controlled through a series of expressions, terminating when a certain condition is no longer met. It continues looping until the specified boolean condition evaluates to false, at which point the loop is broken and execution resumes after the loop body: for (expression; booleanExpression ; expression) { ... } The first expression initializes the loop variable. The second is a boolean expression that specifies the condition that must be met in order for the loop body to be executed. The third and final expression specifies how the loop variable is to change each time through the loop.

Consider the following example : int x; for (x = 0 ; x<10; x++ ) { System.out.println( The for loop is being executed.); System. out.println (And the value of x is : + x); }

Modifiers At the end of this session, you will be able to: To Know the Access Modifiers: 1. Public 2. Private 3. Protected 1. 2. 3. 4. 5. To understand other Modifiers: final abstract static native synchronized

25 of 149

Java Programming In general, Java class declarations have the form AccessSpecifier class NewClass extends NameofSuperClass implements NameofInterface There are four properties of the class that may be defined in the declaration: 1. 2. 3. 4. Modifier class name Super class Interfaces

26 of 149

Java Programming This session deals with modifiers. Modifier Overview: Encapsulation links data with the code that manipulates it. It also provides another important attribute: access control. Through encapsulation, you can control what parts of a program can access the members of a class. By controlling access, the misuse of that data can be prevented. The access specifier that modifies its declaration determines how a member can be accessed. Java supplies a rich set of access modifier specifiers. The Access Modifiers Access modifiers control which classes may use a feature. A class features are The class itself The class variables The methods and constructors

Class- level variables are modifiers are the only variables that may be controlled by access modifiers. The variables that declared and used within a class methods may not have access modifiers. This makes sense; a method variable can only be used within its method. The access modifiers are:

public protected private

public Public is the most generous access modifier. A public class, variable, or method may be used is any Java program without restriction. An application declares its main ( ) method to be public so that main( ) may be invoked from any Java runtime environment. private The least generous access modifiers is private. Top level classes may not be declared private. A private variable or method may only be used by an instance of the class that declares the variables or method. friendly If no access modifier is specified Friendly is the name of the default access of classes, variables, and methods. A class data and methods may be friendly, as well as the class in the same package as the class in question. 27 of 149

Java Programming

Friendly is not a Java keyword; it is simply name that is given to the access level that results from not specifying an access modifier. Only classes that are in the package may access friendly features of classes that are in the package. protected The name protected is a bit misleading. Form the sound of it, you might guess that protected access is extremely restrictive-perhaps the next closest thing to private access. In fact, protected features are even more accessible than friendly features.

Other Modifiers Java s other modifiers: final abstract static native synchronized Declaring a class to be public final is no different from declaring it final public. Declaring method to be protected static has the same effect as declaring it static protected. Final The final modifiers apply to classes, methods, and variables. The meaning of final varies from context, but the essential idea is the same: Final features may not be changed. A final class may not be subclasses. For example, the code below will not compile, because the java.lang.Math class is final: Class SubMath extends java.lang.Math { } The compiler error says, Cant subclass final classes. A final variable may not be modifies once it has been assigned a value. For example, the java.lang.Math class has a final variable, of type double, called PI. Obviously, pi is not the sort of value that should be changed during the execution of a program. final reference variable cannot be changed. data owned by an object that is referred to by a final object reference variable can be changed. 28 of 149

Java Programming

Abstract The abstract modifiers can be applied to classes and methods. An abstract class may not be instantiated (that is, may not call is constructor.) Abstract classes provide a way to refer implementation to subclasses. abstract void travel( )

void travel ( )

void travel ()

void travel ()

A class hierarchy with abstraction In a way, abstract is the opposite of final. A final class, for example, may not be subclassed; an abstract class must be subclassed. Static The static modifier can be applied to variables, methods, and even a strange kind of code that is not part of a method. You can think of static features as belonging to a class, rather than being associated with an individual instance of the class. Methods, as well as data, can be declared static. Static methods are not allowed to use the non-static features of their class (although they are fee to access the class static data and call its other static methods). Thus static methods are not concerned with individual instance of a class. They may be invoked before even a single instance of the class is constructed. To summarize static methods.

A static method may only access the static data of its class; it may not access non-static data. A static method may only call the static methods of its class; it may not call non-static methods. A static method has no this. A static method may not be overridden to be non-static.

Native The native modifier can refer only to methods. Like the abstract keyword, native indicates that the body of a method is to be found elsewhere. In the case of abstract methods, the 29 of 149

Java Programming body is in a subclass;with native methods, the body lies entirely outside the Java Virtual Machine, in a library. Native code is written in a non-Java language, typically C for C++, and complied for a single target language, typically C for C++, and complied for a single target machine type. (Thus Javas platform independence is violated.) People who port Java to new platforms implement extensive native code of other platform-specific functionality. However, it is rare for application and applet programmers to need to write native code. Synchronized The synchronized modifier is used to control access to critical code in multithreaded programs. Multithreading is an extensive topic is its own right and is covered later on. Modifiers and features Not all modifiers can be applied to all features. Top-level classes may not be protected.. Static is so general that you can apply it to free-floating blocks of code. Table 3.1 shows all the possible combinations of features and modifiers. Note that classes here are strictly top-level (that is, not inner) classes. Modifier public protected (friendly)* private final abstract static native synchronized Class Variable Method/Constructor yes no yes no yes yes yes no no yes yes yes yes yes yes no yes yes yes yes yes yes yes yes yes yes yes Free-Floating Block no no no no no no yes no no

*friendly is not a modifier, it is just the name of the default if no modifier is specified. 30 of 149

Java Programming

Exception Handling When an error occurs within a Java methods , the method can throw an exception to indicate to its caller that an error that an error occurred and the type of error that accrued. The calling method can use the try, catch, and finally statements to catch and handles the exception. /*End of Modifiers*/ Branching statements Break and continue statements Java supports two additional statements: break and continue. These are considered jump statements, because they allow the flow of program execution to branch out in directions not seen with the standard control flow statements. The switch statement makes use of the break statement to terminate a specific cases execution. However, those break statements were used without labels. Both break and continue can be used with an optional label that specifies exactly where the execution will be transferred. When this happens, not only does the break occur for the switch statement, but also for the entire while loop! If this labeled break were not present, the while loop would execute ten times. It only executes five times, since the labeled break kicks the flow of control out of both the switch and while loop. In Java, there are actually four jump statements : break continue return throw

The return statement is used to return program execution to the caller of a code segment, such as when a method has been invoked. At any point in the method, a return statement can return the flow of control back to the caller of that method. The throw statement is used to signal a runtime exception, as described below, which interrupts the flow of program execution while a handler is sought to deal with that exception. ARRAYS AND STRING ARRAYS: 31 of 149

Java Programming

Arrays are simple datatypes that can hold multiple values of the same datatype in contiguous memory locations. To create and use an array in Java, we need to first declare the array and then initialize it. Single -dimensional Arrays To declare a single-dimensional array the general syntax is: Datatype [] variablename; For example: Int [] numbers; The above statement will declare a variable that can hold an array of float type variables . Using the new operator in the following way can do this: Num=new int[10]; This statement assigns ten contiguous memory locations of type int to the variable Num. Initializing the array can be done using the for loop: for(int var =0; var<10;var++) Num[var]=var; Two-dimensional Arrays The general syntax for declaring a two dimensional array is: Datatype [] [] variablename; For example: int [][] Num; To initialize the array in memory, the following statement can be used: Num=new int[4][4]; This will create a two-dimensional array of eight elements-four rows and four column. For example: for(int varo=0 ; varo<4 ; varo++) 32 of 149

Java Programming for(int vari = 0 ; vari<4 ; var++) Num[vari][varo]=0; This loop will ensure that all the elements of the array are initialized to zero. Arrays in java are very secure. During compile time, the program is checked for any errors - like accessing out of array bounds. If there is an error, it is reported at compile time. This prevents the program from abnormal termination. Multidimensional Arrays (ARRAY OF ARRAYS) Although Java not supporting multi-dimensional arrays, it offers essentially the same capability by allowing us to create an array of arrays: int grid[][] = new int[10][10]; grid[0][0] = 1230; grid[0][5] = 4; grid[9][5] = 355; System.out.println("Grid value at 0,0 is " + grid[0][0]; System.out.println("Grid value at 0,5 is " + grid[0][5]; System.out.println("Grid value at 9,5 is " + grid[9][5]; In the above snippet of code, we created two arrays of integer values, both accessible through the grid variable. We can create as many arrays as necessary, each accessible through the single variable: int grid2[][][] = new int[15][10][5]; grid2[0][0][0] = 4630; grid2[4][5][1] = 7345; grid2[9][5][0] = 35; grid2[14][9][0] = 6465; grid2[14][9][4] = 16547; System.out.println("Grid2 value at 0,0,0 us " + grid2[0][0][0] ); System.out.println("Grid2 value at 0,5,1 is " + grid2[4][5][1] ); System.out.println("Grid2 value at 9,5,0 is " + grid2[9][5][0] ); System.out.println("Grid2 value at 14,9,4 is " + grid2[14][9][0] ); And we can even use an array of arrays in another array of arrays, to give us as many dimensions as we'd like. Declaring Array Variables Once you've declared an array, in order to use it, you must first instantiate an Array object. Without an Array object, you have only an empty array variable. 33 of 149

Java Programming

int Integers[]; // array declaration Integers = new int[25]; // instantiation Typically, the array declaration and instantiation happen at the same time: int Integers[] = new int[25]; // declare and instantiate

STRINGS : In c and C++, strings are implemented as null-terminated character arrays. Java uses a different approach. It implements String as object of type String. Implementing strings as built-in objects allows Java to provide a full complement of feature that makes string handling convenient. There are methods to perform string operation: String Comparison. -By using equals() or compareTo() methods. Searching Strings by using indexOf () or lastIndexOf() methods. Changing Case. By using toLowerCase () or toUpperCase () methods .

String Concatenation In general, Java does not allow operators to be applied to String objects. The one exception to this rule is the + operator. The + concatenates two strings, producing a String object as the result. This allows to chain together a series of + operations. For example, the following fragment concatenates three strings: String sum = 17; String str = The sum is + sum + only; System.out.println (str); This displays the string The sum is 17 only. Operator precedence causes the concatenation of four with the string equivalent of 2 to take place first. This result is then concatenated with the string equivalent of 2 a second time. To complete the integer addition first, you must use parentheses, like this : String str = four: + (2 + 2); Now str contains the string four : 4. 34 of 149

Java Programming

Class and Objects


Class Fundamentals The most important thing to understand about a class is that it defines a new data type. Once defined, this new type can be used to create objects of that type. Thus, a class is a template for an object, and an object an instance of a class. The General form of a class When you define a class, you declare its exact form and nature. You do this by specifying the data that it contains and the code that operates on that data. While very simple classes may contain only code or only data, most real world classes contain both. A class is declared by use of the class keyword. The classes that have been used up to this point are actually very limited examples of its complete form. As you will see, classes can (and usually do) get much more complex. The general form of a class definition is shown here: class classname { type instance variable1; type instance variable2; //... type insance variableN; type methodname1 (parameter-l;ist) { / / body of method } type methodname2(parameter-list) { / / body of method } //... type methodnameN(parameter-list) { / / body of method } } The data, or variables, defined within a class are called instance variables. The code is contained within methods. Collectively, the methods and variables defined within a class are called members of the class.

35 of 149

Java Programming Variables defined within a class are called instance variables because each instance of the class (that is, each object is separate and unique from the data for another. We will come back to this point shortly, but it is an important concept to learn early. All methods have the same general form as main( ), which we have been using thus far. However, most methods will not be specified as static or public. Notice that the general form of a class does not specify a main( ) method. Java classes do not need to have a main( ) method. You only specify one if that class is the starting point for your program. Further, applets dont require a main( ) method at all. A closer look at new The new operator dynamically allocates memory for an object. It has this general form : class-var = new classname( ); Here, class-var is a variable of the class type being created. The classname is the name of the class that is being instantiated. The class name followed by parentheses specifies the constructor for the class. A constructor defines what occurs when an object of a class is created. Constructors are an important part of all classes and have many significant attributes. Lets once again review the distinction between a class and an object. A class creates a new data type that can be used to create objects. That is, a class creates a logical framework that defines the relationship between its members. When you declare an object of a class, you are creating an instance of that class. Thus, a class is a logical construct. An object has physical reality (i.e., an object occupies space in memory). It is important to keep this distinction clearly in mind. Assigning object reference variables Object reference variables act differently than you might expect when an assignment takes place. For example, what do you think the following fragment does? Box b = new Box( ); Box b1 = b; You might think that b1 is being assigned a reference to a copy of the object referred to by b. That is, you might think that b and b1 refer to separate and distinct object. However, this would be wrong. Instead, after this fragment executes, b and b1 will both refer to the same object. The assignment of b to b1 did not allocate any memory or copy any part of the original object. It simply makes b refer to the same object as does b1. Thus, any changes made to the object through b1 will affect the object to which b is referring, since they are the same object. b Width 36 of 149

Java Programming

Height Depth b1

Box object

Although b and b1 both refer to the same object, they are not linked in any other way. For example, a subsequent assignment to b will simply unhook b from the original object without affecting the object or affecting b1. For example: Box b = new Box( ); Box b1 = b; //... b = null; Here, b has been set to null, but b1 still points to the original object.

Introducing methods Classes usually consist of two things: instance variables and methods. The topic of methods is a large one because Java gives them so much power and flexibility. In fact, much of the next chapter is devoted to methods. However, there are some fundamentals that you need to learn now so that you can begin to add methods to your classes. This is the general form of a method: type name(parameter-list) { / / body of method } Here, type specifies the type of data returned by the method. This can be any valid type, including class types that you create. If the method does not return a value, its return type must be void. The name of the method is specified by name. This can be any legal identifier other than those already used by other items within the current scope. The parameter list is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. If the method has no parameters, then the parameter list will be empty. Methods that have a return type other than void return a value to the calling routine using the following form of the return statement : return value; Here, value is the value returned. 37 of 149

Java Programming

38 of 149

Java Programming 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. Constructors look a little strange because they have no return type, not even void. This is because the implicit return type of a class constructor is the class type itself. It is the constructors job to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object immediately. Parameterized Constructors What is needed is a way to construct objects of various dimensions. The easy solution is to add parameters to the constructor. As you can probably guess, this makes them much more useful.

The this keyword


Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword. this can be used inside any method to refer to the current object . Declaring member variables The variables are automatically initialized when an object is created. The following lines of code in the above declares the member variables Interest( ) { System.out.println.("Computing the Interest ") ; principal = 5000; time = 2; rate = 8; } In the above example you can calculate the interest only for one particular entry .If you add parameters to the constructor , you can construct various Interest objects of different values. //* Parameterized Constructors Interest( double p ,double t ,double r) { principal = p ; time = t ; 39 of 149

Java Programming rate = r ; } Implementing methods Classes consist of both methods and variables.The general form of amethod is as follows: type name (parameter-list) { body method } type specifies the type of data returned by the method. If the method does not return a value its return type must be void. The name of the method is specified by name. The parameter list is a sequence of type and identifier pairs separated by commas. Methods that have a return type other than void return a value to the calling routine using the return statement: return value; The following code in the above program is an example of a method. double Int( ) { return (principal * time * rate )/100; } Some methods don't need parameters but most of them do. The following example is a method that returns the cube of number 5; int cube( ) { return 5 * 5 * 5; } If you modify this example so that it takes a parameter you can make the method more useful. int cube (int i) { return i * i * i ; } In the above example program you can set the variables of Interest by creating method that takes the variables in its parameters and sets each instance variable appropriately. void setVar(double p, double t , double r) { principal = p; time = t ; 40 of 149

Java Programming rate =r ; } Now you need to initialize each Interest object as simp_int1.setVar(5000,3,12); simp_int2.setVar(10000,2,10); Controlling access to members of a class You might be familiar with the access modifiers(public, protected, private)by now. When a member of a class is specified as public then that member can be accessed by any other code in your program and also within the same package. If the member is declared private then it can be accessed by other members of its class . A protected member can be accessed by the members of its class and also by its immediate subclass. Understanding instance and class members You know that objects are instances of a class .In the above example, you create objects using the following code Interest simp_int1 = new Interest( ); Interest simp_int2 = new Interest( ) ; Here simp_int1 and simp_int2 are instances of Interest class. Every object contains its own copies of the instance variables principal,timeand rate. To access these variables use the dot operator. Ex: simp_int1.principal = 5000; Sometimes a method will need to refere to the object that invoked it. You can achieve this using the this keyword. ITm can be used inside any method to refer to the current object. It is a reference to the object on which the method was invoked. You can use it anywhere whenever a a reference to an object of the currentclass type is permitted.

Interest( double p, double t , double r) { this.principal = p ; this.time = t; this.rate = r ; } Writing a finalize methods 41 of 149

Java Programming When no refernces to an object are made it is considered to be longer neededand the memory occupied is reclaimed.This is called garbage colloection. Sometimes an object may have to perform some action when it is destroyed. Before its memory is recaimed you need to maske sure that some of its resources are freed. To handle such a situation JAva provides finalization mechanism. By using finalization you can define specific actions that occur when an object is just to be destroyed. To add a finalizer you should define a finalize( ) method. In this method you need to specify the actions that must be performed before the destruction of the object . The general form of a finalize method: Protected void finalize( ) { // code } The keyword is a specifier prevents access from members outside the class. This method is called before garbage collection.

42 of 149

Java Programming

Managing Inheritance
Inheritance is one of the cornerstones of object oriented programming because it allows the creation of hierarchical classifications. Using inheritance, you can create a general class that defines traits common to a set of related items. This class can then be inherited by other, more specific classes, each adding those things that are unique to it. In the terminology of Java, a class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a superclass. It inherts all of the instance variables and methods defined by the superclass and adds its own, unique elements. Inheritance Basics To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword. To see how, lets begin with a short example. The following program creates a superclass called A and a subclass called B. Notice how the keyword extends is used to create a subclass of A. // A simple example of inheritance. // Create a superclass. class A { int p, q; void show( ) { System.out.println( p and q : + p + + q); } } // Create a subclass by extending class A. class B extends A { int r ; void showC ( ) { System. out. println ( r : + r); } void sum ( ) { System.out.println ( p+q+r: + (p+q+r)); } } class SimpleInheritance { public static void main(String args[ ] ) { A Ob1 = new A ( ) ; 43 of 149

Java Programming B Ob2 = new B ( ); // The superclass may be used by itself. Ob1.p = 10; Ob2.q = 20; System.out.println(Contents of Ob1: ); Ob1.show ( ); System.out.println( ); /* The subclass has access to all public members of its superclass. */ Ob2.p = 7; Ob2.q = 8; Ob2.r = 9; System.out.println(Contents of Ob2: ); Ob1.show ( ); Ob2.showC ( ); System.out.println( ); System.out.println(Sum of p, q and r in Ob2:); Ob2.sum( ); } } The output from this program is shown here : Contents of Ob1: p and q : 10 20 Contents of Ob2: p and q : 7 8 r: 9 Sum of p,q and r in Ob2: p + q+ r: 24 Member Access and Inheritance Although a subclass includes all of the members of its superclass, it cannot access those members of the superclass that have been declared as private. Understanding inheritance /*Inserted */ /* In a class hierarchy, private members remain private to their class. This program contains an error and will not compile. 44 of 149

Java Programming */ // Create a superclass. class A { int a ; // public by default private int b ; // private to A void setab (int x, int y) { a = x; b = y; } } // As j is not accessible here. class B extends A { int tot; void sum( ) { tot = a + b; / / ERROR,b is not accessible here } } class Access { public static void main (String args[ ] ) { B Ob1 = new B ( ); Ob1.setab(10, 12); Ob1. sum ( ); System.out.println (Total is + Ob1.tot); } } This program will not compile because the reference to b inside the sum ( ) method of B causes an access violation. Since b is declared as private, it is only accessible by other members of its own class. Subclasses have no access to it. A more practical Example Lets look at a more practical example that will help you to explain the power of inheritance. //This program uses inheritance to extend Box. class Box1 { double w; double ht; double d; 45 of 149

Java Programming //construct the clone of an object Box1(Box1 o) { w=o.w; ht=o.ht; d= o.d; } //constructor used when all dimensions specified Box1() { w=-1; ht=-1; d=-1; } //constructor used when cube is created Box1(double len) { w=ht=d=len; } //compute and return volume double volume() { return w*ht*d; } } //here Box1 is extended to include weight; class BoxWt extends Box1 { double weight; //Weight of Box1 //constructor for BoxWt BoxWt(double wt,double h,double dp,double m) { w=wt; ht=h; d=dp; wt=m; } } class DemoBoxWt { public static void main(String args[]) { BoxWt b1=new BoxWt(10,20,15,34.3); BoxWt b2=new BoxWt(2,3,4,0.076); double vol; 46 of 149

Java Programming vol=b1.volume(); System.out.println( "Volume of b1 is "+vol); System.out.println("Weight of b1 is " +b1.weight); System.out.println(); vol=b2.volume(); System.out.println("Volume of b2 is "+vol); System.out.println("Weight of b2 is"+b2.weight); } } BoxWt inherits all the characteristics of Box1and adds to them tothe weight component .It is not necessary for BoxWt to re-create all of the features found in the Box1. A major advantage of inheritance is that once you have created a superclass that defines the attributes common to a set of objects ,it can be used to create any number of more specific subclasses. //Here Box1 is extended to include color { class Color1 extends Box1 { int c; //color of box Color1(double wt,double h,double dp,int c1) { w=wt; ht=h; d=dp; c=c1; } } A point to note that once you have created a superclass that defines the general aspects of an object ,that the superclass can be inherited to form specialized classes .Each subclass simply adds bits own attributes which is the essence of inheritance. A Superclass Variable Can Reference a Subclass Object A reference variable of a superclass can be assigned a reference to any subclass derived from the superclass. You will find this aspect of inheritance quite useful in a variety of situations. For example, consider the following : class Ref { public static void main (String args[ ] ) { BoxWeight wbox = new BoxWeight( 3, 5, 7, 8, 37); Box b = new Box( ); double v; v = wbox.volume ( ); System.out.println(Volume of weightbox is + v); 47 of 149

Java Programming System.out.println(Weight of weightbox is + wbox.weight); System.out.println( ); / / assign BoxWeight reference to Box reference b = wbox; v = b.volume( ); // OK, volume( ) defined in Box System.out.println (Volume of plainbox is + v); /* The following statement is invalid because plainbox does not define a weight member. * / // System. out. println ( Weight of plainbox is + b.weight) ; } } Here, wbox is a reference to BoxWt objects, and box is a reference to box objects. Since BoxWeight is a subclass of box, it is permissible to assign plainbox a reference to the wbox object. It is important to understand that it is the type of the reference variable - not the type of the object that it refers to - that determines what members can be accessed. That is, when a reference to a subclass object is assigned to a superclass reference variable, you will have access only to those parts of the object defined by the superclass. This is why plainbox cant access weight even when it refers to a BoxWeight object. If you think about it, this makes sense, because the superclass has no knowledge of what a subclass adds to it. This is why the last line of code in the preceding fragement is commented out. It is not possible for a Box reference to access the weight field, because it does not define one. Using super In the preceding examples, classes derived from Box1were not implemented as efficiently or as robustly as they could have been. For example, the constructor for BoxWt explicitly initializes the width, height, and depth fields of Box1( ). Not only does this duplicate code found in its superclass, which is inefficient, but it implies that a subclass must be granted access to these members. However, there will be times when you will want to create a superclass that keeps the details of its implementation to itself (that is, that keeps its data members private). In this case, there would be no way for a subclass to directly access or initialize these variables on its own. Since encapsulation is a primary attribute of OOP, it is not surprising that Java provides a solution to this problem. Whenever a subclass need to refer to its immediate superclass, it can do so by use of the keyword super. super has two general forms. The first calls the superclass constructor. The second is used to access a member of the superclass that has been hidden by a member of a subclass. Each use is examined here. 48 of 149

Java Programming Using super to Call Superclass Constructers A subclass can call a constructor method defined by its superclass by the use of the following form of super: super(parameter-list); Here, parameter-list specifies any parameters needed by the constructor in the superclass.super()must always be the first statement executed inside a subclass constructor. Lets review the key concepts behind super( ). When a subclass calls super( ), it is calling the constructor of its immediate superclass. Thus, super( ) always refers to the superclass immediately above the calling class. This is true even in a multileveled hierarchy. Also, super( ) must always be the first statement executed inside a subclass constructor. A second use for super The second form of super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used. This usage has the following general form : super.member Here, member can be either a method or an instance variable. This second form of super is most applicable to situations in which member names of a subclass hide members by the same name in the superclass. Consider this simple class hierarchy. // Using super to overcome name hiding. class P { int a; } // / create a subclass by extending class P. class Q extends P { int a ; // this a hides the a in P Q (int c, int d) { super.a = c; // a in P a = d; // a in B } void show( ) { System.out.println("a in superclass: " + super.a); System.out.println("a in subclass : " + a); } } class Super { 49 of 149

Java Programming

public static void main (String args[ ] ) { Q Ob1 = new Q (1, 2) ; Ob1. show( ); } } This program displays the following : a in superclass : 1 a in subclass : 2 Although the instance variable a in Q hides the a in P, super allows access to the defined in the superclass. As you will see, super can also be used to call methods that are hidden by a subclass. When constructors are called When a class hierarchy is created, in what order are the constructors for the classes that make up the hierarchy called ? For example, given a subclass called Q and a superclass called P, is Ps constructor called before Qs, or vice versa? The answer is that in a class hierarchy, constructors are called in order of derivation, from superclass to subclass. Further, since super() must be the first statement executed in a subclass constructor , this order is the same whether or not super( ) is used. If super( ) is not used, then the default or parameterless constructor of each superclass will be used, then the default or parameterless constructor of each superclass will be executed. The following program illustrates when constructors are executed : // Demonstrate when constructors are called.

// Create a super class class R { R( ) { System.out.println (Inside Rs constructor.); } } / / Create a subclass by extending class R. class D extends R { D( ) { System.out.println(Inside Ds constructor.); } } / / Create another subclass by extending B. class E extends D { E( ) { 50 of 149

Java Programming System.out.println (Inside Es constructor.); } } class Cons { public static void main (String args[ ]) { Cons con = new C( ) ; } } The output from this program is shown here: Inside Rs constructor Inside Ds constructor Inside Es constructor Method Overriding In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden. Consider the following : // Method overriding. class B { int a,b ; B (int i, int j) { a = i; b = j; } / / display i and j void show ( ) { System.out.println ( a and b : + a + + b); } } class C extends B { int c; C (int p, int q, int r) { super(i, j); c = r; } 51 of 149

Java Programming / / display k - - this overrides show( ) in A void show( ) { System.out.println(c: + c); } } class Over { public static void main(String args[ ] ) { C Ob1 = new C ( 1, 2, 3); Ob1.show( ); / / this calls show( ) in C } } The output produced by this program is shown here : c:3 When show( ) is invoked on an object of type C, the version of show( ) defined within C is used. That is, the version of show( ) inside C overrides the version declared in B. If you wish to access the superclass version of an overridden function, you can do so by using super. For example, in this version of B, the superclass version of show( ) is invoked within the subclass version. This allows all instance variables to be displayed. class C extends B { int c; B (int p, int q, int r ) { super (a, b); c = r; } void show( ) { super.show( ) ; / / this calls Bs show( ) System.out.println (c: + c); } } If you substitute this version of A into the previous program, you will see the following output: a and b : 1 2 c: 3 Here, super.show( ) calls the superclass version of show( ). 52 of 149

Java Programming Method overriding occurs only when the names and the type signatures of the two methods are identical. If they are not, then the two methods are simply overloaded. For example, consider this modified version of the preceding example : / / Methods with differing type signatures are overloaded -- not / / overridden. class B { int a, b ; B (int i, int j) { a = i; b = j; } / / display a and b void show( ) { System.out.println( a and b: + a + + b); } } / / create a subclass by extending class A. class C extends B { int c; C (int p, int q, int r) { super (i, j); c = r; } / / overload show( ) void show(String msg) { System.out.println(msg + c); } } class Over { public static void main (String args[ ] ) { C Ob1 = new C(1, 2, 3); Ob1.show (This is c : ); / / this calls show( ) in C Ob1.show ( ); / / this calls show( ) in B } } The output produced by this program is shown here : 53 of 149

Java Programming This is c : 3 a and b : 1 2 The version of show( ) in C takes a string parameter. This makes its type signature different from the one in B, which takes no parameters. Therefore, no overriding (or name hiding) takes place. Why overridden methods? Overridden methods allow Java to support run time polymorphism. Polymorphism is essential to object oriented programming for one reason : it allows a general class to specify methods that will be common to all of its derivatives, while allowing subclasses to define the specific implementation of some or all of those methods. Overridden methods are another way that Java implements the one interface, multiple methods aspect of polymorphism. Dynamic run time polymorphism is one of the most powerful mechanisms that object oriented design brings to bear on code reuse and robustness. The ability of existing code libraries to call methods on instances of new classes without recompiling while maintaining a clean abstract interface is a profoundly powerful tool. Applying method overriding Lets look at a more practical example that uses method overriding. The following program creates a superclass called Fig that stores the dimensions of various two dimensional objects. It also defines a method called area( ) that computers the area of an object. The program derives two subclasses from Fig. The first is rectangle and the second is triangle. Each of these subclasses overrides area( ) so that it returns the area of a angle and a triangle, respectively. / / Using run time polymorphism. class Fig { double d1; double d2; Fig (double i, double j) { d1 = i; d2 = j; } double area( ) { System.out.println (Area for Figure is undefined.); return 0; } } class Angle extends Fig { 54 of 149

Java Programming Angle (double i, double j) { super(i, j); } / / override area for rectangle double area( ) { System.out.println(Inside area for rectangle.); return d1 * d2; } } class triangle extends Fig { Triangle (double i, double j) { super (i, j); } / / override area for right triangle double area( ) { System. out.println (Inside are for triangle.); return d1 * d2 / 2; } } class Find { public static void main(String args[ ] ) { Fig f = new Fig (10, 10); Angle r = new Angle(9, 5); Triangle t = new Triangle (10, 8); Fig ref; ref = r; System. out.println (Area is + ref.area( ) ); ref = t; System.out.println(Area is + ref.area( ) ); ref = f; System.out.println (Area is +ref.raea( ) ); } } The output from the program is shown here : Inside area for Angle. Area is 45 55 of 149

Java Programming Inside area for triangle. Area is 40 Area for fig is undefined. Area is 0 Through the dual mechanisms of inheritance and run time polymorphism , it is possible to define one consistent interface that is used by several different , yet related, types of objects. In this case, if an object is derived from Fig, then its area can be obtained by calling area( ). The interface to this operation is the same no matter what type of figure is being used.

Using super However, there will be times when you will want to create a superclass that keeps the details of its implementation to itself (that is, that keeps its data members private). In this case, there would be no way for a subclass to directly access or initialize these variables on its own. Since encapsulation is a primary attribute of OOP, it is not surprising that Java provides a solution to this problem. Whenever a subclass need to refer to its immediate superclass, it can do so by use of the keyword super. super has two general forms. The first calls the superclass constructor. The second is used to access a member of the superclass that has been hidden by a member of a subclass. Each use is examined here. Using super to Call Superclass Constructers A subclass can call a constructor method defined by its superclass by the use of the following form of super: super(parameter-list); Here, parameter-list specifies any parameters needed by the constructor in the superclass. super()must always be the first statement executed inside a subclass constructor. To see how super( ) is used, consider this improved version of the BoxWt( ) class : / / BoxWt now uses super to initialize its Box attributes. class BoxWt extends Box1 { double weight ; // weight of box / / initialize width, height, and depth using super( ) BoxWt (double w, double h, double d, double m) { 56 of 149

Java Programming super (w, h, d) ; // call superclass constructor weight = m; } } Here BoxWt( ) calls super( ) with the parameters w, h, and d. This causes the Box( ) constructor to be called, which initializes width, height and depth using these values. BoxWeight no longer initializes these values itself. It only needs to initialize the value unique to it : weight . This leaves Box1 free to make these values private if desired. In the preceding example, super( ) was called with three arguments. Since constructors can be overloaded, super( ) can be called using any form defined by the superclass. The constructor executed will be the one that matches the arguments. For example, here is a complete implementation of BoxWt that provides constructors for the various ways that a box can be constructed. In each case, super( ) is called using the appropriate arguments. Notice that width, height, and depth have been made private within Box. / / A complete implementation of boxwood. class Box 1{ private double w; private double ht; private double d; // / construct clone of an object Box (Box o) { // pass object to constructor w = o.w; ht = o.ht; d = o.d; } // constructor used when all dimensions specified Box1 (double wt, double h, double db) { w = wt; ht = h; d = db; } // constructor used when no dimensions specified Box1() { w = -1; // use -1 to indicate ht = -1 ; // an uninitialized d = -1 ; // box } // constructor used when cube is created 57 of 149

Java Programming Box 1(double l) { w = ht = d = l ; } // compute and return volume double volume ( ) { return w * ht * d ; } } //BoxWeight now fully implements all constructors. class BoxWt extends Box1 { double wt ; // weight of box // / construct clone of an object BoxWt (BoxWt o) { // / pass object to constructor super (o); wt = o.wt ; } // / constructor when all parameters are specified BoxWt (double w, double h, double d, double m) { super (w, h, d); // call superclass constructor wt = m; } // default constructor BoxWt() { super( ); wt = -1; } //constructor used when cube is created BoxWt (double l, double m) { super (l); wt = m; } } class Super { 58 of 149

Java Programming public static void main (String args [ ]) { BoxWt box1 = new BoxWt (10, 20, 15, 34); BoxWt box2 = new BoxWt (2, 3, 4, 0.076); BoxWt box3 = new BoxWt ( ); // default BoxWt cube = new BoxWt (3, 2); BoxWt clone = new BoxWt (box1); double v; v = box1 . volume( ); System.out.println("volume of mybox1 is " + v); System.out.println ("Weight of mybox1 is " + box1.wt); System.out.println( ); v = box2. volume( ); System.out.println("Volume of box2 is " + v); System.out.println("Weight of box2 is " + box2 . wt); System .out.println( ); v = box3.volume( ); System.out.println("Volume of box3 is " + v); System.out.println ( "Weight of box3 is " + box3.wt); System.out.println( ); v = clone.volume( ); System.out.println("Volume of clone is " + v); System.out.println("Weight of clone is " + clone.wt); System.out.println ( ); v = cube.volume ( ); System.out.println ("Volume of cube is " + v); System.out.println ("Weight of cube is " +cube.wt); System.out.println ( ); } } This program generates the following output : Volume of box1 is 3000 Weight of box1 is 34.3 Volume of box2 is 24 Weight of box2 is 0.076 Volume of box3 is -1 Weight of box3 is -1 59 of 149

Java Programming

Volume of clone is 3000 Weight of clone is 34.3 Volume of cube is 27 Weight of cube is 2 Pay special attention to this constructor in BoxWt( ): // construct clone of an object BoxWt (BoxWt o) { / / pass object to constructor super (o); w = o.w; } Notice that super( ) is called with an object of type BoxWt - not of type Box1. This still invokes the constructor Box1(Box ob). As mentioned earlier, a superclass variable can be used to reference any object derived from that class. Thus, we are able to pass BoxWt object to the Box1 constructor . Of course, Box1 only has knoweldge of its own members. Lets review the key concepts behind super( ). When a subclass calls super( ), it is calling the constructor of its immediate superclass. Thus, super( ) always refers to the superclass immediately above the calling class. This is true even in a multileveled hierarchy. Also, super( ) must always be the first statement executed inside a subclass constructor. A second use for super The second form of super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used. This usage has the following general form : super.member Here, member can be either a method or an instance variable. This second form of super is most applicable to situations in which member names of a subclass hide members by the same name in the superclass. Consider this simple class hierarchy. // Using super to overcome name hiding. class P { int a; } // / create a subclass by extending class P. class Q extends P { int a ; // this a hides the a in P 60 of 149

Java Programming Q (int c, int d) { super.a = c; // a in P a = d; // a in B } void show( ) { System.out.println("a in superclass: " + super.a); System.out.println("a in subclass : " + a); } } class Super { public static void main (String args[ ] ) { Q Ob1 = new Q (1, 2) ; Ob1. show( ); } } This program displays the following : a in superclass : 1 a in subclass : 2 Although the instance variable a in Q hides the a in P, super allows access to the defined in the superclass. As you will see, super can also be used to call methods that are hidden by a subclass. Using Abstract Classes There are situations in which you want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method ie. sometimes you will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to subclass to fill in details .Such a class determines the nature of the methods that the subclasses must implement. One way this situation can occur is when a superclass is unable to create a meaningful implementation for a method. This is the case with the class Fig used in the preceding example. The definition of area() is simply a placeholder. It will not compute and display the area of any type of the object. As you will see as you create your own class libraries ,it is uncommon for a method to have no meaningful definition in the context of its superclass.You can this situation in two ways.One way,as shown in the above example .You may have methods which must be overridden by the subclass in order for the subclass to have any meaning.

61 of 149

Java Programming Consider the class Triangle .It has no meaning if area() is not defined.In this case,you want some way to ensure that a subclass does,indeed,override all necessary methods.Javas solution to these problem is the abstract method. You can require that certain methods be overridden by subclasses by specifying the abstract type modifier. These methods are sometimes referred to as subclasses responsibility because they have no implementation specified in the superclass. Thus a subclass must override them---it cannot simply use the version defined in the superclass. To declare an abstract method ,use this general form: abstract type name(parameter-list); As you can see,no method body is present. Any class that contains one or more abstract methods must also be declared abstract.To declare a class abstract,you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration. There can be no objects of an abstract class ie.an abstract class cannot be directly instantiated with new operator. Such objects would be useless,because an abstract class is not fully defined. Also, you cannot declare abstract constructors,or abstract static methods.Any subclass of an abstract class must either implement all of the abstract methods in the superclass ,or be itself declared abstract. Here is a simple example of a class with an abstract method,followed by a class which implements that method: //A simple demonstration of abstract. abstract class P { abstract void callme(); //concrete methods are still allowed in the abstract classes void callmetoo() { System.out.println(This is a concrete method.); } } class Q extends P { void callme() { System.out.println(Qs implementation of callme.); } } class AbstractDemo { public static void main(String args[]) { Q q=new Q(); q.callme(); q.callmetoo(); } 62 of 149

Java Programming } Notice that no objects of class P are declared in the program. As mentioned, it is not possible to instantiate an abstract class.One other point:class P implements a concrete method called callme too().This is perfectly acceptable.Abstract classes can include as much implementation as they see fit. Although abstract classes cannot be used to instantiate objects,they can be used to create object references,because Javas approach to run-time polymorphism is implemented through the use of superclass references.Thus,it must be possible to create a reference to an abstract class so that it can be used to point to a subclass object.You willsee this feature put to use in the next example. Using an abstract class,you can improve the Fig class shown earlier.Since there is no meaningful concept of area for an undefined two-dimensional figure,the following version of the program declares area() as abstract inside Fig .This ,ofcourse,means that all classes derived from Fig must override area(). //Using abstract methods and classes. abstract class Fig { double d1; double d2; Fig(double i,double j) { d1=i; d2=j; } //area is now an abstract method abstract double area(); } class Angle extends Fig { Angle(double i,double j) { super(i,j); } //override area for rectangle double area() { System.out.println(Inside Area for Angle.); return d1*d2; } } class Triangle extends Fig { Triangle(double i,double j) { Triangle(double i,double j) { super(i,j); 63 of 149

Java Programming } //override area for right triangle double area() { System.out.println(Inside Area for Triangle.); return d1*d2 / 2; } } class AbstractAreas() { public static void main(String args[]) { //Fig f =new Fig(10,10); //illegal now Angle r =new Angle(9,5); Triangle t=new Triangle(10,8); Fig f; //this is OK,no object is created f =r; System.out.println(Area is + f .area()); f =t; System.out.println(Area is +f.area()); } } As the comment inside main()indicates,it is no longer possible to declare objects of type Fig,since it is now abstract.And,all subclasses of Fig must override area().You will receive a compile-time error. Although it is not possible to create an object of type Fig, you can create a reference variable of type Fig .The variable f is declared as a reference to Fig,which means that it can be used to refer to an object of any class derived from Fig .As explained,it is through superclass reference variables that overridden methods are resolved at run time.

Creating Package and Interfaces


What is an interface? Using the keyword interface, you can fully abstract a class interface from its implementation. Using interface, you can specify what a class must do, but not how it does it. Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body. In practice, this means that you can define interfaces which dont make assumptions about how they are implemented. Once it is defined, any number of classes can implement an interface. Also, one class can implement any number of interfaces. 64 of 149

Java Programming By providing the interface keyword, Java allows you to fully utilize the one interface, multiple methods aspect of polymorphism. Interfaces are designed to support dynamic method resolution at run time. Normally, in order for a method to be called from one class to another, both classes need to be present at compile time so the Java compiler can check to ensure that the method signatures are compatible. This requirement by itself makes for a static and nonextensible classing environment. Inevitably in a system like this, functionality gets pushed up higher and higher in the class hierarchy so that the mechanisms will be available to more and more subclasses. Interfaces are designed to avoid this problem. They disconnect the definition of a method or set of methods from the inheritance hierarchy. Since interfaces are in a different hierarchy from classes, it is possible for classes that are unrelated in terms of the class hierarchy to implement the same interface. This is where the real power of interfaces is realized. Interfaces add most of the functionality that is required for many applications which would normally resort to using multiple inheritance in a language such as C++. Defining an Interface An interface is defined much like a class. This is the general form of an interface : 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 mehtod-nameN(parameter-list); type final-varnameN=value; } Here, access is either public or not used. When no access specifier is included, then default access results, and the interface is only available to other members of the package in which it is declared. When it is declared as public, the interface can be used by any other code, name is the name of the interface, and can be any valid identifier. Notice that the methods which are declared have no bodies. They end with a semicolon after the parameter list. They are, essentially, abstract methods; there can be no default implementation of any method specified within an interface. Each class that includes an interface must implement all of the methods. 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 65 of 149

Java Programming declares a simple interface which contains one method called Call()that takes single integer parameter. interface Call { void call(int param) }

Implementing an interface 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 methods defined by the interface.The general form of a class that includes the implements clause look as below: access class classname[extends superclass] [implements interface[,interface...]] { //class -body } 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.

PACKAGE Java provides a mechanism for partitioning the class name space into more manageable chunks. This mechanism is the package. The package is both a naming and a visibility control mechanism. You can define classes inside a package that are not accessible by code outside that package. Creating 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 you 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, you will define a package for your code. This is the general form of the package statement : package pk; 66 of 149

Java Programming

Here, pk is the name of the package . For example, the following statement creates a package called MyPack. package MyPack ; You 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 form of a multileveled package statement is shown here : package pkg1[.pkg2[.pkg3] ];

Using package members ///Todo

Managing source and class files Assume that you create a class called Test in a package called test1. Since your directory structure must match your packages, you create a directory called test and put Test.java inside that directory. You then make test the current directory and compiled Test.java. This results in Test.class being stored in the test1 directory, as it should be. When you try to run Test, though, the Java interpreter reports an error message similar to cant find class Test as it is because the class is now stored in a package called test1. You can no longer refer to it simply as Test.You must refer to the class by enumerating its package hierarchy, separating the packages with dots. This class must now be called test.Test.

67 of 149

Java Programming Implementing nested class Inner classes In Java its possible to place a class definition within another class definition. This is called an inner class. The inner class is a useful feature because it allows you to group classes that logically belong together and to control the visibility of one within the other. However, its important to understand that inner classes are distinctly different from composition. Often, while you're learning about them, the need for inner classes isnt immediately obvious. At the end of this section, after all of the syntax and semantics of inner classes have been described, youll find an example that should make clear the benefits of inner classes.

Static nested classes To understand the meaning of static when applied to inner classes, you must remember that the object of the inner class implicitly keeps a handle to the object of the enclosing class that created it. This is not true, however, when you say an inner class is static. A static inner class means: You dont need an outer-class object in order to create an object of a static inner class. You cant access an outer-class object from an object of a static inner class. There are some restrictions: static members can be at only the outer level of a class, so inner classes cannot have static data or static nested classes

Anonymous nested class


Some classes that you define inside a method do not need a name. A class defined in this way without a name is called an anonymous class. Clearly you cannot use new in the usual way to create an instance of a class if you do not know its name. Additional Featuresof Anonmous classes: The following are the additional features supported by anonymous classes: An anonymous class can be a sub classof another explicit class or it can implement a single explicit interface. An anonymous class cannot be both an explicit subclass and implement an interface. Note that extending Object is implicit where an interface is implemented. If an anonymous class extends an existing calss rather than implements an interface then arguments for the superclass constructor may be placed in the argumenty part of the new expression like: 68 of 149

Java Programming

NewButton (Press me) { //define some modification of Button} The parent class for anonymous classes that implement interfaces is the java.lang.Object.Its constructor has no arguments

69 of 149

Java Programming

String and StringBuffer


The java.lang package contains two strings Classes: String StringBuffer Youve already seen the String class on several occasions. You use the String class when you are working with strings that cannot change. StringBuffer , on the other hand,is used when you want to manipulate the contents of the string. Creating string Many Strings are created from string literals. When the compiler encounters a series of characters enclosed in double quotes,it creates a String object whose value is the text that appeared between the quotes.When the compiler encounters the following string literal,it creates a String object whose value is Gobbledy gook. Gracy Team. You can also create String objects as you would any other Java object: using the new keyword. new String(Gracy Team.); Creating StringBuffer The constructor method used by the reverselt ti intialize the dest requires an integer argument indicating the initial size of the new StringBuffer. StringBuffer(int length) Reverse lt could have used StringBuffers default constructor that leaves the buffers length undetermined until a later time.However,its more efficient to specify the length of the buffer if you know it,instead of allocating more memeory every time you append a character to the buffer .The following statement taken form the reverselt method creates a new StringBuffer in three steps: declaration,instantiation, and initialization. StringBuffer dest= new StringBuffer(len); These are the same steps for creating an object of any type. Accessor methods for string and string buffer 70 of 149

Java Programming

The reverselt method use two accessor methods to obtain information about the source string:charAt and length. Both String and StringBuffer provide a number of other accessor methods, including some for inspecting substrings and getting the positions of a specific character. Accessor method for String: charAt() To extract a single character from a string ,you can refer directly to an individual character via the charAt() method .It has general form: char charAt(int where) Here, where is the index of the character that you want to obtain .The value of where must be nonnegative and specify a location within the string .charAt() returns the character at the specified location. For example, char c; c= acd .charAt(1); assigns the value c to c. String length The length of a string is the number of characters that it contains. To obtain this value, call the length() method ,shown here : int length() The following fragment prints 3,since there are three characters in the string ,s: char chars[] ={a, b, c}; String s= new String(chars); System.out println(s.length());

Modifying string buffer

71 of 149

Java Programming The reverselt method uses StringBuffers append method to add character to dest. In addition to append, StringBuffer provides methods to insert characters into the buffer, modify a character at a specific location within the buffer, and so on. Converting objects to strings You can convert several different data types to Strings using Strings valueOf method. The valueOf() method converts data from its internal format into a humanreadable form. static static static static String valueOf(double num) String valueOf(long num) String valueOf(Object o) String valueOf(char chars[])

Primitive data types and wrapper classes The java programming language does not look at primitive data types as objects. For example, numerical, boolean , and character data are treated in the primitive form for the sake of efficiency .The java programming language provides wrapper classes to manipulate primitive data elements as objects>such data elements are wrapped in an object created around them. Each Java primitive data type has a corresponding wrapper class in the java.lang package. As discussed in the earlier chapters the primitive datatypes such as int, float ,char etc has a corresponding wrapper classes. Wrapper Classes Look at the primitive data elements as objects
Primitive DataType boolean byte char short int long float double Wrapper Class Boolean Byte Character Short Integer Long Float Double

Discuss the need and use of wrapper classes

72 of 149

Java Programming Wrapper classes provides useful static methods for a particular type with a logical & consistent way. Provide descriptive methods & fields in a logical way. Can be used in any context where an object referenced is required.

Important Assessor methods in each Some of the important assessor methods are discussed as below: Class Number public instance methods public abstract double doubleValue() public abstract float floatValue() public abstract int intValue() public abstract long longValue()

Class Integer Some of the Instance methods public double doubleValue() public boolean equals (Object o) public float floatValue() public int intValue() public long longValue() public string toString() / / Construct string from subset of char array. class SubStrCon { public static void main (String args[ ] ) { byte ascii [] = { 65, 66, 67, 68, 69, 70 }; String str = new String(ascii, 0); System.out.println (str); String str1 = new String (ascii, 0, 2, 3); System.out.println (str1); }} This program generates the following output : ABCDEF CDE 73 of 149

Java Programming The contents of the array are copied whenever you create a String object from an array. If you modify the contents of the array after you have created the string, the String will be unchanged. You can construct a String object that contains the same character sequence as another String object using this constructor : String (String Obj) Here, Obj is a String object. Consider this example: // Construct one String from another. class Make { public static void main(String args[]) { char c[ ] = { J , a, v, a); String s1 = new String (c); String s2 = new String (s1); System.out.println(s1); System.out.println(s2); } } The output from this program is as follows : Java Java String Length The length of a string is the number of characters that it contains. To obtain this value, call the length( ) method, shown here : int length( ) The following fragment prints 3, since there are three characters in the string , s : char chars[ ] = { p, q, r }; String str = new String (chars); System.out.println (str.length() ); String Concatenation In general, Java does not allow operators to be applied to String objects. The one exception to this rule is the + operator. The + concatenates two strings, producing a String object as the result. This allows you to chain together a series of + operations. For example, the following fragment concatenates three strings : 74 of 149

Java Programming

String age = 17 ; String str = He is + age + years old; System.out.println(str); This displays the string He is 17 years old. / / Using concatenation to prevent long lines. class Concat { public static void main (String args[ ] ) { String Str = This could have been + a very long line that would have + wrapped around. But string concatenation + prevents this.; System.out.println (Str); } } String Concatentation with other Data types You can concatenate strings with other types of data. For example, consider this slightly different version of the earlier example : int age = 9; String str = :He is + age + years old.; System.out.println(str); In this case, age in an int rather than another String. But the output produced is the same as before. This is because the int value in age is automatically converted into its string representation within a String object. This string is then concatenated as before. The compiler will convert an operand to its string equivalent whenever the other operand of the + is an instance of String. Be careful when you mix other types of operations with string concatenation expressions, however. Consider the following: String str = four: + 2 + 2; System.out.println (str); This fragment displays four : 22 rather than the 75 of 149

Java Programming four : 4 that you probably expected. Heres why . Operator precedence causes the concatenation of four with the string equivalent of 2 to take place first. This result is then concatenated with the string equivalent of 2 a second time. To complete the integer addition first, you must use parentheses, like this : String str = four: + (2 + 2); Now s contains the string four : 4. String Conversion and toString( ) When Java converts data into its string representation during concatenation, it does so by calling one of the overloaded versions of the string conversion method valueOf( ) defined by String.valueOf( ) is overloaded for all the simple types and for type object. For the simple types, valueOf( ) returns a string that contains the human readable equivalent of the valued with which it is called. For objects, valueOf( ) calls the toString( ) method on the object. We will look more closely at valueOf( ) later . Here, lets examine the toString( ) method, because it is the means by which you can determine the string representation for objects of classes that you create. Character Extraction The string class provides a number of ways that characters can be extracted from a String object. Each is examined here. Although the characters that comprise a string within a string object cannot be indexed as if they were a character array, many of the String methods employ an index (or offset ) into the string for their operation. Like arrays, the string indexes begin at zero. charAt( ) To extract a single character from a String, you can refer directly to an individual character via the charAt( ) method. It has this general form : char charAt(int where) Here. where is the index of the character that you want to obtain. The value of where must be nonnegative and specify a location within the string. charAt( ) returns the character at the specified location. For example, char c; c = abnc.charAt(1); assigns the value b to c. getchars( ) 76 of 149

Java Programming

If you need to extract more than one character at a time, you can use the getChars( ) method. It has this general form : void getChars(int sourceStart, intsourceEnd, char target[ ], int targetStart) The following program demonstrates getChars( ): class getCharsDem { public static void main(String args[ ] { String str = This is a demo of the getchars method.; int start = 10; int end = 14; char buf[ ] = new char[end - start]; str.getChars(start, end , buf, 0); System.out.println(buf); } } Here is the output of this program : demo toCharArray( ) If you want to convert all of the characters in a String object into a character array, the easiest way is to call toCharArray( ). It returns an array of characters for the entire string. It has this general form : char[ ] toCharArray( ) This function is provided as a convenience, since it is possible to use getChars( ) to achieve the same result. String Comparison The string class includes several methods that compare strings or substrings within strings. Each is examined here. equals( ) and equalsIgnoreCase( ) To compare two strings for equality, use equals( ). It has this general form: boolean equals(Object str) 77 of 149

Java Programming Here, str is the String object being compared with the invoking String object. It will return true if the strings contain the same characters in the same order and false otherwise. The comparison is case sensitive. To perform a comparison that ignores case differences, call equalsIgnoreCase( ). When it compares two strings, it considers A-Z to be the same as a-z. It has this general form: boolean equalsIgnoreCase(string str) Here, str is the string object being compared with the invoking String object. It too, will return true if the strings contain the same characters in the same order and false otherwise. Here is an example that demonstrates equals( ) and equalsIgnoreCase( ): / / Demonstrate equals( ) and equalsIgnoreCase( ). class equalsDemo { public static void main (String args[ ] ) { String str1 = Hello; String str2 = Hello; String str3 = Good-bye; String str4 = Hello; System.out.println(str1 + equals + str2 + -> + str1. equals(str2); System.out.println(str1 + equals + str3 + -> + str1. equals(str3); System.out.println(str1 + equals + str4 + -> + str1. equals(str4); System.out.println(str1 + equalsIgnoreCase + str4 + -> + str1. equalsIgnoreCase(str4) ); } } The output from the program is shown here : Hello equals Hello-> true Hello equals Good-bye -> false Hello equals HELLO -> false Hello equalsIgnoreCase HELLO -> true compareTo( ) Often it is not enough to simply know whether two strings are identical. For sorting applications, you need to know which is less than, equal to, or greater than the next. A string is less than another if it comes before the other in dictionary order. A string is greater 78 of 149

Java Programming than another if it comes after the other in dictionary order. The string method compareTo( ) serves this purpose. It has this general form: int compareTo(String str) Here, str is the String being compared with the invoking String. The result of the comparison is returned and is interpreted as shown here: Value Less than zero Greater than zero Zero Meaning The invoking string is less than str. The invoking string is greater than str. The two strings are equal.

Here is a sample program that sorts an array of strings. The program uses compareTo( ) to determine sort ordering for a Bubble sort: / / A bubble sort for strings. class Sort { static String ar[ ] = { Now, is, the, time, for, all, good, men, to, come, to, the, aid, of, their, country }; public static void main(String args[ ] ) { for (int j = 0; j < ar.length; j++) { for (int i = j + 1; i < ar.length ; i++) { if (ar[i]. compareTo(ar[j] ) < 0) { String t = ar [j]; ar[j] = ar[i]; ar[i] = t; } } System.out.println(ar[j]); } } } The output of this program is the list of words : Now aid all come 79 of 149

Java Programming country for good is men of the the their time to to As you can see from the output of this example, compareTo( ) takes into account uppercase and lowercase letters. The word Now, came out before all the others because it begins with an uppercase letter, which means it has a lower value in the ASCII character set. At this time, there is no method for String ordering that will ignore case.

Modifying a String Since string objects are immutable, whenever you want to modify a String, you must either copy it into a StringBuffer or use one of the following String methods which constructs a new copy of the string with your modifications complete. substring( ) You can extract a substring using substring( ) . It has two forms. The first is String substring(int startIndex) Here, startIndex specifies the index at which the substring will begin. This form returns a copy of the substring that begins at startIndex and runs to the end of the invoking string. The second form of substring( ) allows you to specify both the beginning and ending index of the substring: String substring(int startIndex, int endIndex) Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. The string returned will contain all of the characters from the beginning index, up to but not including the ending index. The following program uses substring( ) to replace all instances of one substring with another within a string : 80 of 149

Java Programming / / Substring replacement. class StringReplace { public static void main (String args[ ] ) { String str = This is a test. This is, too.; String str1 = is; String str2 = was; String str3 = ; int a ; do { / / replace all matching substrings System.out.println(org); a = str.indexOf(search); if ( a = ! = -1) { str3 = str.substring (0, i); str3 = str + str2; str3 = str3 + str.substring( i + search.length( ) ); str = str3; } } while ( i ! = -1); } } The output from this program is shown here : This is a test. This is, too. Thwas is a test. This is, too. Thwas was a test. This is , too. Thwas was a test. Thwas is, too. Thwas was a test. Thwas was, too. concat( ) You can concatenate two strings using concat( ), shown here : String concat(String str) This method creates a new object that contains the invoking string with the contents of str appended to the end. concat( ) performs the same function as +. For example, string str = one; String str1 = str. concat(two); puts the string onetwo into str1. It generates the same result as the following sequence: String str = one; String str1 = str + two; 81 of 149

Java Programming

replace( ) The replace( ) method replaces all occurrences of one character in the invoking string with another. It has the following general form: String replace(char original, char replacement) Here, original specifies the character to be replaced by the one specified by replacement. The resulting string is returned. For example, String str =Hello. replace (1, w); puts the string Hewwo into s. trim( ) The trim( ) method returns a copy of the invoking string from which any leading and trailing whitespace has been removed. It has this general form : String trim( ) Here is an example: String str = Hello world .trim( ); This puts the string Hello World into str. The trim( ) method is quite useful when you process user commands. For example, the following program prompts the user for the name of a state and then displays that states capital. It uses trim( ) to remove any leading or trailing whitespace that may have inadvertently been entered by the user.

Changing the Case of characters within a string The method toLowercase( ) converts all the characters in a string from uppercase to lowercase. The toUpperCase( ) method converts all the characters in a string from lowercase to uppercase. Nonalphabetical characters, such as digits, are unaffected. Here are the general forms of these methods : String toLowerCase( ) String toUpperCase( )

82 of 149

Java Programming Both methods return a String object that contains the upper or lowercase equivalent of the invoking String. Here is an example that uses toLowerCase( ) and toUpperCase( ): / / Demonstrate toUpperCase( ) and toLowerCase( ). class changecase { public static void main (String args[ ] ) { String str = This is a test.; System.out.println (Original: + str); String upper = str.toUpperCase( ); String lower = str.toLowerCase( ); System.out.println (uppercase: + upper); System.out.println (Lowercase: + lower); } } The output produced by the program is shown here : Original : This is a test. Uppercase : THIS IS A TEST. Lowercase : this is a test. String Buffer StringBuffer is a peer class of String that provides much of the functionality of strings. As you know, String represents fixed length, immutable character sequences. In contrast, StringBuffer represents growable and writeable character sequences. StringBuffer may have characters and substrings inserted in the middle, or appended to the end. StringBuffer will automatically grow to make room for such additions and often has more characters pre allocated than are actually needed, to allow room for growth . Java uses both classes heavily, but many programmers deal only with String and let Java manipulate StringBuffers behind the scenes by using the overloaded + operator. StringBuffer Constructors StringBuffer defines these three constructors: StringBuffer( ) StringBuffer( int size) StringBuffer(String str ) The default constructor (the one with no parameters) reserves room for 16 characters without allocation. The second version accepts an integer argument that explicitly sets the 83 of 149

Java Programming size of the buffer. The third version accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation. StringBufer allocates room for 16 additional characters when no specific buffer length is requested, because reallocation is a costly process in terms of time. Also, frequent reallocations can fragment memory. By allocating room for a few extra characters, StringBuffer reduces the number of reallocations that take place. length( ) and capacity( ) The current length of a StringBuffer can be found via the length( ) method, while the total allocated capacity can be found through the capacity( ) method. They have the following general forms : int length( ) int capacity( ) Here is an example : / / StringBuffer length vs.capacity. class StringBuffer { public static void main(String args[ ] ) { StringBuffer sb = new StringBuffer (Hello); System.out.println (buffer = + sb); System.out.println(length = + sb.length( ) ); System.out.println(capacity = sb.capacity( ) ); } } Here is the output of this program, which shows how StringBuffer reserves extra space for additional manipulations : buffer = Hello length = 5 capacity = 21 Since sb is initialized with the string Hello when it is created, its length is 5. Its capacity is 21 because room for 16 additional characters is automatically added. ensureCapacity( ) If you want to pre-allocate room for a certain number of characters after a StringBuffer has been constructed, you can use ensureCapacity( ) to set the size of the buffer. This is useful if you know in advance that you will be appending a large number of small strings to a StringBuffer. ensureCapacity( ) has this general form : void ensureCapacity (int capacity) 84 of 149

Java Programming Here, capacity specifies the size of the buffer setLength( ) To set the length of the buffer within a StringBuffer object, use setLength( ). Its general form is shown here : void setLength (int len) Here, Len specifies the length of the buffer. This value must be nonnegative. When you increase the size of the buffer, null characters will be added to the end of the existing buffer. if you call setlength( ) , then the characters stored beyond the new length will be lost. The setCharAtDemo sample program that follows uses setLength( ) to shorten a StringBuffer. charAt( ) and setCharAt( ) The value of a single character can be obtained from a StringBuffer via the charAt( ) method. You can set the value of a character within a StringBuffer using setCharAt( ). Their general forms are shown here : char charAt(int where) void setCharAt(int where, char ch) For charAt (), where specifies the index of the character being obtained. For setCharAt(), where specifies the index of the character being set, and ch specifies the new value of that character. For both methods, where must be nonnegative and must not specify a location beyond the end of the buffer. To copy a substring of a StringBuffer into an array, use the getChars( ) method. It has this general form : void getChars (int sourceStart, int sourceEnd, char target[ ], int targetStart) Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an index that is one past the end of the desired substring. This means that the substring contains the characters from sourceStart through sourceEnd - 1. The array that will receive the characters is specified by target. The index within target at which the substring will be copied is passed in targetStart. Care must be taken to assure that the target array is large enough to hold the number of characters in the specified substring. append( )

85 of 149

Java Programming The append( ) method concatenates the string representation of any other type of data to the end of the invoking StringBuffer object. It has overloaded versions for all of the built in types and for Object. Here are a few of its forms : StringBuffer append(String str) StringBuffer append(int num) StringBuffer append(Object obj) String.valueOf( ) is called for each parameter to obtain its string representation. The result is appended to the current StringBuffer object. The buffer itself is returned by each version of append( ) insert( ) The insert( ) method inserts one string into another. It is overloaded to accept values of all the simple types, plus Strings and Objects. Like append( ), it calls String.valueOf( ) to obtain the string representation of the value it is called with. This string is then inserted into the invoking StringBuffer object. These are a few of its forms : StringBuffer insert(int index, String str) StringBuffer insert(int index, char ch) StringBuffer insert(int index, Object obj) reverse( ) You can reverse the characters within a StringBuffer object using reverse( ), shown here : StringBuffer reverse( ) This method returns the reversed object on which it was called. The following program demonstrates reverse( ): class Reverse { public static void main(String args[ ] ) { StringBuffer str = new StringBuffer (pqrst); System.out.println(str); str.reverse( ); System.out.println(str); } } Here is the output produced by the program: pqrst tsrqp

86 of 149

Java Programming

87 of 149

Java Programming

Command line arguments & Collection


- Handling command line arguments Sometimes you will want to pass information into a program when you run it. This is accomplished by passing command- line arguments to main () .A command-line argument is the information that directly follows the programs name on the command line when it is executed . // Display all command-line arguments. class CommandLine { public static void main(String args[]) { for( int i =0; i<args.length; i+ +) System.out.println(args [ + i + ]: +args[i]); } } Try executing this program,as shown here: java CommandLine is a test 100 1 When you do,you will see the following output: args[0]:this args[1]:is args[2]:a args[3]:test args[4]:100 args[5]:-1

Reading System Properties


The System class has two methods that you can use to read the system properties: getProperty and getProperties. The System class has two different versions of getProperty. Both retrieve the value of the property named in the argument list. The simpler of the two getProperty methods takes a single argument: the key for the property you want to search for. For example, to get the value of path.separator, use the following statement: 88 of 149

Java Programming System.getProperty("path.separator"); The getProperty method returns a string containing the value of the property. If the property does not exist, this version of getProperty returns null.

The runtime object and vector object


In java, arrays are of fixed length. Once created, they cannot grow or shrink. This means that you must know in advance how many elements an array will hold. But sometimes you may not know until run time precisely how large an array you will need. To handle this situation, Java defines the Vector class. A Vector is a variable-length array of object references ie. a vector can dynamically increase or decrease in size. Vectors are created with an initial size. When the size is exceeded, the vector is automatically enlarged. When objects are removed, the vector may be shrunk. Vector()-Creates a default vector. Vector(int size)-Creates a vector whose initial capacity is specified by size. Vector(int size, int incr);-Creates a vector whose initial capacity is specified by size and whose increment is specified by incr. Vector defines these data members: int capacityIncrement;-increment value is stored in capacityIncrement. int elementCount;-number of elements currently in the vector is stored. Object elementData[];-the array that holds the vectors are stored. Vector defines several methods and implements the Cloneable interface

89 of 149

Java Programming

The Collection Framework


One of the most exciting enhancements added by Java2 is collection. A collection is a group of objects. It is contained in the java.util package. Collections Overview The Java collections framework standardizes the way in the which groups of objects are handled by your programs. In the past, Java provided ad hoc classes such as Dictonary, Vector, Stack, and Properties to store and manipulate groups of objects. Although these classes were quite useful, they lacked a central, unifying theme. Collections are an answer to these (and other) problems. The collection framework was designed to meet several goals: The framework had to be high-performance. The implementations for the fundamental collection (dynamic array, linked lists, trees, and hash tables) are highly efficient. These data engines are seldom coded manually. The framework had to allow different types of collections to work in a similar manner and with a high degree of interoperability. Extending and/or adapting a collection to be easy. Toward this end, the entire collection framework is designed around a set of standard interfaces. Several standard implementations (such as LinkedList , HashSet, and TreeSet) of these interfaces are provided . An important part of the collection mechanism are Algorithms.They operate on collections and define a static method within the Collection class. Thus, they are available for all collections. The algorithms provide a standard means of manipulating collections.

Java Exceptions
The term Exception means an exceptional event that occurs during the execution of a program and may disrupt the normal flow of instructions. These exceptions may be caused by many errors including hardware errors hard disk crash or simple programming errors such as trying to access an out of bounds array element. When such an error occurs within a Java method the method creates an exception object and hands it off to the runtime system. This object contains information about the exception including its type and the state of the program when the error occured. 90 of 149

Java Programming Try, catch blocks Java exception handling is managed through five key words try , catch , throw, throws and finally. Program statements that you want to monitor for exceptions are contained within a try block. If an exception occurs within the try block it is thrown .The code can catch this exception and handle it in some rational manner. Specify the exception type that you wish to catch in the catch clause immediately following the try block. The following program includes a try and catch clause which has an Arithmetic Exception genrated by the division by zero error. class Excep1{ public static void main(String args[ ] ) { int a,b; try // block of code to be monitored { a = 0; b = 18 ; System.out.println("this will not be printed "); } catch (ArithmeticException e) // catch divide by zero eror. { System.out.println( "Division by zero. "); } System.out.println( "After catch statement "); } } The output of the program is : Division by zero. After catch statement. Throw exceptions The Java runtime system and some of the classes from the JAva PAckage all throw exceptions under some circumstances. You can use the same mechanism to throw exceptions in your Java programs. All exceptions must inherit from the Throwable class defined in the java.lang package. Before you can catch an exception some JAva code must throw one. Any JAva code can throw an exception ; your code, code from a package written by somewhere else or the Java runtime system. Regardless of who (or what) throws the exception its always thrown with the JAva throw statement.

91 of 149

Java Programming To manually throw an exception use the keyword throw. Any exception that is thrown out of a method must be specified by a throws clause. Any code that must be excuted before a method returns is put in a finally block. Specifying the exceptions thrown by a method If a method is capable of causing exception that it does not handle it must specify this behavior so that callers of the method can guard themselves against that exception. You can do this by including a throws clause in the method's declaration. This clause listrs the type of excption that the method can throw. This is necesary for all exceptions except for those of type Error or RuntimeException or ny of their subclasses. All other exceptions that a method can throw must be declared in the throws clause . If they are not a compile time error results. The general form of a method declaration that includes a throws clause: type method-name(parameter-list) throws exception-list { // body of method } Here the exception list is a list of exceptions that a method can throw. Example: class ExcDemo { static void throwOne( ) throws IllegalAccessException { System.out.ptrintln( "Inside throwOne."); throw new IllegalAccessException(" Exception Demo"); } public static void main(String args[ ] ) { try { throwOne( ); } catch(IllegalAccessException e) { System.out.println(" Caught " +e); } } } The output generated with this program is as follows: 92 of 149

Java Programming inside throwOne caught java.lang.IllegalAccessException: Exception Demo. How to throw exceptions with throw statements The throw statement requires a single argument : a throwable object. In Java throwable objects are instances of any subclass of the Throwable class. Example of a throw statement: throw someThrowableObject ; If you atempt to throw an object that is not throwable the compiler refuses to compile your program and displays an error message similar to the following: testing.java:10: cannot throw class java.lang.Integer; it must be a subclass throw new Integer(4); ^ The following diagram illustrates the class hierarchy of the Throwable class and its n\most significant subclasses.
Object

Throwable Error
Exception

RunTime Exception ........... ............. .............

Throwable has two direct descendants : Error and Exceptions. Creating your own exception class You can create your own exception types to handle situations specific to your applications. TO do this just define a subclass of Exception( subclass of Throwable). 93 of 149

Java Programming The exception class does not define any methods of its own. It obly inherits those methods provided by Throwable. Thus all exceptions including those that you create have the methiods defines by Throwable available to them.You can even override one or more of these methods in exception classes that you create. The following example creates an Exception : class MyException extends Exception { private int detail; MyException( int a) detail = a ; } public String toString ( ) { return "MyException [ " + detail + " ]" ; } }

Applets
Applets are Java programs that are referenced by a Web Page and run inside a Java enabled Web Browser. Applets inherit from the AWT Container Class. They are designed to hold Components User interface objects such as buttons labels, pop up lists and scroll bars. Applets use layout managers to control the positioning of Components. Applets cannot read or write files on the computer that it is executing on and it cannot make network connections except to the host that it cam from. Applets can invoke the public methods of other applets on the same page. You need to add an applet to a HTML page so that it can run. Life cycle of an applet The life cycle of an Applet consists of the following methods: init ( ) start ( ) paint ( ) stop ( ) destroy ( ) 94 of 149

Java Programming

The init ( ) method is the first method to be called. Here you should initialize variables. This method is called only once during the run time of your applet. The start ( ) method is called after init ( ). It is also called to restart an applet after it has been stopped. This method is called each time an applet's HTML document is displayed on screen. If you leave an applet and come back the applet resumes execution at start ( ). The paint ( ) method is called each time when the applet's output is drawn. This method is called when the applet begins execution. This method has one parameter called Graphics which contains the graphics context that describes the graphics environment in which the applet is running. It is used whenever output to the applet is required. The Stop ( ) method is called when a web Browser leaves the HTML document containing the applet - when it goes to another page. You can use this method to suspend threads that don't need to run when the applet is not visible. You can restart them when start( ) is called. The destroy ( ) method is called when the environment determines that your applet needs to be removed completely from memory. You should free up all resources the applet uses at this point. The stop( ) method is always called before destroy ( ). You may have to override the update( ) method with your applet in some situations. This method is called when your applet has requested that a portion of its window be redrawn. The default version of update ( ) first fills an applet with the default background color and then calls paint ( ). If you fill the background using a different color in paint( ) you experience a flash of default background each time update( ) is called. The following example shows you an overridden paint( ) method. public void update( Graphics g ){ redisplay your window. } public void paint ( Graphics g ) { update(g); } Using the <applet> tag You can use the APPLET tag to start an applet from both a HTML document and from an appletviewer. The Internet Explorer and Netscape browsers allow many applets ton a single page whereas the applet viewer executes each APPLET tag that it finds in a separate window. The syntax of the APPLET tag is as follows: 95 of 149

Java Programming

<APPLET [CODEBASE = cedebaseURL] CODE = appletFile [ALT = alternate Text] [NAME = appletInstanceName WIDTH = pixels HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels ] [HSPACE = pixels] > [<PARAM NAME = AttributeName1 VALUE = AttributeValue >] [<PARAM NAME = AttributeName2 VALUE = AttributeValue >] .......... </APPLET >

Creating an user interface: To produce a visually pleasing user interface you must Select appropriate Components Organize them within your Windows.

Thus organizing involves Adding each component into a potentially visible container( Frame or Applet). 1. Setting the size of the component and its placement within the container. A typical user interface screen is constructed as a containment tree which is rooted in the top most container. Basic Controls The following are the basic AWT controls : Labels Push Buttons Checkboxes Choice Menus Lists Scroll bars Text editing 96 of 149

Java Programming

These controls are subclasses of Component.

Buttons
These are the most widely used controls . It contains a label and generates an event when it is pressed. They are objects of type Button. It defines the following constructors. Button( ) Button( String str ) The first version creates an empty button. The second creates a button that contains str as a label . You can set a label for the button by calling setLabel( ) .You can retrieve the label by calling getLabel( ) . The corresponding methods are as follows: void setLabel ( String str ) String getLabel ( ) Here str is the label of the button. Whenever a button is pressed action ( ) is called.

Checkboxes
It is a control that can be used to turn an option on or off. It consists of a small box that can either contain a check mark or not. There is a label associated with each check box that describes what option the box represents. You can change the state of a check box by clicking on it . They can be used individually or as part of a group. They are objects of the Checkbox class. It has the following constructors: Checkbox ( ) Checkbox ( String str ) Checkbox ( String str , CheckboxGroup cbg , boolean on )

The first from creates a checkbox that is initially blank. The second form creates a checkbox whose label is specified by str. The third form creates a checkbox whose label is specified str and whose group is specified by cbg .The value of on determines the initial state of the checkbox. To retrieve the current state of the box call getState( ). To set its state call setState( ) . You can get the label associated with the checkbox using getLabel( ) . To set the label use .use setLabel( ). The following are the corresponding methods: boolean getState ( ) 97 of 149

Java Programming void setState ( boolean on ) String getLabel( ) void setLabel(String str)

If on is true the box is checked ,if it is false the box is cleared. Each time the checkbox is pressed action ( ) is called. You will be knowing about action events in the later sections.

Choices
The Choice class is used to create a pop list of items from which the user may choose. Thus the Choice control is a form of menu. When the user clicks on it the whole list of choices pops up and a new selection can be made. Each item in the list of String that appears as a left justified label in the order it is added to the Choice object. To add a selection to the list call addItem( ). It has the general form : void addItem(String name ) Here name is the name of the item being added. Items are added to the list in the order in which calls to addItem ( ) occur. To determine which item is currently selected, you can call either getSelectedItem( ) or getSelectedIndex( ) . The following are shown here: String getSelectedItem ( ) int getSelectedIndex ( )

The getSelectedItem ( ) method returns a string containing the name of the item, getSelectedIndex ( ) returns the index of the item. To obtain the number of items in the list call countItems( ) . You can set the currently selected item using the select ( ) method with either a zero based integer index or a string that will match a name in the list. You can obtain the name associated with the item at that index by calling the getItem ( ) method. These methods are as follows: int countItems( ) void select ( String name) String getItem( int index)

Index is the index of the desired item. Each time a choice is selected action ( ) is called. Choice lists do not cause immediate actions but the current selection is simply obtained by the application .

Menus

98 of 149

Java Programming You can attach a MenuBar class to a frame to provide drop down menu capabilities. You might be familiar with these Menu bars in your MS Word(File, Edit , View , Insert etc.,)The following example creates a Menu bar. MenuBar myMenuBar = new MenuBar( ); You can add it to a Frame by using the following method: myFrame.setMenuBar(myMenuBar); You can add menus to a menu bar by using the add method: public synchronized Menu add( Menu newMenu) The folowing code creates a menu called File and adds it to the Menu bar. Menu fileMenu = new Menu (File); myMenubar.add(fileMenu); You can create menus that sty up after you release the mouse button which are called tear off menus.You can specify that the menu is a tear off menu when you create it by using the following syntax: public Menu(String menuLabel , boolean allowTearoff) After adding the sub menus to the Menubar you can add menu items to it.Menu items are the parts of a menu that the user actually selects. Ex: The File menu on any system contains menu items such as New, Open , Save , and Save As etc., You can add menu iems using the following method : fileMenu.add(Open); // Adds an Open option to the file menu. You can also add an instance of a MenuItem class to a menu : MenuItem saveMenuItem = new MenuItem( Save ); fileMenu.add(saveMenuItem); // Adds the Save option to the file menu. You can enable or disable menu items by using enable and disable. follows: saveMenuItem.disable ( ) ; saveMenuItem.enable ( ); The format is as

// Disables the save option from the file Menu. // Enables the save option again.

In order to add submenus and menu separators( a line that appears on the menu to separate sections of the menu) to a menu you need to call the addSeparator method: public void addSeparator ( ); 99 of 149

Java Programming To create a submenu just create a new instance of a menu and add to the current menu: Menu printSubmenu = new Menu( Print); fileMenu.add(printSubmenu); printSubmenu.add( Print Preview); // Add print preview as option on Print menu . printSubmenu.add(Print Document); // Add Print document as option on Print menu. Whenever a Menu item is selected it eithere generates an action event or it call sits action method depending on the event model you are using. The following code implements the actionPerformed( ) method: public void actionPerformed(ActionEvent event) { if ( event.getSource ( ) instanceOf MenuComponent ) if ( event.getSource ( ) == saveMenuComponent ) { // Handle save option } } } The following example sets up a Fiel menu with New , Open ,and Save menu items , a checkbox called Auto - Save and a Print submenu with two menu items. import java.awt.* ; import java.applet.*; public class MenuApplication extends Object { public static void main(String[ ] args ) { // Create the frame and the menubar. Frame myFrame = new Frame ( Menu Example ); MenuBar myMenuBar = new MenuBar ( ) ; // Add the menubar to the frame myFrame.setMenubar(myMenubar); //Create the File menu and add it to the menubar Menu fileMenu = new Menu (File); myMenuBar.add(fileMenu); // Add the New and Open menuitems fileMenu.add(new MenuItem( New) ); 100 of 149

Java Programming fileMenu.add(new MenuItem( Open ) ); // Create a disabled Save menuitem MenuItem saveMenuItem = new MenuItem (Save); fileMenu.add(saveMenuItem); saveMenuItem .disable ( ) ; // Add an Auto- Save checkbox followed by a separator fileMenu.add(new CheckboxMenuItem(Auto-Save) ); fileMenu.addSeparator( ); // Create the Print submenu Menu printSubmenu = new Menu( Print); fileMenu .add(printSubMenu); printSubmenu .add(Print Preview); printSubmenu .add(Print Document ); // Specify the size of the frame myFrame.resize( 300,300); // Make the frame appear on the screen myFrame.show ( ); } } You can even create a popmenu for a component that enables you to click the component with the right or middle mouse button and bring up a menu specific to that component You can create a pop menu using the following constructors: public PopupMenu ( ) public PopupMenu ( String title) You need to add the MenuItem objects to the pop menu . After all the items are added then add the popmenu to a component using the components add method : PopupMenu popup = new PopupMenu ( Button Stuff ); popup.add(Winken); popup.add(Blinken); popup.add(Nodd); Button myButton = new Button ( Click); myButton.add(popup);

Lists
101 of 149

Java Programming The List class provides a compact multiple choice scrolling selection list. While the Choice object shows only one choice the List object can be constructed to show any number of choices . It can also be created to allow multiple selections. The following are the constructors provided by List: List ( ) List ( int numRows , boolean multipleSelect )

The first form creates a List control that allows only one item to be selected at any one time. In the second version the value of numRows specifies the number of entries in the list that will always be visible . If multipleSelect is true then the user may select two or more items at a time. If it is false then only one item may be selected. To add a selection to the list call addITem ( ) which has the following forms: void addItem ( String name ) void addItem ( String name , int index )

Here name is the name of the item added to the list. The first form adds items to the end of the list. The second form adds the item at the index specified by index. For lists that have only single choice you can fin which item is currently selected by calling either getSelectdItem ( ) or getSelectedIndex ( ) .The following are the methods: String getSelectedItem ( ) Int getSelectedIndex ( )

The getSelectedItem ( )method returns a string containing the name of the item . If no selection is made or if more than one item is selected null is returned. GetSelectedIndex ( ) returns the index of the item. For lists that allow multiple selection you must either use getSelectedItems ( getSelectedIndexes ( ) to determine selections.The following are the methods: String [ ] getSelectedItems ( ) int [ ] getSelectedIndexes ( ) ) or

The first method returns an array containing the names of the currently selected items. The second method returns an array containing the indexes of the currently selected items. To obtain the number of items in the list call countItems ( ) . You can set the currently selected item using the select ( ) method with a zero based integer index. You can get the name associated with the item at that index by calling getItem ( ) . The following are the methods: int countITems ( ) 102 of 149

Java Programming void select (int index) String getItem( int index).

Each time a List is double clicked action ( ) is called.

Text fields & Text Areas


These classes display selectable text and optionally allow the user to edit the text. You can specify the background and foreground colors and font used by text fields and text areas. Both are subclasses of TextComponent .From Text Component they inherit methods that allow them to set and get the current selection, enable and disable editing get the currently selected text and set the text.

The TextComponent superclass of TextArea and TextField supplies the following methods getText ( ) setText ( ) setEditable ( ) selectAll ( ) getSelectedText ( ) isEditable ( ) getSelectionStart ( ) getSelectionEnd ( ) . It also provides a select ( ) method that lets you select between beginning and end positions that you specify. The Textfield class has four constructors: TextField ( ) TextField ( int) TextField(String) TextField(String , int ).

Here int specifies the number of columns in the textfield . The string argument specifies the text initially displayed in the text field. It also has the following methods: int getColumns( ) :returns the number of columns in the textfield. 103 of 149

Java Programming SetEchochar ( ) : sets Echo character which is useful for the password fields. ChargetEchoChar ( ) booleanechoCharIsSet ( ) :both these methods let you ask about the echo character. TextArea also has four constructors : TextArea ( ) TextArea( int , int ) TextArea(String) TextArea( String , int , int ).

Here int specifies the number of rows and columns in the text area and String specifies the text initially displayed in the text area. The TextArea class supplies the following methods : appendText ( ) : appends the required text in the text area. int getRows ( ) : returns the number of rows in the textarea. int getColumns( ) : returns the number of columns in the text area. void insertText ( String ,int ) : Inserts the specified text at the specified position. void replaceText ( String , int , int ) : Replaces the text from the indicated start position to the indicated end position.

Scroll bars
A Scrollbar can act as a slider that the user manipulated to set a value. They help you to display part of a region that is too large for the available display area. They let the user to choose exactly which part of the region is visible. int orientation It indicates whether the scrollbar should be horizontal or vertical. Specified with either Scrollbar.HORIZONTAL or Scrollbar.VERTICAL. int value It is the initial value of the scrollbar. For scrollbars that control a scrollable area this means the x value or y value of the part of the area that is visible when the user first sees the scrollable area. int visible 104 of 149

Java Programming The size in pixels of the visible porion of the scrollable area. This value if set before the scrollbar is visible determines how many pixels a click in the scrollbar. Causes the display area to shift.Setting thism value after the scrolbar is visible has no effect. After the scrollbar is visible you should use the setPageincrement ( ) method to get the same effect. int minimum The minimum value the scrollbar can have. For Scrollbars controlling scrollable areas this value is usually 0. int maximum The maximum value the scrollbar can have. For scrollbars controlling scrollable areas this value is usually : (total width/height ,in pixels of the component that is being partially displayed (currently visible width/height of the scrollable area).

Labels
These controls are the easiest controls. A label is an object of type Label and it contains the string which it displays. They are passive controls that do not support anyinteraction with the user. It defines the following constructors: Label ( ) Label ( String str) Label (String str ,int how) The first form creates an empty label . The second form creates a label that contains the string specified by str. The third form creates a label that contains the string specified by str using the alignment specified by how. ITs value can be Label.LEFT , Label.RIGHT or Label.CENTER. The following are the methods provided by Label: void setText ( String str) : sets or changes the text in a label.(str is the new label). String getText ( ) : gets the current label . void setAlignment ( int how) : sets the alignment of the string within the label . int getAlignment ( ) :gets teh current alignment of the string in the label. (how is the alignment constant as given earlier).

105 of 149

Java Programming

Containers
All the controls that you have studied in the previous sections have to be organized in a window (Container). A container is responsible for laying out any components it contains. The Container calss dedfines three methods for adding components: One argument add( ) Two argument add( ) The first version simply requires that you specify the component to add. The two argument add( ) method lets you add an argument specifying the integer position at which the component should be added. All the layout One argument add( ) Two argument add( ) The first version simply requires that you specify the component to add. The two argument add( ) method lets you add an argument specifying the integer position at which the component should be added. All the layout managers work with these add( ) methods. The first argument of the second version lets you add an argument specifying the integer position at which the component should be added. The second argument of the method specifies the component to be added. Note: You cannot have one component in two containers even if the two containers are never shown at the same time. Adding a component to a container removes the component from the containerit used to be in .

Windows
The Window class creates a top level window. You don't create Window objects directly but you always use a subclass of Window called Frame.

Frames
The Frame class provides windows for applets and applications. Every application needs at least one Frame . If an application has a window that should be dependent on another window - - disappearing when the other window is iconified then yiou should use a Dialog instead of a Frame. The following constructors are used to create a Frame: public Frame ( ) public Frame( String frameTitle) 106 of 149

Java Programming

Besides the no argument Frame constructor implicitly used by the MenuWindow constructor shown above , the Frame class provides a one argument constructor. The argument is a String that specifies the title of the frame's window Other methods provided by Frame: String getTitle( ) & void setTitle ( String) : Returns or sets the title of the frame's window. hide ( ) & show ( ) : Specify whether to make the Frame visible or hide it resize ( ) : Specifies the size of the frame . Image getIconImage ( ) & void setIconImage ( Image) : Returns or sets the image displayed when the window is iconified. MenuBar getMenu ( ) & void setMenuBar ( ) : Returns or sets the bar from this Frame. void remove ( Menu (component) : Removes the specified menu bar from this Frame. boolean is Rizeable ( ) & void setResizeable (boolean) : Returns or sets whether the user can change the window's size. int getCursorType and void setCursor( int) : Gets the current cursor image or sets the cursor image The cursor must be specified as one of the typesdefined in the frame class. The pre-defined types are Frame.DEFAULT _ CURSOR ,Frame.CROSSHAIR_CURSOR , Frame.HAND_CURSOR, Frame.MOVECURSOR,Frame.TEXT_CURSOR, ame.X_RESIZE_CURSOR where X is SW,SE ,NW, NE ,N,S,W or E.
Dialogs

AWT provided support for dialogs which are windows that are dependent on other windows . The Dialog class provides a subclass FileDialog that provides dialogs to help the user open and save files. A dialog is dependent on other windows . When the other window is destroyed all its dependent dialogs are destroyed. Applets don't use dialogs. Dialogs can be modal. Modal dialogs require the user's attention preventing the user from doing anything else in the dialog's appliacation until the dialog has been dismissed. All dialogs are non modal by default which the user can keep up and still work in other windows of the application. You must first have a frame in order to create a dialog The following costructor creates a modal dialog box. public Dialog (Frame Parent Frame, boolean isModal) Dialog myDialog = new Dialog(myFrame ,true); public Dialog (Frame parentFrame ,String title ,boolean isModal ) 107 of 149

Java Programming

The second form creates a modal dialog box whose parent is myFrame , and the third version creates a dialog with a title. The following are the methods provided by dialogs: Dialog (Frame , boolean ) : Creates a dialog box. boolean isModal ( ) : Returns true if the dialog is modal. String getTitle ( ) ,String setTitle( String): Gets or sets the title of the dialog windows. boolean isResizable ( ) ,void setResizable (boolean) :Finds out or sets whether the size ofthe dialog window can change.

Panels
The Panel class is a concrete subclass of Container. It does not add any new methods ; it simply implements Container . A Panel may be thought of a as a recursively nestable, concrete screen component. Panel is the superclass for Applet. When screen output is directed to an applet it is drawn on the surface of a Panel object. In reality a Panel is a window that does not contain a title bar, menu bar or border . That is why you don't se these items when an applet is run inside a browser. When you run an applet using an appletviewer it is the applet viewer that provides the title and border. You can create a new Panel using the following statement : Panel myPanel = new Panel( ) ; You can add this panel to another Container by using the following method: add(myPanel); You can even nest the panels Panel mainPanel ,subPanel1, subPanel 2; subPanel1 = new Panel ( ) ; subPanel2 = new Panel ( ); mainPanel = new Panel ( ); mainPanel.add(subPanel 1); mainPanel.add(subPanel 2); Components can be added to the Panel object by its add ( ) method. Once these components have been added you can position and resize them manually using the move ( ) , resize ( ) or reshape ( ) methods.

Scroll panes
108 of 149

Java Programming A scroll pane container allows you to include scrollabars for the frame so that the user can scroll the contents of the container . This allows you to create very large containers that dont have to be displayed all at once. A common use for a Scrollpane is to display a large image. You can create a canvas that displays the image and then place it in a Scrollpane container to provide automatic scrolling of the image. You can control the scrollpanes use of scrollbars. By default a scroll pane uses scrollbars only if necessary . You can specify that it should always use scrollbars or never use scrollbars. If you use the default constructor the scrollpane uses scrollbars if needed otherwise you can pass either ScrollPane.SCROLLBARS_ALWAYS, ScrollPane.SCROLLBARS_NEVER or ScrollPane.SCROLLBARS_AS_NEEDED. The following are the constructors: public ScrollPane( ) public ScrollPane ( int scrollbarOption) You add Containment hierarchy Object Component

Canvas Scrollbar Container Button Checkbox TextComponent Label Choice Panel Window Dialog
FileDialog

List

TextArea

TextField

Frame

Object

109 of 149

Java Programming

MenuComponent
MenuItem MenuBar

Menu

CheckBoxComponent

As the figures show, all components except for menu related components inherit from the AWT Component class .Because of cross platform restrictions menu related components are not full blown Components .Instead menu components inherit from the AWT MenuComponent class. Drawing -graphics object When a Java program with a GUI needs to draw itself whether for the first time or in response to becoming unhidden or because its appearance needs to change to reflect something happening inside the program it starts with the highest component that needs to be redrawn (top Component in the hierarchy) and works its way down to the bottom most Components. The following figure is the component hierarchy for the converter program.

Frame Converter Conversion Panel (metric Panel) Label TextField Choice Scrollbar Conversion Panel(use Panel ) Label TextField Choice Scrollbar

All graphics are drawn relative to a window.This can be the main window of an applet a child window of an applet or a stand alone application window. The origin of each window is at the top left corner and is 0,0. Coordinats are specified in pixels. All output takes place through a graphics context which is encapsulated by the Graphics class and is obtained in two ways. IT is passed to an applet when one of its various methods such as paint( ) or update( ) is called. It is returned by the getGraphics( ) method. The Graphics class defines a number of drawing functions Each shape can be drawn edge only or filled. Objects are drawn and filled in the currently selected graphics color which is black by default.

110 of 149

Java Programming Event handling


Events are objects that describe what happened .The generator of these events are Event sources wheras the methods that receive event objects, decipher them and processes the user's interaction are called Event Handlers . When the user performs an action at the user interface level ,this causes an event to be issued. There are different classes that describe different categories of user action. A mouse click on a Button component generates an ActionEvent with the button as source. The ActionEvent instance is an object that contains the information about the events that just took place. It contains:

action.

getActionCommand ( )

- Returns the command name associated with the

getModifiers ( ) - Returns any modifiers held during the action.

ActionEvent : generated by activation of components AdjustmentEvent : generatd by adjustment of adjustable components such as scrollbars. ContainerEvent: generated when componetns are added to or removed from a container. FocusEvent : generated when a component receives input focus. ItemEvent : generated when an item is selected from a list, choice or checkbox. KeyEvent : generated by a keyboard activity. MouseEvent : generated by mouse activity. TextEvent: generated when a text component is modified. WindowEvent: generated by window activity ( such as iconifying or de-iconifying ) There are two ways to handle the event mentioned above. The first way is to delegate event handling to a listener object and the second way is to explicitly enable the originating component to handle its own events.

Event Listeners
An Event Listener is an object to which a component has delegated the task of handling a particular kind of event. When the component experiences input , an event of the appropriate type is constructed ,the event is then passed as a parameter to a method call on the listener which must implement the interface that contains the event handling method. Table 1 shows the various interfaces Writing event handlers You can even create events of your own. Let us consider an example of an action Event: Consider a button in an applet .When the button is clicked an action event is to be sent to an instance of class MyActionListener. The code for an ActionListener is :

111 of 149

Java Programming

class MyActionListener implements ActionListener { public void actionPerformed ( ActionEvent ae) { System.out.println( "ActionPerformed "); } } The class implements the ActionListener interface thus guaranteeing the presence of an actionPerformed( ) method. The applet code is as follows: public class ListenerTest extends Applet { public void init ( ) { Button b = new Button ( "OK"); MyActionListener listener = new MyActionListener ( ); b.addActionListener (listener); add(b); } } You are creating an instance of MyActionListner which is set as one of the button's action listeners. The code for giving an ActionListener to a component is according to a formula that is given below : Create a listener class that implements the corresponding Listener interface Construct the component Construct an instance of the listener class. Call the respective add ( ) method on the component passing in the listener object. How to use adapters An adapter is simply a class that defines an interfce by providing do- nothing methods. From the table you you see that most of the interfaces have only a single method while others have several methods. The larget interface Window Listener has 7 methods. Consider a case when you want tocatch iconified evetns on Frame .You can create the following class class MyIc_Listener implements WindowListener { public void windowIconified( WindowEvent we) { // Process the event. } }

112 of 149

Java Programming

This class may not compile. The WindowListener interface defines 7 methods and class MyIc_Listener needs to implement the other six before the compiler will be satisfied . Typing in the remaining methods and giving them empty bodies is tedious. The java.awt.event package provided seven adapter classes one for each listener interface by providing do nothing methods. You can modify the above code with a do nothing method of the WindowAdapter class as follows : class MyIc_Listener extends WindowAdapter { public void windowIconified(WindowEvent we) { //Process the event. } } Table 3 has the list of all adapter classes along with their evetn listener interfaces :

113 of 149

Java Programming

Component At the top of the AWT hierarchy is the Component class. Component is an abstract class that encapsulates all of the attributes of a visual component. All user interface elements that are displayed on the screen and that interact with the user are subclasses of Component. It defines over a hundred public methods that are responsible for managing events, such as mouse and keyboard input, positioning and sizing the window, and repainting. Container The Container class is a subclass of Component. It has additional methods that allow other Component objects to be nested within it. Other Container objects can be stored inside of a container. A Container is responsible for laying out any components that it contains. It does it through the use of various layout managers. Component Container Panel MenuContainer Interface Window Frame The class Hierarchy for Panel and Frame

Panel The Panel class is a concrete subclass of Container. It doesnt add any new methods; it simply implements Container. A Panel may be thought of as a recursively nestable, concrete screen component. Panel is the superclass for Applet. 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, a menu bar, or border. Other components can be added to a Panel object by its add () method (inherited from Container). Once these components have been added, you can position and resize them manually using the setLocation (), setSize (), or setBounds () methods defined by Component. import java.awt.*; import java.applet.*; public class panelexample extends Applet {

114 of 149

Java Programming
Panel main,p1,p2,p3; Button b1,b2,b3,b4,b5,b6; TextField t1,t2,t3; public void init() { b1=new Button(" button 1"); b2=new Button(" button 2"); b3=new Button(" button 3"); b4=new Button(" button 4"); b5=new Button(" button 5"); b6=new Button(" button 6"); main=new Panel(); p1=new Panel(); p2=new Panel(); p3=new Panel(); t1=new TextField("Panel 1"); t2=new TextField("Panel 2"); t3=new TextField("Panel 3"); p1.add(t1); p1.add(b1); p1.add(b2); main.add(p1); p2.add(t2); p2.add(b3); p2.add(b4); main.add(p2); p3.add(t3); p3.add(b5); p3.add(b6); main.add(p3); main.setLayout(new GridLayout(3,1)); add(main); } }

115 of 149

Java Programming

Window
The Window class creates a top-level window. A top-level window is not contained within any other object, it sits directly on the desktop. Generally, you wont create Window objects directly. Instead, you will use a subclass of Window called Frame, described next.

Frame
Frame encapsulates what is commonly thought of as a Window. It is a subclass of Window and has a titlebar, menu bar, borders, and resizing corners, If you create a Frame object from within an applet, it will contain in warning message, such as Warning Applet Window, to the user that an applet window has been created. This message warns users that the window they see was started by an applet and not by software running on their computer. (An applet that could masquerade as a host -based application could be used to obtain passwords and other sensitive information without the users knowledge.) When a Frame window is created by a program rather than an applet, a normal window is created. Frame Class Frame java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--java.awt.Window | +--java.awt.Frame public class Frame extends Window implements MenuContainer A Frame is a top-level window with a title and a border. It is an independent window, decorated by the underlying window system and capable of being moved around the screen independent of other GUI windows. Any application that requires a GUI must use one or more frames to contain the desired components. The size of the frame includes any area designated for the border. The dimensions of the border area can be obtained using the getInsets method, however, since these dimensions are platformdependent, a valid insets value cannot be obtained until the frame is made displayable by either calling pack or show. The default layout for a frame is BorderLayout. Constructors There are only two forms of the Frame constructor: public Frame() : Constructs a new instance of Frame that is initially invisible. The title of the Frame is empty. public Frame(String title) : Constructs a new, initially invisible Frame object with the specified title.

116 of 149

Java Programming
Example: import java.awt.*; public class fram extends Frame { public fram(String str) { super(str); } public static void main(String str[]) { fram fr=new fram("My frame"); fr.setBounds(10,10,500,350); fr.setVisible(true); fr.setBackground(Color.cyan); } }

Working with Frame Windows


After the applet, the type of window you will most often create is derived from Frame . you will use it to create child windows within applets, and top-level or child windows for applications. As mentioned, it creates a standard -style window.

Setting the Windows Dimensions


The setSize() method is used to set the dimensions of the window. Its signature is shown here: void setSize(int new Width, int newHeight) void setSize(Dimensions newSize) The new size of the window is specified by newWidth and NewHeight, or by the width and height fields of the Dimension object passed in newSize . the dimensions are specified in terms of pixels. After a frame window has been created , it will not be visible until you call setVisible(). Its signature is shown here: void setVisible(boolean visibleFlag) The component is visible if the argument to this method is true. Otherwise, it is hidden. You can change the title in a frame window using setTitle(), which has this general form. void setTitle(String newTitle) here , newTitle is the new title for the window.

Closing a Frame window


117 of 149

Java Programming
When using a frame window, your program must remove that window from the screen when it is closed, by calling setVisible(false). To intercept a window close event, you must implement the windowClosing() method of the Window Listener interface. Inside windowClosing(), you must remove the window from the screen . The example in the next section illustrates this technique. A Dialog is a top-level window with a title and a border that is typically used to take some form of input from the user. The size of the dialog includes any area designated for the border. The dimensions of the border area can be obtained using the getInsets method, however, since these dimensions are platform-dependent, a valid insets value cannot be obtained until the dialog is made displayable by either calling pack or show. A Dialog is usually not made visible to the user when it is first created. A dialog must have either a frame or another dialog defined as its owner when it's constructed. Constructor
Dialog(Dialog owner)

Parameters:
owner

- the owner of the dialog

public Dialog(Dialog owner,String title) Parameters: owner - the owner of the dialog title - the title of the dialog. public Dialog(Dialog owner,String title,boolean modal) Parameters: owner - the owner of the dialog title - the title of the dialog. modal - if true, dialog blocks input to other app windows when shown

Layouts
A layout manager automatically arranges controls within a window by using some type of algorithm. All of the components have been positioned by the default layout manager. Each container object has a layout manager associated with it. A layout manager is an instance of any class that implements the Layout Manager interface. The layout manager is set by the setlayout() method. If no call to setLayout() is made ,then the default layout manager is used.Whenever a container is resized(or sized for the first time),the layout manager is used to position each of the components within it.] Each layout manager keeps track of a list of components that can be stored by their names. The layout manager is notified each time you add a component to a container. Java has several predefined Layout Manager classes .You can use the layout manager that best fits your application . 118 of 149

Java Programming

How to use Flow layout Flow Layout is the default layout manager. Flow Layout implements a simple layout style, which is similar to how the words flow in a text editor. Components are laid out from the upper-left corner, left to right and top to bottom. When no more components fit on a line, the next one appears on the next line . A small space is left between each component ,above and below,as well as left and right . Here are the constructors for Flow Layout : Flow Layout() Flow Layout (int how) Flow Layout(int how, int horz, int vert) The first form creates the default layout, which centers components and leaves 5 pixels of space between each component .The second form lets you specify how each line is aligned. Valid values for how are as follows: Flow Layout.LEFT, Flow Layout.CENTER , Flow Layout.RIGHT These values specify left, center, and right alignment, respectively.The third form allows you to specify the horizontal and vertical space left between components in horz and vert ,respectively. Border layout The Border Layout 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. Each of these regions is referred to by name. North, South, East, and West represent the four sides ,and Center is the middle area. Here are the constructors defined by BorderLayout: Border Layout() Border Layout(int how ,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 . When adding components ,you will use the names of the regions using the folllowing form of add(): Component add(String name,Component compObj); Here, name is the name of the area in which you want the component specified by compObj added.A reference to the component being added is returned. 119 of 149

Java Programming

Grid layout Grid Layout 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 Grid Layout are shown here: Grid Layout(int numRows, int numColumns) Grid Layout(int numRows, int numColumns, int horz,int vert) The first form creates a grid layout with the specified number of rows and columns.The second form allows you to specify the horizontal and vertical space left between components in horz and vert ,respectively.Either numRows or numColumns can be zero. Specifying numRows as zero allows for unlimited-length columns. Specifying numColumns as zero allows for unlimited length rows.

Card layout
The Card Layout class is unique among the other layout managers in that it stores several different layouts managers in that it stores several different layouts. Each layout can be thought of as being on a separate index card in a deck that can be shuffled so that any card is on top at a given time. This can be useful for user interfaces that have optional components which can be dynamically enabled and disabled upon user input. You can prepare the other layout and have them hidden, ready to be activated when needed. CardLayout provides these two constructors: CardLayout() CardLayout(int horz, int vert) The first form creates a default card layout. The second form allows you to specify the horizontal and vertical space left between components in horz and vert,respectively. Use of a card layout requires a bit more work than the other layouts.The cards are typically held in an object of type Panel.This panel must have CardLayout selected as its layout manager.The cards that form the deck are also typically objects of type Panel.Thus you can create a panel that contains the deck ,and a panel for each card in the deck.Next,youadd these panels to the panel for which CardLayout is the that contains the deck ,and a panel for each card in the deck. Next, you add these panels to the panel for which CardLayout is the layout manager. Finally, you add this panel to the main applet panel. Once these steps are complete you must provide some way for the user to select between cards. One common approach is to include one push button for each card in the deck. When card panels are added to a panel, they are usually given a name.Thus, most of the time ,You will use this form of add() when adding cards to a panel: 120 of 149

Java Programming

Component add(string name,Component panelObj); Here,name is the name of the card whose panel is specified by panelObj. A reference To the component being added is returned .The advantage to naming each card is that you can bring a card to the surface by specifying its name. After you have created a deck ,your program activates a card by calling one of the following methods defined by CardLayout: void first(Container deck) void last(Container deck) void next(Container deck) void Previous(Container deck) void show(Container deck) Here, deck is a reference to the container (usually a panel)that holds the cards,and cardName is the name of a card.Calling first() causes the first card in the deck to be shown.To show the last card,call last() .To show, the next card,call next(). To show the previous card, call previous ().Both next() and previous() automatically cycle back to the top or bottom of the deck,Respectively.The show() method displays the card whose name is passed in cardName.

import java.awt.*; import java.applet.*; import java.awt.event.*; public class CardLay extends Applet implements ActionListener { CardLayout cl; public void init() { cl=new CardLayout(); setLayout(cl); Button b1=new Button("1"); Button b2=new Button("2"); Button b3=new Button("3"); add("First",b1); add("Second",b2); add("Third",b3); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); } public void actionPerformed(ActionEvent ae) 121 of 149

Java Programming { cl.next(this); } } Grid bag layout Grid Bag Layout is the most flexible and complexlayout manager the AWT provides. As the above applet shows a GridBagLayout places components in a grid of rows and columns,allowing specified components to span multiple rows and columns . Not all rows necessarily have the same height. Similarly, not all columns necessarily have the same width. Essentially,GridBagLayout places components in a squares (cells) in agrid ,and then uses the components preferred sizes to detemine how big the cells should be. If you enlarge the window the applet brings up, youll notice that the last row gets all the new vertical space , and that the new horizontal space is split evenly among all the columns.This resizing behavior is based on weights the applet assigns to individual components in the GridBagLayout. Youll also notice that each component takes up as much as space it can. This behavior is also specified by the applet. The way the applet specifies the size and position characteristics of its components is by specifying constraints for each component. To specify constraints,you set instance variables in a GridBagConstraints object and tell the GridBagLayout(with the setConstraints() method ) to associate the constraints with the component.

The graphics object


You need a Graphics object in order to use any of the Java's rendering methods. When the Graphics object is drawn that exceeds the dimensions of the window output is automatically clipped. The graphics context is an instance of the Graphics class. It knows how to render onto a single target. A graphics context can render onto the three media: Components Images Printers The Graphics class defines a number of drawing functions Each shape can be drawn edge only or filled. Objects are drawn and filled in the currently selected graphics color which is black by default. 122 of 149

Java Programming

The four major operations provided by the GRaphics class are Selecting a color Selecting a font. Drawing and filling Clipping.

The coordinate system All the methods of the Graphics class specify pixel coordiante positions for the shapes they render.Every component has its own coordinate space with the origin in the component's upperleft corner , x increasing to the right and y increasing downward .The foll figure shows the component coordinate system. (0,0) X Y

Drawing and Filling Graphics contexts do not have an extensive repertoire of painting methods. The following are the methods: drawLine ( ) drawRect ( ) & fillRect ( ) drawOval ( ) & fillOval ( ) drawArc ( ) & fillArc ( ) drawPolygon ( ) & fillPolygon ( ) drawPolyline ( ) drawString ( )

Using images

123 of 149

Java Programming Every image is represented by a java.awt.Image object. In addition tot eh Image class the java.awt.package provides other basic image suuport such as the Graphics drawImage( ) methods , the Toolkit getImage( ) methods and the Media Tracker class . The java.awt.image package provides interfaces and classes that let you crete ,manipulate and observe images.

124 of 149

Java Programming

Creating Images The Component class in java.awt has a factory method called createImage ( ) that is used to create Image objects. The createImage( ) method has the folowing two forms: Image createImage( ImageProducer imgProd) Image createImage (int width ,int height) The first version returns an image object producede by imgProdwhich is an object of aclass that implements the ImageProducer interface. Ex: Canvas c = new Canvas; Image test = c.createImage(100,100); This example creates an instance of Canvas and then calls the createImage ( ) method to amke an Image object The image is blank at this stage. Loading images The AWT makes it to easy to load images in either GIF or JPEG format. The Applet and Toolkit classes provide getIamge( ) methods that work for either format. The getImage ( ) methods returns immediately so that you don't have to wait for an image to be loaded before going on to perform other operations in your program. The corresponding methods are : myImage = getImage( URL ); or myImage = Toolkit.getDefaultToolkit ( ).getImage(filename or URL); You can track image loading status either by using the Mediatracker class or by implementing the imageUpdate ( ) method which is defined by the ImageObserver interface . Loading images using the getImage( ) methods: The Applet class supplies two getImage ( ) methods: public Image getImage( URL url) public Image getImage (URL url ,String name) Only applets can use these methods . These methods don't work if called in a constructor or in a statement that declares an instance variable. You should call these methods from a method called init( ). 125 of 149

Java Programming

The following methods show you how to use the Applet geImage ( ) methods. Image image 1 = getImage ( getCodeBase ( )."imageFile.gif"); Image image 2 = getImage (getDocumentBAse ( ) ,"anImageFiel.jpeg"); Image image 3 = getImage (newURL (http://java.sun.com/graphics/people.jpeg ) ) Displaying Images It is easy to display an image using the GRaphics object that is passed into your update ( ) or paint ( ) method. You simply invoke the drawImage ( ) method on the Graphics object. The corresponding method is : g.drawImage ( myImage , 0 , 0 ,this ); The Graphics class declares the folowing drawImage( ) methods .They all return a boolean value although this value is not used. The return value is true if the iamge has been completely loaded and completely drawn else it is false. public abstract boolean drawImage(Image img ,int x, int y, ImageObserver observer) public abstract boolean drawImage(Image img ,int x, int y, int height ,int width, ImageObserver observer) public abstract boolean drawImage(Image img ,int x, int y, Color bgcolor, ImageObserver observer) public abstract boolean drawImage(Image img ,int x, int y, int height, int width, Color bgcolor ImageObserver observer) Displaying short status strings in an object To display strings in an object you can use the drawString( ) method which is a member of the Graphics class. Itis called from within either update( ) or paint ( ) . It has the folowing form: public void drawString( String message ,int x, int y) Here message is the string that is to be displayed beginning at the x,y coordinates. This method does not recognise new line characters. IF you want to start a line of text on a new line ,you must do it manually specifying the precise x ,y location where you want the line to begin.

126 of 149

Java Programming

Overview of I/O streams


A stream is an abstraction that either produces or consumes information. A stream is linked to a physical device by the Java I/O system. All streams behave in the same manner, even if the actual physical devices they are linked to differ. Thus, the same I/O classes and methods can be applied to any type of device. This means that an input stream can abstract many different kinds of input: from a disk file,a keyboard, or a network socket. Likewise , an output stream may refer to the console ,a disk file ,a network connection .Streams are a clean way to deal with input/output without having every part of your code understand the difference between a keyboard and a network,for example. The I/O classes defined by java.io are listed here: InputStream OutputStream BufferedInputStream BufferedOutputStream ByteArrayInputStream ByteArrayOutputStream DataInputStream DataOutputStream FileInputStream FileOutputStream FilterInputStream FilterOutputStream LineNumberInputStream PipedInputStream PipedOutputStream PrintStream PushbackInputStream SequenceInputStream StringBufferInputStream File FileDescriptor RandomAccessFile Stream Tokenizer

At the top of the hierarchy are two abstract classes:InputStream and OutputStream. All the other stream classes extend these two classes. Only File, FileDescriptor, Random Access File, and Stream Tokenizer are not derived from InputStream or OutputStream. Characters stream One of the differences between Java and languages such as C is that Java treats characters as 16-bit values rather than 8-bit values. Unfortunately, under Java 1.0 ,there was no 16-bit version of the byte array streams. This encouraged programmers to treat characters as 8-bit values if they wanted to use the byte array streams. Fortunately, with java1.1 changes were made to include character array streams, but they are not called streams. Java 1.1 introduced a new type of stream called a Reader or a Writer ,depending on whether it is an input stream or an output stream .The character version of the ByteArrayInputStream is called a CharArrayReader, while the CharArrayWriter performs functions similar to the ByteArrayOutputStream. The CharArrayReader and CharArrayWriter classes function almost identically to their byte array counterparts. They contain the same methods,only the char array counterparts.They contain the same methods ,only the char array streams use char values everywhere the byte array streams use byte values.The constructors for CharArrayReader and CharArrayWriter look like this, for example : 127 of 149

Java Programming public CharArrayReader(char []buf) public CharArrayReader(char[] buf, int offset,int length) public CharArrayWriter() public CharArrayWriter(int size)
Byte streams

You dont always have to write to a file or the network to use streams.You can write to and read from arrays of bytes using the ByteArrayInputStream and ByteArrayOutputStream classes. These streams are not filter streams like some of the others; they are input and output streams. When you create a ByteArrayInputStream, you must supply an array of bytes that will serve as the source of the bytes to be read from the stream. public ByteArrayInputStream(byte[] bytes) creates a byte input stream using the entire contents of bytes as the data in the stream. public ByteArrayInputStream(byte[] bytes, int offset, int length) creates a byte input stream that reads up to length bytes starting at position offset. A ByteArrayOutputStream is an array of bytes that continually grows to fit the data stored in it. The Constructor for the ByteArrayOutputStream class takes an optional initial size parameter that determines the initial size parameter that determines the intial size of the array that stores the bytes written to the stream. public ByteArrayOutputStream

Understanding I/O super classes

Javas stream based I/O is built upon two abstract classes InputStream and OutputStream. They are used to create several concrete stream subclasses. Although it is through the concrete subclasses that your programs perform I/O
InputStream :

InputStream is an abstract class that defines Javas model of streaming input .All of the Methods in this class willthrow an IOException on errror conditions.Table 1 shows a brief synopsis of the methods in InputStream. Method 128 of 149 Description

Java Programming int read() int read(byte buffer[]) int read(byte buffer[], numBytes) int skip(long numBytes) int available() void close() Output Stream : As with Input Stream, Output Stream is an abstract class that definesstreaming output .All of the methods in this class return a void value and throw an IOException in the case of errors.Table-2 shows a list of each of the methods in OutputStream. Returns an integer representation of the next available byte of input. Attempts to read up to buffer.length bytes into buffer and returns the actual number of bytes that were successfully read int offset, int Attempts to read up to numBytes bytes of input, returning the number of bytes successfully Skips over numBytes of input, returning the number of bytes actually skipped Returns the number of bytes of input currently available for reading Closes the input source. Further read attempts will generate an IOException

Note: Most of the methods described in Table-1 and Table-2 are implemented by the subclasses of InputStream and OutputStream. mark() and reset() are exceptions .

Method Description void write(int b) rites a single byte to an output W stream . Note that the parameter is an int , which allows you to call write with expressions without having to cast them to byte void write(byte buffer[]) Writes a complete array of bytes to an output stream

void write(byte buffer, int offset, int Writes a subrange of numBytes, bytes numBytes) from the arrya buffer, beginning at buffer[offset]. void flush() Finalizes the output state so that any buffers are cleared. void close() Closes the output stream

129 of 149

Java Programming

Object serialization

Up to this point you have been working with objects, and you have learned to create classes so you can manipulate the objects using their methods. However, when you have had to write an object to a different source, say out to a network via a socket or to file, you have only written out native types like int or char. Object Serialization is the tool that was added to java to allow you to fully utilize the OOP nature of java and write those objects youve labored to produce to a file or other stream. Saving an object to some type of permanent storage is called persistence. An object is said to be persistent capable when you can store that object on a disk or tape or send it to another machine to be stored in memory or on disk. The java.io.Serializable interface has no methods and only serves as a marker that indicates that the class that implements the interface can be considered for serialization. Objects from classes that do not implement Serializable cannot save or restore their state.

Threading
In this session, you will learn what threads are, the need for them and write programs to implement the concept of Multithreading. This section introduces you to threads.
What is a thread?

A thread can be defined as a single sequential flow of control. Threads are also known as execution contexts or lightweight processes. A program is a normally broken into smaller chunk (separate tiny program called tasks) and tasks are further broken into still similar chunks called threads. In computer terminology, more than one thread executing at any point in time is called multithreading. The main advantage of multithreading is the speed of execution of the program.

Threads
Thread encapsulates a thread of execution. Since you cant directly refer to the ethereal state of a running thread, you will deal with it through its proxy, the Thread instance that spawned it. To create a new thread, your program will: Extend Thread (sub classing thread). Implement the Runnable interface. 130 of 149

Java Programming

The Thread class defines several methods that help manage threads.
Method Meaning

getName getPriority isAlive join run sleep start


Creating a Thread

Obtain a threads name Obtain a threads priority. Determine if a thread is still running. Wait for a thread to terminate. Entry point for the thread. Suspend a thread for a period of time Start a thread by calling its run method.

In the most general sense, you create a thread by instantiating an object of type Thread. Java defines two ways in which this can be accomplished: You can implement the Runnable interface or you can extend the Thread class, itself. This has been discussed earlier. Now let us see the advantages of both the ways. Advantages of Implementing Runnable: From an object-oriented design point of view, the thread class is strictly an encapsulation of a virtual CPU, and as such, it should be extended only when you are changing or extending the behavior of that CPU model. Because of this, and the value of making the distinction between the CPU, code and data parts of a running thread, this course module has used this approach. Because Java technology allows only single inheritance, you cannot extend any other class, such as Applet, if you have already extended Thread. In some situations, this forces you to take the approach of implementing Runnable. Because there are times when you are obliged to implement Runnable, you might prefer to be consistent and always do it this way.

Advantages of extending Thread

The advantage of extending Thread: 131 of 149

Java Programming

When a run () method is embodied in a class that extends the Thread class, this refers to the actual Thread instance that is controlling execution . Therefore, the code no longer needs to use longhand controls, such as the following: Thread.currentThread().sleep(100); Can simply say: sleep(100); Because the resulting code is slightly simpler, many programmers of the Java programming language use the mechanism of extending threads. Implementing the Runnable interface The easiest way to create a thread is to create a class that implements the Runnable interface. Runnable abstracts a unit of executable code. You can construct a thread on any object that implements Runnable. To implement Runnable, a class need only implement a single method called run(), which is declared like this : public void run( ) Inside run (), you will define the code that constitutes the new thread. It is important to understand that run () can call other methods, use other classes, and declare variables just like the main thread. The only difference is that run () establishes the entry point for another, concurrent thread of execution within your program. This thread will end when run() returns. After you have created a class that implements Runnable, you 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) In this constructor, threadOb is an instance of a class that implements the Runnable interface. This defines where execution of the thread will begin. The name of the new thread is specified by threadName. Once created, the new thread will not start running until you call its start () method, which is declared within Thread. In essence, start() executes a call to run( ). The start () method is shown here: void start( ) For now, dont worry about the synchronized modifier. 132 of 149

Java Programming

Overview of networking

Networking basics
Computers running on the Internet communicate to each other using TCP and UDP protocols which are both 4 layer protocols:

Application (HTTP, ftp ,telnet ,) Transport ( TCP /IP , UDP, .) Network ( IP ,..) Link ( device, driver.. )

When you are programming over the network you are programming at the application layer. You can use the classes in the java.net.package instead of the TCP and UDP layers. These classes provide system independent network communication. When two applications want to communicate to each other reliably they establish a connection and send data over that connection .TCP guarantees that data sent from one end of the connection actually gets to the other end in the same order it was sent.

TCP/IP
A TCP is a connection based protocol that provides a reliable flow of data. It establishes a communication link between a source port IP address and a destination port IP address. Applications that require a reliable point to point channel to communicate use TCP to communicate. HTTP ( Hypertext Transfer Protocol ), FTP (File Transfer Protocol) and Telnet are examples of applications that require a reliable communication channel. The order that the data is sent and received over the network is critical to the success of these applications when using HTTP to read from a URL the data must be received in the order that it was sent otherwise you end up with a jumbledd HTML file ,corrupt zip file or some other invalid information.

UDP
The UDP protocol provides for non guaranteed communication between two applications on the network. UDP is a connectionless protocol and it does not establish a link for the duration of the connection . It sends packets of data called datagrams from one 133 of 149

Java Programming application to another .Sending datagrams is like sending a letter through the mail service , the order of delivery is not guaranteed and each message is independent of any others. When using UDP an application program writes the destination port and IP address on the datagram and then sends the datagram to the destination .

Understanding ports
A computer generally has a single physical connection to the network. All data destined for a particular computer arrives through that connection . Sometimes the data may be intended for different applications running on the computer . Through the use of ports the computer knows which application to forward data to. Data transmitted over the Net is accompanied by addressing information that identifies the computer and the port that it is destined for. Each computer is identified by its 32 bit number which TCP and UDP use to deliver the data to the right application. In connection based communication an application establishes a connection with another application by binding a socket to a port number. This has the effect of registering the application with the system to receive all data destined for that port . No two applications can bind to the same port. In a datagram based communication the datagram packet contains the port number of the destination . app app app app

port

port2 2

port3

port4

TCP/IP or UDP

Packet port #
Data

Port numbers range from 0 to 65535 ( because ports are represented by 16 bit numbers ). The port numbers ranging from 0 to 1023 are restricted they are reserved for 134 of 149

Java Programming user by well known services such as http and ftp and other system services. The applications should not attempt to bind to these ports .Ports reserved for well known services (HTTP and ftp) are called well known ports.

135 of 149

Java Programming

app http telnet

echo

TCP/IP or UDP 80 21 23 Packet 7 Data Through the classes in java.net , Java programs can use TCP or UDP to communicate over the Net. The URL , URL Connection ,Socket and SocketServer classes all use TCP to communicate over the network. The DatagramPacket and DatagramServer classes use UDP. Working with URL' s URL stands for Uniform Resource Locator and is a reference ( an address)to a resource on the Net. They are the doorway to the Internet and the WWW. You provide URL s to your favorite Web browser so that it can locate files on the Internet in the sameway as you provide addresses on the letters so that the post office can locate your correspondence. The java programs you write that interact with the Internet may also use URLs to find the resources on the Internet they wish to access. The java.net.package contains a class called URL that your Java programs can use to represent a URL address . What is a URL? A URL takes the form of a string that describes how to find a resource on the Internet. URLs have two main components : the protocol needed to access the resources and the location of the resource. If you have been surfing the net , you might already be familiar with URLs . These URLs can point to other resources on the network such as database queries and command output. The following example is a URL: http:/java.sun.com/ This URL addresses the Web site hosted by Sun Microsystems. The URL shown above has two main components separated by a colon(:) 136 of 149 7

Java Programming

the protocol identifier the resource name In the example http is the protocol identifier and //java.sun.com/ is the resource name. The protocol identifier indicates the name of the protocol to be used to fetch the resource . The example uses the HTTP which is typically used to serve hypertypes documents. HTTP is just many different protocols used to access different types of resources on the net. The resource name is the complete address to the resource . The format of the resource name depends entirely on the protocol used. The resource name contains one or more of the following components: host name : the name of the machine the resource lives on. filename: the pathname to the file on the machine . port number : the port number to connect to.( typically optional). reference : a reference to a named within a resource ; usually identifies a specific location within a file.(optional). When constructing a URL put the protocol identifier first followed by a colon (:) ,followed by the resource name as follows: protocol ID : resource Name The java.net package contains a class named URL that Java programs use to represent a URL address. A java program can construct a URL object open a connection to it,and read to or write from it. Creation of URL using constructors. Java URL class has four constructors and each can throw a Malformed URLException . The following are the constructors: URL(String urlSpecifier) URL (String protocolName, String hostName ,int port ,String path) URL (Stirng protocolName ,String hostName ,String path) URL(URL urlObj ,String urlSpecifier )

The first URL version specifies a string that is identical to what you see in a browser. The second and third forms of the constructor allow you to break up the URL into its component parts. The fourth version allows you to use an existing URL as a reference context and then create a new URL from that context. The following example creates a URL : 137 of 149

Java Programming import java.net.*; class URL_ex { public static void main(String args[ ] ) throws MalformedURLException { URL ue = new URL( http:// www.java.sun.com/products/index/); System.out.println(Protocol : + ue.getProtocol( ) ) ; System.out.println(Port : + ue.getPort( ) ) ; System.out.println(Host : +ue.getHost( )); System.out.println(File : + ue.getFile ( ) ) ; System.out.println(Exit : + ue.getExit( ) ) ; System.out.println(Ext : + ue.toExternalForm ( ) ) ; } The output of the program is as follows :
Protocol : http Port : -1 Host : www.java.sun.com File : /products/index/ Ext: http: // www.java.sun.com /products/index/

The Port number is 1; this means that you need to retrieve the data associated with that URL for that particular port. To access the actual bits or content information of a Url you should create a URL connection object by using the openComponent( ) method as follows: url.openConnection ( ) The openConnection has the following general form: URLConnection openConnection ( ) which returns a URL Connection object associated with the invoking URL object and may throw an IO exception.

138 of 149

Java Programming What is a socket? A socket is one end point of a two way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and server program. The java.net package provides two classes Socket and ServerSocket that implement the client side of the connection and the server side of the connection. respectively.

Java database connectivity


The JDBC API JDBC API stands for Java Database Connectivity Application Programming Interface. As its name implies, the JDBC API is a set of specifications that defines how a program written in Java can communicate and interact with a database. It defines how the communication is to be carried out and how the application and the database interact with each other. More specifically, the JDBC API defines how an application opens a connection ,communicates with a database,executes SQL statements, and retrieves query results. JDBC provides a vehicle for the exchange of SQL between Java applications and databases. Design of JDBC JDBC API is a completely fresh and new idea, designed entirely by the Javasoft. Like many other aspects of the programming language, much of the JDBC API concepts are borrowed from the other sources, in particular, Microsofts Open Database Connectivety (ODBC). Both ODBC and JDBC are based on the X/OPEN call level interface for SQL. Since ODBC is well established and one of the most widely accepted database interface currently available ,it only makes sense to use it as a starting point. While JDBC is certainly not a derivative of ODBC, they both share the same parent and can be thought of as siblings. JDBC was designed to be very compact, simple interface focusing on the execution of raw SQL statements and retrieving the results.

139 of 149

Java Programming

Client Application GUI


Database Server JDBC API

Network Interface SQL Results SQL Request SQL Results Figure 1 :Data Flow Model SQL Request

JDBC drivers available Currently, all drivers fit into four distinct categories. Each type has specific properties that make it more or less useful for a particular environment purpose. It will be up to you to decide which environment is best for your application.
Type I: JDBC-ODBC bridge

The JDBC-ODBC bridge driver is the only driver currently supplied by JavaSoft. The reason for this is simple. The ODBC bridge is the only driver that can be used with multiple databases and is vendor independent. ODBC like JDBC, defines an interface. The ODBC interface remains constant no matter which database is used. This means that this type of JDBC driver only needs to speak one language: ODBC. Once JDBC passes the request off to the ODBC driver, it is responsibility of the ODBC driver to communicate with the database. The JDBC driver ,therefore, has no knowledge of the actual database it is communicating with. One drawback of the JDBC-ODBC bridge driver is that it adds another layer of complexity to our program and can make software bugs more difficult to isolate .The obvious benefit to this is that any database that has an ODBC driver can be used with Java,even if a native JDBC driver does not exist. Figure 2 shows how the JDBC-ODBC bridge is implemented. 140 of 149

Java Programming

Application

JDBC Driver

ODBC Driver

Database Figure 2:JDBC-ODBC Bridge As you can see from the diagram, the java application submits an SQL statement through the JDBC driver. The JDBC driver translates the request to an ODBC call. The ODBC driver then converts the request again and presents it to the database interface. The results of the request are fed back through the same channels but in reverse. The JDBC-ODBC bridge ends up making two translations for each request and for each result returned. Type II: Native API-Partly Java drivers
The Native API-Partly Java driver makes use of local native libraries to communicate with the database. The driver does this by making calls to the locally installed native(vendor specific)call level interface (CLI).The CLI libraries are typically written in C but can be in any one of many programming languages. The CLI libraries are responsible for the actual communications with the database server. When a client application makes a request ,the driver translates the JDBC request to the native method call and passes the request to the native method call and passes the request to the native CLI. After the database services the request, results are then translated from their native format back to JDBC and presented to the client application.

Application

141 of 149

Java Programming

JDBC Driver Native Database Libraries(Call Level Interface Network Interface Proprietary Database Protocol

Local Disk )

Network Network Interface

Database Server

Type III: JDBC-Net All-Java driver

Although Type III JDBC-Net-All Java drivers sound different from the previous two, they actually offer little that is new. The only difference between Type I, Type II, and Type III drivers is the placement of the native database access libraries. With Type I drivers, it was necessary to have the ODBC driver loaded locally on the client. Similarly, with Type II drivers, all native CLI libraries are located on the client. All communications between the server processes and the JDBC driver have been through native program interfaces. The main difference when using a Type III driver is that the native CLI libraries are placed on a remote server and the driver uses a network protocol to facilitate communications between the application and the driver. This splits the driver into two parts: an all-Java portion that can be downloaded to the client and a server portion containing both Java and native methods. All communications between the application and the database server are100% Java to Java. However the communications between the database itself and the server process is still done via a native database CLI. Figure shows how this would look.

142 of 149

Java Programming
Application JDBC Driver(Client)

Network Interface

Local Disk

JDBC Driver Network Protocol

Network Database Server Network Interface

JDBC Driver (Server Listener) Database

Native Database Libraries

Type III Driver Implementation The Type III drivers still implement the same type of Java-to-native call translation we saw in Type II drivers. Instead of the Java-to-native CLI translation occurring on the client, it is done on a remote server. When using Type III drivers, the client side of the driver translates the client request into a driver specific network protocol. It then sends the request to a listener process on the server. It is the responsibility of the remote process to present the request to the database. The remote server process is a proxy for the client. By using Type III drivers ,the client is freed from the database-specific protocol translation.The client piece of a Type III driver only translates requests into the network protocol that the proxy server process understands. It is also important to note that with the type III drivers, you do not download the portion of the driver that communicates with the database-native libraries to the client. As a result of this, Type III drivers are not subject to the same security restrictions found with Types I and II and do not have the same size constraints. Since all of the database 143 of 149

Java Programming specific code resides on the server,you can create one large driver capable of connecting to many different databases. One drawback to Type III drivers, however, is that the network protocol is not standardized. The vendors driver decides how the network protocol is designed and implemented .This means that you cannot use one vendors driver on the client and another vendors driver on the server. Even in cases where both client and server use the same vendors driver, strict version control may be required to ensure complete compatibility between them. The benefit of Type III drivers is that they can be used over the Internet. Since all of the native library calls are made on the remote server,the client does not need to access any local native libraries .Currently ,this is the preferred method of access for applets. IV :Native-Protocol-All-Java Driver Type IV drives are unlike any of the drivers any we have discussed so far. These types of drivers are 100% Java and use no CLI native libraries. A Type IV driver is capable of communicating directly with the database without the need for any type of translation as we have seen in the previous driver types. Implementing a Type IV driver is very straightforward. Figure shows a Type IV implementation.

Client
Application

144 of 149

Java Programming

JDBC Driver

Network Interface

Local Disk

Proprietary DB Protocol(in Java)

Network

Network Interface

Database

Server
Type IV Driver Implementation

Example 1: SQL Select JDBC Application import java.sql.*; public class sqlselect { 145 of 149

Java Programming public static void main(String args[]) { Statement s; ResultSet rs; try{ try{ Class.forName(weblogic.jdbc.oci.Driver); } catch(Exception e) { System.out.println(\n Class not found exception); } Connection c=DriverManager.getConnection(jdbc:weblogic:oracle:fool:, jbcuse r, jbcisfun); s= c.createStatement(); rs=s.executeQuery(select * from department); while(rs.next()) { System.out.println(rs.getInt(department_id)+ ,); System.out.println(rs.getString(dept_name)+ ,); System.out.println(rs.getString(manager)+ ,); } } catch(SQLException e) { System.out.println(\n SQL Exception + e.getMessage() + \n); } s.close(); c.close(); } }

The seven basic steps to JDBC Import java.sql package

146 of 149

Java Programming The JDBC API is a set of classes and interfaces. The package name for these classes and interfaces is java.sql and is imported in the firstline of the example: import java.sql.*; Any application you intend to use the JDBC API is must import the java.sql package. Load and register driver Step two actually involves two steps in and of itself. The first is to load the driver, the second is to register the driver. However, although they are two very distinct processes, only one method call is needed to perform both steps. Loading the driver The driver can be loaded in any of several different ways. The most common and easiest method to load the driver using the Class.forName() Class.forName(weblogic.jdbc.oci.Driver); \ The Class.forName() method takes the complete package name of the driver as its argument .In this example ,I am using the Oracle driver from WebLogic found in the weblogic.jdbc.oci.Driver package.Your driver package name be different. Registering the Driver All drivers are required to register themselves at load time. The driver itself calls the DriverManager.registerDriver() method at load time to ensure that the driver is properly registered. The DriverManager.registerDriver() method should never have to be called explicitly by an application. Establish connectionOnce a driver is loaded, the standard method of establishing a connection to the database is to call DriverManager.getConnection ()method. The getConnection() method takes at least two arguments .The first is a string representing the URL of the database followed by a set of login properties, such as the user name and password. In Example ,we establish our connection using: Connection c=DriverManager.getConnection(jdbc:weblogic:oracle:fool:,jdbcuser,jdbcisfun); Here,the URL used is jdbc:weblogic:oracle:fool.The next string is the user name jdbcuser and finally the password for the jdbcuser. Create a statement

147 of 149

Java Programming Once you have established a connection to the database,you need to create a statement object from which to execute your query This is done in example using the Connection.createStatement(). Statement s=c.createStatement(); Note that to create a Statement object, you must use the Connection.createStatement().method.As with nearly all class objects in the JDBC, Statements cannot be instantiated using the new keyword. It should also be mentioned that the Statement created in this example is only one of three types of statement objects. The other two types of statement classes, PreparedStatement and CallableStatement, are subclasses of the Statement class. Execute the statement Finally, after all the preparations, we are ready to actually execute an SQL statement .The method used to execute a simple query is Statement executeQuery().Here is the code used in the example: ResultSet rs =s.executeQuery(select * from department); The code for a simple SQL query is fairly straight forward. The executeQuery() method takes an SQL query string as an argument and returns the results of the query as a ResultSet object.The ResultSet object contains boththe data returned by the query and methods for retrieving the data. There are several variations on execution methods. The executeUpdate() method is used to update the database(write to)results and the execute() method is used for SQL statements that return multiple. Retrieve the statement After the execution of SQL statement, the next task is to retrieve the results. Results are stored in a ResultSet object. Unlike the rest of the seven steps, retrieval of the data takes more than one line of code. To retrieve the data out of the ResultSet and into java variable, you need to use one of the ResultSet get methods . The get method retrieves the data from the ResultSet and converts it to a Java type. Each get method is used to retrieve a different Java type. In the example we used getInt() method to retrieve the integer value from the particular column.getString () is also used to retrieve the String value. The get methods all take the column index as an argument and return the value found in the current row of that column. By placing the get method in a loop and incrementing the row pointer using the ResultSet.next() each time, you can step through the entire result set. In our example, we used the following code to accomplish this. While(rs.next()) 148 of 149

Java Programming { System.out.println(rs.getInt(department_id) + , System.out.println(rs.getString(dept_name) + , System.out.println(rs.getString(manager) ) } Close the connection and statement The final steps in any database application should be to close the connection and any open statements. As noted earlier, open connections can often cause trouble for databases and can also cause security problems. While it is not absolutely necessary that you close every connection and its statement object, it is highly recommended. Simply add the lines as in the following example: s.close(); c.close();

Exception handling
The only two lines of code not discussed so far are the try and catch statements. Since nearly all of the methods used in the example have the potential to throw SQLException, we must either catch them or allow them to propagate up to the next level. Here in the following example , we will catch them and handle them locally by simply printing out the error message: catch(SQLException e) { System.out.println(\n SQLException +exception.getMessage() + \n); } We also could have added a throws clause to the main clause if we wanted to. Example : public static void main ( String args[] ) throws Exception

149 of 149

You might also like