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, try…catch, 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

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. Java can be a bit slower than native code.Java Programming As a platform-independent environment. Classes and Objects 4 of 149 . You teach a class what to do with a “message” by creating a “method. 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. • Object –Oriented systems can be easily upgraded from small to large systems. • It is easy to partition the work in project-based objects. • 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. we can eliminate redundant code and extend the use of existing class. well-tuned interpreters. smart compilers.” The user creates variables of a data type(objects) or instances and sends messages to those objects. and just-in-time bytecode compilers can bring Java's performance close to that of native code without threatening portability. • Software complexity can be easily managed. However.

private and public denote which of the members are private and which of them are public. we can create variables of that type by using the class-name (like any other built-in type variable ). What is a class? A class is a way to bind the data and its associated functions together. The general form of a class declaration is: class class_name { private: variable declarations. The keyword class specifies that what follows is an abstract data of type class_name. creates a variable y of type item. y is called an object of type item. These functions and variables are collectively called members. These class variable are known as objects. function declarations. public and private are discussed later. Therefore. Benefits: 5 of 149 . When defining a class . we are creating a new abstract data type that can be treated like any other built-in datatype. if necessary from the external use. It allows data (and functions)to be hidden. a class specification has two parts: • • Class declaration. Once the class has been declared. public: variable declarations. } The class declaration is similar to a struct declaration. For example : item y . They are usually grouped under two sections. Note that a colon follows these keywords scope of the variables ie. The body of the class is enclosed within braces and terminated by a semicolon. Class function definitions. The class declaration describes the type and scope of its members. Benefits: • Objects provides the benefit of modularity and information hiding. The class function definitions describe how the class function are implemented. Generally. namely. The class body contains the declaration of variables and functions.Java Programming What is an object? An object is an instance of the class Objects are the runtime entities in an object–oriented system. function declarations.

over and over again to create many objects. and keeps them both safe from outside interference and its misuse. Polymorphism means the ability to take more than one form. dynamic) Polymorphism is another important OOP concept. They encapsulate all the essential properties of the objects that are to be created. Shape Draw() Circle object Draw(circle) Box object Draw(box) Square object Draw(square) 6 of 149 . One way to think about encapsulation is as a protective wrapper that prevents the code defined outside the wrapper. Polymorphism (static. Access to the code and data inside the wrapper is tightly controlled through a well-defined interface. and functions to operate on these attributes. Abstraction Abstraction refers to the act of representing essential features without including the background details or expressions. Characteristics of OOP’s Encapsulation Encapsulation is the mechanism that binds together code and the data it manipulates. they are known as Abstract Data Type(ADT). Classes use the concept of abstraction and are and are defined as a list of a list of abstract attributes such as size. 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. weight and cost.Java Programming • Classes provide the benefit of reusability for example we can use the same class. and thus the same code. Since the class use the concept of data abstraction. Polymorphism plays an important role in allowing objects having different internal structures to share the same external interface. Polymorphism is extensively used in implementing inheritance.

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

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

This process is known as hierarchical 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. Let us consider a simple diagram: A B Multiple Inheritance A derived class with several base classes is called Multiple Inheritance.Java Programming Single Inheritance A derived class with only one base class is called single inheritance. A 9 of 149 . A B Multilevel Inheritance C D This is a mechanism of deriving a class from another “derived class” is known as multilevel inheritance.

The abstract superclasses defines and partially implement the behavior but much of the class is undefined and unimplemented. which executes a Java applet. called hypertext links. It was conceived by James Gosling. Thus. Gosling and others began work on a portable. Inc. platform neutral language that could be used to produce code that would run on a variety of CPUs under different environments. programmers can reuse the code in the superclass many times. Patrick Naughton and his team at Sun Microsystems. to related information. Programmers can implement superclass called abstract classes that define “generic” behaviors. 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. in 1991. because the Web. The only connection that HTML has to Java is that it provides the applet tag. to do so requires a full C++ compiler targeted for that CPU. it is possible to embed instructions in a hypertext document that cause a Java applet to execute. With the emergence of the World Wide Web. Through the use of inheritance. While it is possible to compile a C++ program for just about any type of CPU. This effort ultimately led to the creation of Java. The problem is that compilers are expensive and time consuming to create. Other programmers fill in the details with specialized classes.Java Programming B C Benefits of inheritance are as follows: • • Subclasses provide specialized behaviors form the basis of common elements provided by the superclass. Java Applets and Applications 10 of 149 . too. 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. The trouble with C and C++ was that they were designed to be compiled for a specific target. Java was propelled to the forefront of computer language design.

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. 11 of 149 . Java achieves this by confining a Java program to the Java execution environment and not allowing it access to other parts of the computer. any Java program can run on it. An application is a program that is specific to your computer. 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. An applet is an application that can run any where on the Net and can be executed by a Java compatible Web browser. you are risking a viral infection. Portability You have innumerable computers with different operating systems connected to the Internet. every time you download a “normal” program. under the operating system of that computer. the Java runtime system is an interpreter for bytecode. 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. You need to implement only the Java run time system for each platform. Indeed.Java Programming Java can be used to create two types of programs: applications and applets. As you know. The following features help in achieving this task. Once the run time package exists for a given system. Java’s solution to these two problems is both elegant and efficient. 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. Security As you are already aware.

Java was designed to perform well on very low-power CPUs. To achieve reliability. 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. Architecture-Neutral A main issue for the Java designers was that of code longevity and portability. 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 . such as integers. learning Java will be even easier Object –oriented Java was not designed to be source code compatible with any other language. which allows you to write programs that do many things at once. forever . Reliability is given a higher priority in the design of JAva. Operating system upgrades.run time. It is true that Java is interpreted. Java restricts you in a few key areas to force you to find your mistakes early in program development. Multithreaded Java supports multithreaded programming.”To a great extent the goal was accomplished. not multitasking subsystem. processor upgrades. 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.Java Programming FEATURES OF JAVA Simple If you already understand the basic concepts of object oriented programming. Java’s easy to use approach to multithreading allows you to think about the specific behavior of your program. 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. The object model in Java is simple and easy to extend. and changes in core system resources can all combine to make a program malfunction. Distributed 12 of 149 . while simple types.

Create a Java source file Let us know the basic features of a Java Program by writing a simple program. This allowed objects on two different computers to execute procedures remotely.1 and performance enhancements.2 is version 1. improvements to the APIs of JDK 1. Both Netscape and Internet Explorer support Java applets. The original version of Java included features for intra. Java has recently revived these interfaces in a package called remote method invocation (RMI) . /* This is a simple Java program. Example : Let’s start by compiling and running the short sample program shown here.This feature brings an unparalleled level of abstraction to client\server programming.address-space messaging.Java Programming Java was designed for the distributed environment of the Internet because it handles TCP\IP protocols. where small fragments of byte code may be dynamically updated on a running system. This is crucial to the robustness of the applet environment. In fact. 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. accessing a resource using a URL is not much different from accessing a file. 13 of 149 . probably the single most important new feature added to JDK 1. 95 and NT .1 of the Java Foundation Classes(JFC). 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.1 of the Java Foundation classes (JFC).2 is a major upgrade of the Core and standard Extension APIs of the Java development Kit.Macintosh and UNIX. The Java Foundation Classes. JFC is a set of APIs for building the GUI-related components of Java applets and applications. a more secure and flexible security model. CORBA support. It includes version 1. The new features added by Java: The JDK 1.

(The opposite of public is private .Java Programming Call this file”Myfirst. When a class is preceded by public. } } Entering the Program In this example.java”.println (“This is my first Java Program ”). will be between the opening curly brace( { )and the closing curly brace( }). public static void main(String args[]) { System. a source file is officially called a compilation unit.which prevents a member from being used 14 of 149 . The entire class definition .including all of its members. The public keyword is an access specifier.java filename extension A Closer Look at the First Sample Program Although Myfirst. */ class Myfirst { // The program begins with a call to main( ).java In Java. It is a text file that contains one or more class definitions. it includes several key features which are common to all Java programs. Myfirst is an identifier that is the name of the class. then that member may be accessed by code outside the class in which it is declared. 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. 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 Java compiler requires that a source file use the . the name of the source file should be Myfirst.out. which allows the programmers to control the visibility of class members.java program appears to be quite short.

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

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

the following output is displayed: This is my first Java Program.class that contains the bytecode version of the program. Run the application To actually run the program. on those occasions that a method does in fact return data when called. execute the compiler. you must use the Java interpreter. called java. is know as the value of the variable or return. Types identifies the information stored in variables and returned by methods. as shown here: C:\>java Myfirst When the program is run. The information stored in a variable. as shown here: C:\>javac Myfirst. Data Types Java being a programming language. by specifying the name of the source file on the command line. allows to define variable of the following data types : • • • • • • • • boolean char byte short int long float double 17 of 149 . pass the class name Myfirst as a command-line argument. or returned by a method. javac.java The javac compiler creates a file called Myfirst. Thus the output of javac is not code that can be directly executed.Java Programming Compile the source file To compile the Myfirst program. To do so. The Java bytecode is the intermediate representation of your program that contains instructions that the Java interpreter executes. Variable and Data Types All variables in the java language must have a data type.

Java Programming The sizes of these types are a defined in the java languages specification and are listed in the table. it simply uses the name 18 of 149 . then the encoding is the same as seven bit ASCII. For example. Java characters are in Unicode . Their ranges are given in Table 1. The two floating –point types are • • float double Variable name A program refers to a variable’s value by its name.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. 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 two’s complement numbers. when the character counting program wants to refer to the value of the count variable. which is a 16 bit encoding . The range of a variable of type char is from 0 through 2-1. If the most significant nine bits of char are a110.

int count = 0. The character – counting program provides an initial value for count when declaring it.Java Programming count. Final Variable 19 of 149 . Scope places a variable into one of these four categories. Scope of the variable is established when it is declared. 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. Local variables are not declared within a method or within a block of code in a method. Scope A variable ‘s scope is the block of code within which the variable is accessible. • • • • 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 class’s methods) The character counting program declares no member variables . The value assigned to the variable must match the variable’s type. Method parameters are exception handler parameters cannot be initialized in this way. By convention. The value for a parameter is set by the caller. variable names begin with a lowercase letter and class names begin with and uppercase letter. Also a variable’s scope determines when the variable is created and destroyed.

The example program uses + to concatenate “ Input has”. OPERATORS Java operators are divided into these categories: Arithmetic. This means that you must initialize a final variable when it is declared. the value of count.Logical .out. final is similar to const in C/C++. Arithmetic Operators Java’s 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. Assignment. Doing so prevents its contents from being modified.Java Programming A variable can be declared as final.) For example : final int FILE_NEW = 1. evaluate to value incrementing 20 of 149 before . 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 You’ll learn more about flow control in control Flow Statements. Bitwise . Similarly – also has prefix and postfix versions which function in the same way as ++. System.printIn (“Input has” + count+chars”). Relational an conditional . to a string. Operator ++ use op++ Description Increments op by 1. (In this usage.

evaluate to value after Decrementing Relational and Conditional Operators Relational operators compare two values and determine the relationship between them. ! is synonym for || if both of its operands are boolean. != returns true if the two operands are unequal . so they look and act as you would expect if you’re already familiar with one (or both) of these languages. Control Flow Statements Java supports several control flow statements.in read is not equal to –1. evaluates to value before Decrementing Decrements op by 1. These are similar to their C and C++ counterparts. Similarly. 21 of 149 . For example . evaluates to value after incrementing Decrements op by 1. This table summarizes Java’s 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.Java Programming ++ --++op op --op Increments of by 1. The character –counting program uses != to determine whether the value returned by System.

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

Loops Control flow statements include a number of loops : while loops. while and do-while loops while (boolean expression) { .. Boolean expressions aren’t allowed. If expression value is false.. .. In the while loop. although it makes the programmer’s job a lot easier when a number of else clauses are needed: switch (expression) { case constant1: .. do-while loops.. break . case Constant2. break . If the expression evaluates to true. } do { . . byte. for loops. } while (boolean expression).. } The data type of the expression must be either char. . short. the loop is executed. default. the boolean expression is evaluated. .. The value of this expression determines whether or not the body of the loop is executed. Each time 23 of 149 ... case Constant3. or int. .. .. although they are used in all other control flow mechanisms. break. it does not execute..Java Programming Switch Statement The Switch statement is similar in nature to the if -then-else statement. break.

Since we increment the value of x by one (x++) in the expression itself. or in the expression itself.”). as follows: while (x < 10) { x++.println (“The while loop is being executed. (“And the value of x is: “ + x).out. This ensures that your loop code is executed atleast once.println (“The while loop is being executed. the expression always remains true and the loop execute indefinitely! 24 of 149 . no matter what the expression evaluates to. Note that the increment could also have taken place in the body of the loop itself. Be sure to change your expression value either inside the body of the while or do while loop.out. rather than inside the expression : do { System.println (“And the value of x is : “ + x). System. System. System.Java Programming through the body of the while loop. while (x++ < 10) { System. } The while loop is by far the more popular of the two.println (“And the value of x is: “ + x).println (“The while loop is being executed. the expression is re-evaluated. Out. } With the do while loop.out.out. The loop continues until the expression evaluates to false: int x = 0. while (x < 10).out. the body of the loop continues executing as long as x is less than 10.println (“The while loop is being executed. regardless of how the expression evaluates: do { System. If the value never changes. System.println. As with the while loop. we could have incremented our expression inside the loop body.out. the loop is executed 10 times.”). } while (x++ < 10). although the do while loop has the advantage of executing your code atleast once.println (“And the value of x is : “ + x). x++.”).”). the body of the loop executes once before the expression is ever evaluated. } In the preceding example. System.out.

Consider the following example : int x. x<10.println( “The for loop is being executed.Java Programming For loop The for loop repeats program execution as controlled through a series of expressions. It continues looping until the specified boolean condition evaluates to false. Protected 1. System. The third and final expression specifies how the loop variable is to change each time through the loop.. terminating when a certain condition is no longer met. To understand other Modifiers: final abstract static native synchronized 25 of 149 .”). 4.println (“And the value of x is : “ + x). 3.. The second is a boolean expression that specifies the condition that must be met in order for the loop body to be executed. for (x = 0 . booleanExpression . at which point the loop is broken and execution resumes after the loop body: for (expression. 2. x++ ) { System. Public 2. you will be able to:  To Know the Access Modifiers: 1. expression) { . 5.out. out. } The first expression initializes the loop variable. Private 3. } Modifiers At the end of this session.

2. 4. 3. 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.Java Programming In general. Modifier class name Super class Interfaces 26 of 149 .

The variables that declared and used within a class’ methods may not have access modifiers. A private variable or method may only be used by an instance of the class that declares the variables or method. variables. The access modifiers are:    public protected private public Public is the most generous access modifier. as well as the class in the same package as the class in question. you can control what parts of a program can access the members of a class. private The least generous access modifiers is private. By controlling access. a method variable can only be used within its method. and methods.level variables are modifiers are the only variables that may be controlled by access modifiers. the misuse of that data can be prevented.Java Programming This session deals with modifiers. friendly If no access modifier is specified Friendly is the name of the default access of classes. 27 of 149 . A public class. It also provides another important attribute: access control. A class features are • • • The class itself The class variables The methods and constructors Class. Top level classes may not be declared private. Through encapsulation. An application declares its main ( ) method to be public so that main( ) may be invoked from any Java runtime environment. Modifier Overview: Encapsulation links data with the code that manipulates it. This makes sense. Java supplies a rich set of access modifier specifiers. The Access Modifiers Access modifiers control which classes may use a feature. variable. The access specifier that modifies its declaration determines how a member can be accessed. A class’ data and methods may be friendly. or method may be used is any Java program without restriction.

28 of 149 . of type double. the code below will not compile. you might guess that protected access is extremely restrictive-perhaps the next closest thing to private access. Obviously.  data owned by an object that is referred to by a final object reference variable can be changed. Only classes that are in the package may access friendly features of classes that are in the package.lang. and variables.” A final variable may not be modifies once it has been assigned a value. Form the sound of it. For example. Final The final modifiers apply to classes. A final class may not be subclasses. protected The name protected is a bit misleading. methods. Declaring method to be protected static has the same effect as declaring it static protected. but the essential idea is the same: Final features may not be changed.lang.Math { } The compiler error says. In fact.  final reference variable cannot be changed. because the java. The meaning of final varies from context. protected features are even more accessible than friendly features. the java. pi is not the sort of value that should be changed during the execution of a program. For example.Math class has a final variable. it is simply name that is given to the access level that results from not specifying an access modifier. 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. “Can’t subclass final classes.lang. called PI.Math class is final: Class SubMath extends java.Java Programming Friendly is not a Java keyword.

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). methods. the 29 of 149 . A static method may not be overridden to be non-static. Methods. and even a strange kind of code that is not part of a method. for example. an abstract class must be subclassed. Like the abstract keyword. can be declared static. it may not access non-static data. A final class. rather than being associated with an individual instance of the class. abstract is the opposite of final. Native The native modifier can refer only to methods. it may not call non-static methods. In the case of abstract methods. They may be invoked before even a single instance of the class is constructed. To summarize static methods.Java Programming Abstract The abstract modifiers can be applied to classes and methods. Static The static modifier can be applied to variables. may not call is constructor. native indicates that the body of a method is to be found elsewhere. as well as data. A static method may only call the static methods of its class. You can think of static features as belonging to a class. abstract void travel( ) void travel ( ) void travel () void travel () A class hierarchy with abstraction In a way.) Abstract classes provide a way to refer implementation to subclasses. A static method has no this. An abstract class may not be instantiated (that is.     A static method may only access the static data of its class. Thus static methods are not concerned with individual instance of a class. may not be subclassed.

typically C for C++.1 shows all the possible combinations of features and modifiers. typically C for C++. the body lies entirely outside the Java Virtual Machine. 30 of 149 .Java Programming body is in a subclass. 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. Static is so general that you can apply it to free-floating blocks of code. in a library. Modifiers and features Not all modifiers can be applied to all features. Top-level classes may not be protected. and complied for a single target machine type. Table 3. Multithreading is an extensive topic is its own right and is covered later on. not inner) classes. it is rare for application and applet programmers to need to write native code. However. (Thus Java’s platform independence is violated. it is just the name of the default if no modifier is specified.with native methods. Note that classes here are strictly top-level (that is. Synchronized The synchronized modifier is used to control access to critical code in multithreaded programs..) People who port Java to new platforms implement extensive native code of other platform-specific functionality. and complied for a single target language. Native code is written in a non-Java language.

ARRAYS AND STRING ARRAYS: 31 of 149 . 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. Both break and continue can be used with an optional label that specifies exactly where the execution will be transferred. but also for the entire while loop! If this labeled break were not present. not only does the break occur for the switch statement. as described below. such as when a method has been invoked. which interrupts the flow of program execution while a handler is sought to deal with that exception. /*End of Modifiers*/ Branching statements Break and continue statements Java supports two additional statements: break and continue. At any point in the method. catch. a return statement can return the flow of control back to the caller of that method. because they allow the flow of program execution to branch out in directions not seen with the standard control flow statements. those break statements were used without labels. The switch statement makes use of the break statement to terminate a specific case’s execution. and finally statements to catch and handles the exception. The calling method can use the try. However. The throw statement is used to signal a runtime exception.Java Programming Exception Handling When an error occurs within a Java methods . In Java. When this happens. It only executes five times. since the labeled break kicks the flow of control out of both the switch and while loop. the while loop would execute ten times. 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. These are considered “jump” statements.

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

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

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

This can be any legal identifier other than those already used by other items within the current scope. they are not linked in any other way.Java Programming Height Depth b1 Box object Although b and b1 both refer to the same object. including class types that you create. For example: Box b = new Box( ). but b1 still points to the original object. a subsequent assignment to b will simply unhook b from the original object without affecting the object or affecting b1.. 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. b = null. If the method has no parameters. Introducing methods Classes usually consist of two things: instance variables and methods. If the method does not return a value. much of the next chapter is devoted to methods. Here. 37 of 149 . Here. type specifies the type of data returned by the method.. 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. then the parameter list will be empty. The topic of methods is a large one because Java gives them so much power and flexibility. Box b1 = b. The parameter list is a sequence of type and identifier pairs separated by commas. value is the value returned. For example. However. This can be any valid type. //. In fact. its return type must be void. b has been set to null. The name of the method is specified by name. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called.

Java Programming 38 of 149 .

rate = 8. not even void. Once defined. //* Parameterized Constructors Interest( double p . Parameterized Constructors What is needed is a way to construct objects of various dimensions.out. The this keyword Sometimes a method will need to refer to the object that invoked it.If you add parameters to the constructor . As you can probably guess. The easy solution is to add parameters to the constructor. It has the same name as the class in which it resides and is syntactically similar to a method. before the new operator completes. Java defines the this keyword.double r) { principal = p . this makes them much more useful. To allow this. Declaring member variables The variables are automatically initialized when an object is created. principal = 5000. time = t . This is because the implicit return type of a class constructor is the class type itself.println. Constructors look a little strange because they have no return type. 39 of 149 . this can be used inside any method to refer to the current object .("Computing the Interest ") . 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. time = 2. The following lines of code in the above declares the member variables Interest( ) { System.double t . usable object immediately. you can construct various Interest objects of different values.Java Programming Constructors A constructor initializes an object immediately upon creation. the constructor is automatically called immediately after the object is created. } In the above example you can calculate the interest only for one particular entry .

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

It is a reference to the object on which the method was invoked. Ex: simp_int1. this. Understanding instance and class members You know that objects are instances of a class .Java Programming rate =r .12). you create objects using the following code Interest simp_int1 = new Interest( ). Here simp_int1 and simp_int2 are instances of Interest class. Every object contains its own copies of the instance variables principal.3.2. 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. Controlling access to members of a class You might be familiar with the access modifiers(public. double r) { this.rate = r . simp_int2. protected.principal = 5000. You can achieve this using the this keyword.setVar(5000. } Writing a finalize methods 41 of 149 .In the above example. Sometimes a method will need to refere to the object that invoked it.time = t.setVar(10000. ITm can be used inside any method to refer to the current object. Interest simp_int2 = new Interest( ) .timeand rate. this. You can use it anywhere whenever a a reference to an object of the currentclass type is permitted.principal = p . A protected member can be accessed by the members of its class and also by its immediate subclass. If the member is declared private then it can be accessed by other members of its class . } Now you need to initialize each Interest object as simp_int1. To access these variables use the dot operator. private)by now. double t . Interest( double p.10).

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

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

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

class Box1 { double w. // private to A void setab (int x. void sum( ) { tot = a + b. A more practical Example Lets look at a more practical example that will help you to explain the power of inheritance.out.Java Programming */ // Create a superclass. it is only accessible by other members of its own class. b = y. / / ERROR.b is not accessible here } } class Access { public static void main (String args[ ] ) { B Ob1 = new B ( ). //This program uses inheritance to extend Box. Subclasses have no access to it.tot). } } // A’s j is not accessible here. System. Ob1. sum ( ). class B extends A { int tot. int y) { a = x. double ht.setab(10. double d. } } 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. class A { int a . Ob1.println (“Total is “ + Ob1. // public by default private int b . 12). 45 of 149 .

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

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 can’t 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. Let’s 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

then the default or parameterless constructor of each superclass will be used. } } / / Create another subclass by extending B.println (“Inside R’s constructor. Further. } } / / Create a subclass by extending class R. super can also be used to call methods that are hidden by a subclass. in what order are the constructors for the classes that make up the hierarchy called ? For example. then the default or parameterless constructor of each superclass will be executed. As you will see.”). this order is the same whether or not super( ) is used.out. from superclass to subclass. is P’s constructor called before Q’s.”). show( ).Java Programming public static void main (String args[ ] ) { Q Ob1 = new Q (1. The following program illustrates when constructors are executed : // Demonstrate when constructors are called. super allows access to the defined in the superclass. When constructors are called When a class hierarchy is created. since super() must be the first statement executed in a subclass constructor . Ob1. // Create a super class class R { R( ) { System. class E extends D { E( ) { 50 of 149 . constructors are called in order of derivation. class D extends R { D( ) { System. given a subclass called Q and a superclass called P. or vice versa? The answer is that in a class hierarchy. } } 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. 2) .out. If super( ) is not used.println(“Inside D’s constructor.

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

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

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 Let’s 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

The second is used to access a member of the superclass that has been hidden by a member of a subclass. Using super However. class BoxWt extends Box1 { double weight . The interface to this operation is the same no matter what type of figure is being used. double h. The first calls the superclass constructor. Whenever a subclass need to refer to its immediate superclass. To see how super( ) is used. there would be no way for a subclass to directly access or initialize these variables on its own. Here. if an object is derived from Fig. Each use is examined here. Area is 40 Area for fig is undefined. // weight of box / / initialize width. Area is 0 Through the dual mechanisms of inheritance and run time polymorphism . it can do so by use of the keyword super. then its area can be obtained by calling area( ). that keeps its data members private). super()must always be the first statement executed inside a subclass constructor. it is not surprising that Java provides a solution to this problem. there will be times when you will want to create a superclass that keeps the details of its implementation to itself (that is. it is possible to define one consistent interface that is used by several different . In this case. double d. double m) { 56 of 149 . Since encapsulation is a primary attribute of OOP. In this case. 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). super has two general forms.Java Programming Inside area for triangle. height. types of objects. and depth using super( ) BoxWt (double w. parameter-list specifies any parameters needed by the constructor in the superclass. consider this improved version of the BoxWt( ) class : / / BoxWt now uses super to initialize its Box attributes. yet related.

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

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

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

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

2) .a = c. int d) { super.println("a in subclass : " + a). Ob1. super allows access to the defined in the superclass.println("a in superclass: " + super.out.out. 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. As you will see.as shown in the above example .a). As you will see as you create your own class libraries . leaving it to subclass to fill in details . This is the case with the class Fig used in the preceding example.Such a class determines the nature of the methods that the subclasses must implement. // a in B } void show( ) { System.Java Programming Q (int c.You can this situation in two ways. System. The definition of area() is simply a placeholder. super can also be used to call methods that are hidden by a subclass. It will not compute and display the area of any type of the object. } } class Super { public static void main (String args[ ] ) { Q Ob1 = new Q (1.You may have methods which must be overridden by the subclass in order for the subclass to have any meaning.One way. One way this situation can occur is when a superclass is unable to create a meaningful implementation for a method. sometimes you will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses. 61 of 149 . // a in P a = d. 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.it is uncommon for a method to have no meaningful definition in the context of its superclass.

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

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

Using interface.println(“Area is “ +f. System.Java Programming } //override area for right triangle double area() { System.area()). Fig f.8).And.it is through superclass reference variables that overridden methods are resolved at run time.out.out. you can specify what a class must do. but they lack instance variables. f =t. and their methods are declared without any body.println(“Inside Area for Triangle.since it is now abstract.which means that it can be used to refer to an object of any class derived from Fig . Also. any number of classes can implement an interface.it is no longer possible to declare objects of type Fig.area()).5). this means that you can define interfaces which don’t make assumptions about how they are implemented. you can fully abstract a class interface from its implementation. Although it is not possible to create an object of type Fig. but not how it does it. System.You will receive a compile-time error. Creating Package and Interfaces What is an interface? Using the keyword interface.As explained. In practice. Once it is defined. return d1*d2 / 2. //this is OK.10). Interfaces are syntactically similar to classes. //illegal now Angle r =new Angle(9.out.The variable f is declared as a reference to Fig. Triangle t=new Triangle(10.println(“Area is “ + f .all subclasses of Fig must override area(). } } class AbstractAreas() { public static void main(String args[]) { //Fig f =new Fig(10. } } As the comment inside main()indicates. you can create a reference variable of type Fig .no object is created f =r. one class can implement any number of interfaces.”). 64 of 149 .

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

To implement an interface. PACKAGE Java provides a mechanism for partitioning the class name space into more manageable chunks. include the implements clause in a class definition. The methods that implement an interface must be declared public.. the class names are put into the default package. it is inadequate for real applications.]] { //class -body } Access is either public or not used. Any classes declared within that file will belong to the specified package.The general form of a class that includes the implements clause look as below: access class classname[extends superclass] [implements interface[. interface Call { void call(int param) } Implementing an interface Once an interface has been defined. The package is both a naming and a visibility control mechanism. you will define a package for your code. and then create methods defined by the interface. The package statement defines a name space in which classes are stored. While the default package is fine for short. one or more classes can implement that interface.interface. If you omit the package statement.. the type signature of the implementing method must match exactly the type signature specified in the interface definition. then the same method will be used by clients of either interface. sample programs. Also. Most of the time. If a class implements two interfaces that declare the same method. If a class implements more than one interface.Java Programming declares a simple interface which contains one method called Call()that takes single integer parameter. the interfaces are separated with a comma. which has no name. You can define classes inside a package that are not accessible by code outside that package. 66 of 149 . Creating a package To create a package is quite easy : simply include a package command as the first statement in a Java source file. This mechanism is the package. This is the general form of the package statement : package pk.

You can no longer refer to it simply as Test.pkg3] ]. You then make test the current directory and compiled Test. you create a directory called test and put Test. the following statement creates a package called MyPack. 67 of 149 .java.class being stored in the test1 directory. though. This results in Test. You can create a hierarchy of packages.Test. To do so. When you try to run Test. simply separate each package name from the one above it by use of a period. Using package members ///Todo Managing source and class files Assume that you create a class called Test in a package called test1. separating the packages with dots. Since your directory structure must match your packages. This class must now be called test. as it should be. For example. the Java interpreter reports an error message similar to “can’t find class Test as it is because the class is now stored in a package called test1.pkg2[. pk is the name of the package .You must refer to the class by enumerating its package hierarchy. package MyPack .Java Programming Here. The general form of a multileveled package statement is shown here : package pkg1[.java inside that directory.

while you're learning about them.Java Programming Implementing nested class Inner classes In Java it’s possible to place a class definition within another class definition. An anonymous class cannot be both an explicit subclass and implement an interface. A static inner class means: • You don’t need an outer-class object in order to create an object of a static inner class. however. Clearly you cannot use new in the usual way to create an instance of a class if you do not know its name. 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. it’s important to understand that inner classes are distinctly different from composition. • You can’t 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. 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. 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. However. Note that extending Object is implicit where an interface is implemented. At the end of this section. when you say an inner class is static. after all of the syntax and semantics of inner classes have been described. Static nested classes To understand the meaning of static when applied to inner classes. Often. you’ll find an example that should make clear the benefits of inner classes. the need for inner classes isn’t immediately obvious. you must remember that the object of the inner class implicitly keeps a handle to the object of the enclosing class that created it. A class defined in this way without a name is called an anonymous class. This is not true. 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 . This is called an inner class.

Object.Its constructor has no arguments 69 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.

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

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

As discussed in the earlier chapters the primitive datatypes such as int. and character data are treated in the primitive form for the sake of efficiency . Each Java primitive data type has a corresponding wrapper class in the java. For example. In addition to append. modify a character at a specific location within the buffer. Converting objects to strings You can convert several different data types to Strings using String’s valueOf method. The valueOf() method converts data from its internal format into a humanreadable form. and so on. boolean .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.char etc has a corresponding wrapper classes. numerical. 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 The reverselt method uses StringBuffer’s append method to add character to dest. float . 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. StringBuffer provides methods to insert characters into the buffer.lang package.

out.println (str). Provide descriptive methods & fields in a logical way.println (str1).Java Programming • • • Wrapper classes provides useful static methods for a particular type with a logical & consistent way. 67. 3).out. }} This program generates the following output : ABCDEF CDE 73 of 149 . 0. Can be used in any context where an object referenced is required. 66. String str = new String(ascii. String str1 = new String (ascii. 69. System. 2. 68. class SubStrCon { public static void main (String args[ ] ) { byte ascii [] = { 65. 70 }. 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. 0). System.

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

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

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

Java Programming If you need to extract more than one character at a time. It has this general form : void getChars(int sourceStart. } } 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. 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. use equals( ). It has this general form: boolean equals(Object str) 77 of 149 .start]. System. the easiest way is to call toCharArray( ). you can use the getChars( ) method.out. equals( ) and equalsIgnoreCase( ) To compare two strings for equality. since it is possible to use getChars( ) to achieve the same result.getChars(start. intsourceEnd. char target[ ].println(buf). str. int end = 14.”. buf. char buf[ ] = new char[end . int start = 10. 0). String Comparison The string class includes several methods that compare strings or substrings within strings. It has this general form : char[ ] toCharArray( ) This function is provided as a convenience. end . Each is examined here. It returns an array of characters for the entire string.

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

“men”. class Sort { static String ar[ ] = { “Now”.out. It has this general form: int compareTo(String str) Here. “to”. } } } The output of this program is the list of words : Now aid all come 79 of 149 . “is”. “their”. Here is a sample program that sorts an array of strings.Java Programming than another if it comes after the other in dictionary order. 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. i < ar. compareTo(ar[j] ) < 0) { String t = ar [j]. “good”.println(ar[j]). “time”. “of”. “for”. The string method compareTo( ) serves this purpose. “aid”.length. “all”. “to”. “the”. ar[j] = ar[i]. j++) { for (int i = j + 1. The invoking string is greater than str. “come”. ar[i] = t. j < ar. } } System.length . public static void main(String args[ ] ) { for (int j = 0. i++) { if (ar[i]. str is the String being compared with the invoking String. “country” }. The program uses compareTo( ) to determine sort ordering for a Bubble sort: / / A bubble sort for strings. The two strings are equal. “the”.

there is no method for String ordering that will ignore case. startIndex specifies the beginning index. Modifying a String Since string objects are immutable. came out before all the others because it begins with an uppercase letter. 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. which means it has a lower value in the ASCII character set.Java Programming country for good is men of the the their time to to As you can see from the output of this example. The string returned will contain all of the characters from the beginning index. At this time. startIndex specifies the index at which the substring will begin. The first is String substring(int startIndex) Here. up to but not including the ending index. The word “Now”. It has two forms. int endIndex) Here. substring( ) You can extract a substring using substring( ) . The second form of substring( ) allows you to specify both the beginning and ending index of the substring: String substring(int startIndex. The following program uses substring( ) to replace all instances of one substring with another within a string : 80 of 149 . This form returns a copy of the substring that begins at startIndex and runs to the end of the invoking string. and endIndex specifies the stopping point. compareTo( ) takes into account uppercase and lowercase letters.

concat( ) performs the same function as +.indexOf(search).println(org). concat( ) You can concatenate two strings using concat( ). a = str.substring( i + search. string str = “one”. Thwas was a test. 81 of 149 . This is. Thwas was.Java Programming / / Substring replacement. do { / / replace all matching substrings System. i).out. } } The output from this program is shown here : This is a test. String str1 = str + “two”. too. str3 = str3 + str. Thwas was a test. concat(“two”). It generates the same result as the following sequence: String str = “one”. 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. too. too. str = str3.”. This is. int a . String str2 = “was”. This is. Thwas was a test. puts the string “onetwo” into str1. String str1 = str. String str3 = “ “. } } while ( i ! = -1). Thwas is a test. str3 = str + str2. too. if ( a = ! = -1) { str3 = str. Thwas is. For example.length( ) ). class StringReplace { public static void main (String args[ ] ) { String str = “This is a test.substring (0. too. too. String str1 = “is”. This is .

such as digits. the following program prompts the user for the name of a state and then displays that state’s capital. ‘w’). 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. puts the string “Hewwo” into s. For example. original specifies the character to be replaced by the one specified by replacement. Here are the general forms of these methods : String toLowerCase( ) String toUpperCase( ) 82 of 149 . Nonalphabetical characters.Java Programming replace( ) The replace( ) method replaces all occurrences of one character in the invoking string with another. replace (‘1’. char replacement) Here. It has the following general form: String replace(char original. are unaffected.trim( ). It uses trim( ) to remove any leading or trailing whitespace that may have inadvertently been entered by the user. It has this general form : String trim( ) Here is an example: String str = “ Hello world “. This puts the string “Hello World” into str. The resulting string is returned. For example. trim( ) The trim( ) method returns a copy of the invoking string from which any leading and trailing whitespace has been removed. The trim( ) method is quite useful when you process user commands. String str =“Hello”.

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

Also. length( ) and capacity( ) The current length of a StringBuffer can be found via the length( ) method.length( ) ). class StringBuffer { public static void main(String args[ ] ) { StringBuffer sb = new StringBuffer (“Hello”).capacity. because reallocation is a costly process in terms of time. They have the following general forms : int length( ) int capacity( ) Here is an example : / / StringBuffer length vs.out. ensureCapacity( ) has this general form : void ensureCapacity (int capacity) 84 of 149 .println(“length = “ + sb.out. ensureCapacity( ) If you want to pre-allocate room for a certain number of characters after a StringBuffer has been constructed. while the total allocated capacity can be found through the capacity( ) method. System. frequent reallocations can fragment memory.Java Programming size of the buffer. StringBufer allocates room for 16 additional characters when no specific buffer length is requested.out. System. This is useful if you know in advance that you will be appending a large number of small strings to a StringBuffer. } } Here is the output of this program. 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. you can use ensureCapacity( ) to set the size of the buffer. Its capacity is 21 because room for 16 additional characters is automatically added.capacity( ) ). By allocating room for a few extra characters. System. its length is 5. 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. StringBuffer reduces the number of reallocations that take place.println(“capacity = “ sb.println (“buffer = “ + sb).

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

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

Java Programming 87 of 149 .

The System class has two different versions of getProperty. // Display all command-line arguments. The simpler of the two getProperty methods takes a single argument: the key for the property you want to search for. i+ +) System. This is accomplished by passing command.A command-line argument is the information that directly follows the program’s name on the command line when it is executed .length.line arguments to main () . to get the value of path.separator. } } Try executing this program. use the following statement: 88 of 149 . i<args.out. For example. Both retrieve the value of the property named in the argument list.println(“args [ “ + i + “]: ”+args[i]).Java Programming Command line arguments & Collection . class CommandLine { public static void main(String args[]) { for( int i =0.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.as shown here: java CommandLine is a test 100 –1 When you do.Handling command line arguments Sometimes you will want to pass information into a program when you run it.

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

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

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

Any exception that is thrown out of a method must be specified by a throws clause.").println(" Caught " +e). This clause listrs the type of excption that the method can throw. Any code that must be excuted before a method returns is put in a finally block.Java Programming To manually throw an exception use the keyword throw.ptrintln( "Inside throwOne. 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. You can do this by including a throws clause in the method's declaration. Example: class ExcDemo { static void throwOne( ) throws IllegalAccessException { System. 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.out. throw new IllegalAccessException(" Exception Demo").out. } catch(IllegalAccessException e) { System. } public static void main(String args[ ] ) { try { throwOne( ). } } } The output generated with this program is as follows: 92 of 149 . All other exceptions that a method can throw must be declared in the throws clause . This is necesary for all exceptions except for those of type Error or RuntimeException or ny of their subclasses. If they are not a compile time error results.

... ^ The following diagram illustrates the class hierarchy of the Throwable class and its n\most significant subclasses. In Java throwable objects are instances of any subclass of the Throwable class.... How to throw exceptions with throw statements The throw statement requires a single argument : a throwable object....lang. . 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....Integer..IllegalAccessException: Exception Demo.java:10: cannot throw class java..... Example of a throw statement: throw someThrowableObject .. 93 of 149 . . TO do this just define a subclass of Exception( subclass of Throwable).. Creating your own exception class You can create your own exception types to handle situations specific to your applications.... it must be a subclass throw new Integer(4).......lang.Java Programming inside throwOne caught java.... Object Throwable Error Exception RunTime Exception . Throwable has two direct descendants : Error and Exceptions....

} public String toString ( ) { return "MyException [ " + detail + " ]" . pop up lists and scroll bars. The following example creates an Exception : class MyException extends Exception { private int detail. 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 . They are designed to hold Components – User interface objects such as buttons labels. 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 use layout managers to control the positioning of Components.Java Programming The exception class does not define any methods of its own.You can even override one or more of these methods in exception classes that you create. } } Applets Applets are Java programs that are referenced by a Web Page and run inside a Java enabled Web Browser. Thus all exceptions including those that you create have the methiods defines by Throwable available to them. It obly inherits those methods provided by Throwable. Applets inherit from the AWT Container Class. MyException( int a) detail = a .

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

Thus organizing involves  Adding each component into a potentially visible container( Frame or Applet)...... </APPLET > Creating an user interface: To produce a visually pleasing user interface you must • • Select appropriate Components Organize them within your Windows. Setting the size of the component and its placement within the container.. Basic Controls The following are the basic AWT controls :        Labels Push Buttons Checkboxes Choice Menus Lists Scroll bars Text editing 96 of 149 . 1.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 >] .... A typical user interface screen is constructed as a containment tree which is rooted in the top most container.

There is a label associated with each check box that describes what option the box represents.The value of on determines the initial state of the checkbox. To set its state call setState( ) . Whenever a button is pressed action ( ) is called. boolean on ) The first from creates a checkbox that is initially blank. It consists of a small box that can either contain a check mark or not. The second creates a button that contains str as a label . The second form creates a checkbox whose label is specified by str. Checkboxes It is a control that can be used to turn an option on or off. CheckboxGroup cbg . You can change the state of a check box by clicking on it . To set the label use .You can retrieve the label by calling getLabel( ) . The following are the corresponding methods:  boolean getState ( ) 97 of 149 . It contains a label and generates an event when it is pressed. The corresponding methods are as follows: void setLabel ( String str ) String getLabel ( ) Here str is the label of the button. It has the following constructors:    Checkbox ( ) Checkbox ( String str ) Checkbox ( String str .Java Programming These controls are subclasses of Component. They can be used individually or as part of a group. You can get the label associated with the checkbox using getLabel( ) . It defines the following constructors. They are objects of type Button. The third form creates a checkbox whose label is specified str and whose group is specified by cbg . Buttons These are the most widely used controls . You can set a label for the button by calling setLabel( ) . To retrieve the current state of the box call getState( ). They are objects of the Checkbox class.use setLabel( ). Button( ) Button( String str ) The first version creates an empty button.

getSelectedIndex ( ) returns the index of the item. Choice lists do not cause immediate actions but the current selection is simply obtained by the application . Each time the checkbox is pressed action ( ) is called. You will be knowing about action events in the later sections. 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. Items are added to the list in the order in which calls to addItem ( ) occur. Choices The Choice class is used to create a pop list of items from which the user may choose. Each time a choice is selected action ( ) is called. Each item in the list of String that appears as a left justified label in the order it is added to the Choice object. It has the general form : void addItem(String name ) Here name is the name of the item being added. To determine which item is currently selected.Java Programming    void setState ( boolean on ) String getLabel( ) void setLabel(String str) If on is true the box is checked . 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. you can call either getSelectedItem( ) or getSelectedIndex( ) .if it is false the box is cleared. To add a selection to the list call addItem( ). The following are shown here:   String getSelectedItem ( ) int getSelectedIndex ( ) The getSelectedItem ( ) method returns a string containing the name of the item. When the user clicks on it the whole list of choices pops up and a new selection can be made. Thus the Choice control is a form of menu. Menus 98 of 149 . To obtain the number of items in the list call countItems( ) .

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

import java. MenuBar myMenuBar = new MenuBar ( ) . Frame myFrame = new Frame ( “ Menu Example “). public class MenuApplication extends Object { public static void main(String[ ] args ) { // Create the frame and the menubar. fileMenu. // Add the menubar to the frame myFrame.*.and Save menu items .applet.add(fileMenu). The following code implements the actionPerformed( ) method: public void actionPerformed(ActionEvent event) { if ( event. import java. 100 of 149 . // Add the New and Open menuitems fileMenu.setMenubar(myMenubar).getSource ( ) == saveMenuComponent ) { // Handle save option } } } The following example sets up a Fiel menu with New .add(“Print Document”).getSource ( ) instanceOf MenuComponent ) if ( event.* .add(“ Print Preview”). // Add print preview as option on Print menu . printSubmenu. Open . // Add Print document as option on Print menu. printSubmenu.Save and a Print submenu with two menu items.awt.add(new MenuItem( “New”) ). 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. a checkbox called Auto .add(printSubmenu). //Create the File menu and add it to the menubar Menu fileMenu = new Menu (“File”).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”). myMenuBar.

fileMenu .add(new MenuItem( “Open “) ). printSubmenu .add(“Winken”). Lists 101 of 149 . // Specify the size of the frame myFrame.add(printSubMenu).disable ( ) .300).addSeparator( ).Save checkbox followed by a separator fileMenu. printSubmenu . fileMenu.add(“Print Document ”). Button myButton = new Button ( “Click”). fileMenu. // Create a disabled Save menuitem MenuItem saveMenuItem = new MenuItem (“Save”). saveMenuItem . // Create the Print submenu Menu printSubmenu = new Menu( “Print”).add(“Nodd”).add(“Blinken”).resize( 300. myButton. // Make the frame appear on the screen myFrame. popup.show ( ). After all the items are added then add the popmenu to a component using the component’s add method : PopupMenu popup = new PopupMenu ( “Button Stuff “).add(popup). } } 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 . popup.Java Programming fileMenu.add(saveMenuItem). // Add an Auto.add(new CheckboxMenuItem(“Auto-Save”) ).add(“Print Preview”). popup.

The following are the methods:   String getSelectedItem ( ) Int getSelectedIndex ( ) The getSelectedItem ( )method returns a string containing the name of the item . The first form adds items to the end of the list. GetSelectedIndex ( ) returns the index of the item. The following are the methods:  int countITems ( ) 102 of 149 . You can get the name associated with the item at that index by calling getItem ( ) . The second form adds the item at the index specified by index. While the Choice object shows only one choice the List object can be constructed to show any number of choices .The following are the methods:   String [ ] getSelectedItems ( ) int [ ] getSelectedIndexes ( ) ) or The first method returns an array containing the names of the currently selected items.Java Programming The List class provides a compact multiple choice scrolling selection list. For lists that have only single choice you can fin which item is currently selected by calling either getSelectdItem ( ) or getSelectedIndex ( ) . To obtain the number of items in the list call countItems ( ) . The second method returns an array containing the indexes of the currently selected items. If it is false then only one item may be selected. If multipleSelect is true then the user may select two or more items at a time. To add a selection to the list call addITem ( ) which has the following forms:   void addItem ( String name ) void addItem ( String name . If no selection is made or if more than one item is selected null is returned. boolean multipleSelect ) The first form creates a List control that allows only one item to be selected at any one time. The following are the constructors provided by List:   List ( ) List ( int numRows . int index ) Here name is the name of the item added to the list. You can set the currently selected item using the select ( ) method with a zero based integer index. It can also be created to allow multiple selections. For lists that allow multiple selection you must either use getSelectedItems ( getSelectedIndexes ( ) to determine selections. In the second version the value of numRows specifies the number of entries in the list that will always be visible .

enable and disable editing get the currently selected text and set the text. 103 of 149 . Text fields & Text Areas These classes display selectable text and optionally allow the user to edit the text.From Text Component they inherit methods that allow them to set and get the current selection.Java Programming   void select (int index) String getItem( int index). Here int specifies the number of columns in the textfield . It also has the following methods:  int getColumns( ) :returns the number of columns in the textfield. The Textfield class has four constructors:     TextField ( ) TextField ( int) TextField(String) TextField(String . The string argument specifies the text initially displayed in the text field. It also provides a select ( ) method that lets you select between beginning and end positions that you specify. Each time a List is double clicked action ( ) is called. You can specify the background and foreground colors and font used by text fields and text areas. The TextComponent superclass of TextArea and TextField supplies the following methods  getText ( )  setText ( )  setEditable ( )  selectAll ( )  getSelectedText ( )  isEditable ( )  getSelectionStart ( )  getSelectionEnd ( ) . Both are subclasses of TextComponent . int ).

They let the user to choose exactly which part of the region is visible.  void replaceText ( String .int ) : Inserts the specified text at the specified position. TextArea also has four constructors :     TextArea ( ) TextArea( int .Java Programming  SetEchochar ( ) : sets Echo character which is useful for the password fields. int ).VERTICAL.  int getColumns( ) : returns the number of columns in the text area. The TextArea class supplies the following methods :  appendText ( ) : appends the required text in the text area.  ChargetEchoChar ( )  booleanechoCharIsSet ( ) :both these methods let you ask about the echo character. int ) TextArea(String) TextArea( String . int value It is the initial value of the scrollbar.  int getRows ( ) : returns the number of rows in the textarea.  void insertText ( String . Here int specifies the number of rows and columns in the text area and String specifies the text initially displayed in the text area. int . int ) : Replaces the text from the indicated start position to the indicated end position. int orientation It indicates whether the scrollbar should be horizontal or vertical.HORIZONTAL or Scrollbar. Specified with either Scrollbar. Scroll bars A Scrollbar can act as a slider that the user manipulated to set a value. int visible 104 of 149 . They help you to display part of a region that is too large for the available display area. int . 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 minimum The minimum value the scrollbar can have. (how is the alignment constant as given earlier). The third form creates a label that contains the string specified by str using the alignment specified by how.Setting thism value after the scrolbar is visible has no effect.(str is the new label).CENTER.in pixels of the component that is being partially displayed – (currently visible width/height 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. A label is an object of type Label and it contains the string which it displays.LEFT . After the scrollbar is visible you should use the setPageincrement ( ) method to get the same effect. For Scrollbars controlling scrollable areas this value is usually 0. Labels These controls are the easiest controls.RIGHT or 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. It defines the following constructors:  Label ( )  Label ( String str)  Label (String str . Label. For scrollbars controlling scrollable areas this value is usually : (total width/height . int maximum The maximum value the scrollbar can have. The second form creates a label that contains the string specified by str. 105 of 149 .Java Programming The size in pixels of the visible porion of the scrollable area.int how) The first form creates an empty label . They are passive controls that do not support anyinteraction with the user.  String getText ( ) : gets the current label . ITs value can be Label. The following are the methods provided by Label:  void setText ( String str) : sets or changes the text in a label.

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 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.Java Programming Containers All the controls that you have studied in the previous sections have to be organized in a window (Container). The two argument add( ) method lets you add an argument specifying the integer position at which the component should be added. Adding a component to a container removes the component from the containerit used to be in . All the layout  One argument add( )  Two argument add( ) The first version simply requires that you specify the component to add. A container is responsible for laying out any components it contains. The first argument of the second version lets you add an argument specifying the integer position at which the component should be added. The following constructors are used to create a Frame: public Frame ( ) public Frame( String frameTitle) 106 of 149 . Note: You cannot have one component in two containers even if the two containers are never shown at the same time. Every application needs at least one Frame .disappearing when the other window is iconified then yiou should use a Dialog instead of a Frame. Frames The Frame class provides windows for applets and applications.. You don't create Window objects directly but you always use a subclass of Window called Frame. Windows The Window class creates a top level window. The second argument of the method specifies the component to be added. If an application has a window that should be dependent on another window .

 boolean is Rizeable ( ) & void setResizeable (boolean) : Returns or sets whether the user can change the window's size. 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.  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.MOVECURSOR.  Image getIconImage ( ) & void setIconImage ( Image) : Returns or sets the image displayed when the window is iconified.N. ame.boolean isModal ) 107 of 149 . NE .  MenuBar getMenu ( ) & void setMenuBar ( ) : Returns or sets the bar from this Frame.NW.DEFAULT _ CURSOR .Frame. When the other window is destroyed all its dependent dialogs are destroyed.W or E.String title .SE . Frame.Java Programming Besides the no argument Frame constructor implicitly used by the MenuWindow constructor shown above . Applets don't use dialogs.TEXT_CURSOR. A dialog is dependent on other windows . 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.S. The pre-defined types are Frame.X_RESIZE_CURSOR where X is SW.  void remove ( Menu (component) : Removes the specified menu bar from this Frame.Frame.true). public Dialog (Frame parentFrame . boolean isModal) Dialog myDialog = new Dialog(myFrame . public Dialog (Frame Parent Frame. Dialogs can be modal.  hide ( ) & show ( ) : Specify whether to make the Frame visible or hide it  resize ( ) : Specifies the size of the frame . Frame. the Frame class provides a one argument constructor.HAND_CURSOR. You must first have a frame in order to create a dialog The following costructor creates a modal dialog box. All dialogs are non modal by default which the user can keep up and still work in other windows of the application. 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.CROSSHAIR_CURSOR .

 boolean isResizable ( ) .void setResizable (boolean) :Finds out or sets whether the size ofthe dialog window can change. subPanel2 = new Panel ( ).subPanel1. Panel is the superclass for Applet. and the third version creates a dialog with a title. Once these components have been added you can position and resize them manually using the move ( ) .  String getTitle ( ) . When screen output is directed to an applet it is drawn on the surface of a Panel object. subPanel 2. boolean ) : Creates a dialog box. mainPanel.Java Programming The second form creates a modal dialog box whose parent is myFrame . You can add this panel to another Container by using the following method: add(myPanel). it simply implements Container . menu bar or border . It does not add any new methods .add(subPanel 1). You can create a new Panel using the following statement : Panel myPanel = new Panel( ) . resize ( ) or reshape ( ) methods.   Panels The Panel class is a concrete subclass of Container. Components can be added to the Panel object by its add ( ) method. boolean isModal ( ) : Returns true if the dialog is modal. The following are the methods provided by dialogs: Dialog (Frame . concrete screen component. mainPanel = new Panel ( ).String setTitle( String): Gets or sets the title of the dialog windows. In reality a Panel is a window that does not contain a title bar. subPanel1 = new Panel ( ) . That is why you don't se these items when an applet is run inside a browser. A Panel may be thought of a as a recursively nestable. When you run an applet using an appletviewer it is the applet viewer that provides the title and border. You can even nest the panels Panel mainPanel . Scroll panes 108 of 149 .add(subPanel 2). mainPanel.

If you use the default constructor the scrollpane uses scrollbars if needed otherwise you can pass either ScrollPane.SCROLLBARS_ALWAYS.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 . By default a scroll pane uses scrollbars only if necessary .SCROLLBARS_NEVER or ScrollPane. 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 . A common use for a Scrollpane is to display a large image. ScrollPane. This allows you to create very large containers that don’t have to be displayed all at once.SCROLLBARS_AS_NEEDED. 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 scrollpane’s use of scrollbars. You can specify that it should always use scrollbars or never use scrollbars.

Because of cross – platform restrictions menu related components are not full blown Components . The Graphics class defines a number of drawing functions Each shape can be drawn edge only or filled. All output takes place through a graphics context which is encapsulated by the Graphics class and is obtained in two ways. 110 of 149 .This can be the main window of an applet a child window of an applet or a stand alone application window.Java Programming MenuComponent MenuItem MenuBar Menu CheckBoxComponent As the figures show.0.  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. 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. Coordinats are specified in pixels. Objects are drawn and filled in the currently selected graphics color which is black by default.Instead menu components inherit from the AWT MenuComponent class. 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. The origin of each window is at the top left corner and is 0. all components except for menu related components inherit from the AWT Component class . The following figure is the component hierarchy for the converter program.

this causes an event to be issued. The ActionEvent instance is an object that contains the information about the events that just took place. Event Listeners An Event Listener is an object to which a component has delegated the task of handling a particular kind of event. TextEvent: generated when a text component is modified. decipher them and processes the user's interaction are called Event Handlers . getActionCommand ( ) .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. Let us consider an example of an action Event: Consider a button in an applet . MouseEvent : generated by mouse activity. WindowEvent: generated by window activity ( such as iconifying or de-iconifying ) There are two ways to handle the event mentioned above.Returns the command name associated with the  getModifiers ( ) . choice or checkbox.When the button is clicked an action event is to be sent to an instance of class MyActionListener.Java Programming Event handling Events are objects that describe what happened . FocusEvent : generated when a component receives input focus.Returns any modifiers held during the action. an event of the appropriate type is constructed . It contains:  action. ActionEvent : generated by activation of components AdjustmentEvent : generatd by adjustment of adjustable components such as scrollbars. KeyEvent : generated by a keyboard activity. A mouse click on a Button component generates an ActionEvent with the button as source. The code for an ActionListener is : 111 of 149 . 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. When the component experiences input . ContainerEvent: generated when componetns are added to or removed from a container. Table 1 shows the various interfaces Writing event handlers You can even create events of your own. ItemEvent : generated when an item is selected from a list. There are different classes that describe different categories of user action. When the user performs an action at the user interface level .The generator of these events are Event sources wheras the methods that receive event objects.

} } 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"). Consider a case when you want tocatch iconified evetns on Frame . The larget interface – Window Listener has 7 methods. 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.You can create the following class class MyIc_Listener implements WindowListener { public void windowIconified( WindowEvent we) { // Process the event. From the table you you see that most of the interfaces have only a single method while others have several methods.nothing methods. } } You are creating an instance of MyActionListner which is set as one of the button's action listeners.out. } } 112 of 149 . How to use adapters An adapter is simply a class that defines an interfce by providing do.println( "ActionPerformed "). MyActionListener listener = new MyActionListener ( ).Java Programming class MyActionListener implements ActionListener { public void actionPerformed ( ActionEvent ae) { System.addActionListener (listener). add(b). b.

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. Typing in the remaining methods and giving them empty bodies is tedious. The WindowListener interface defines 7 methods and class MyIc_Listener needs to implement the other six before the compiler will be satisfied . } } Table 3 has the list of all adapter classes along with their evetn listener interfaces : 113 of 149 .event package provided seven adapter classes one for each listener interface by providing do – nothing methods.Java Programming This class may not compile.awt. The java.

public class panelexample extends Applet { 114 of 149 . Other Container objects can be stored inside of a container. When screen output is directed to an applet. import java. or border. or setBounds () methods defined by Component. All user interface elements that are displayed on the screen and that interact with the user are subclasses of Component. It has additional methods that allow other Component objects to be nested within it.*. Other components can be added to a Panel object by its add () method (inherited from Container). positioning and sizing the window. A Panel may be thought of as a recursively nestable. a Panel is a window that does not contain a title bar.awt. It doesn’t add any new methods. it is drawn on the surface of a Panel object.applet. such as mouse and keyboard input. A Container is responsible for laying out any components that it contains.*. It defines over a hundred public methods that are responsible for managing events. In essence. It does it through the use of various layout managers.Java Programming Component At the top of the AWT hierarchy is the Component class. and repainting. import java. Component Container Panel MenuContainer Interface Window Frame The class Hierarchy for Panel and Frame Panel The Panel class is a concrete subclass of Container. concrete screen component. Container The Container class is a subclass of Component. you can position and resize them manually using the setLocation (). a menu bar. Panel is the superclass for Applet. Once these components have been added. setSize (). Component is an abstract class that encapsulates all of the attributes of a visual component. it simply implements Container.

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

Java Programming Window The Window class creates a top-level window. you will use a subclass of Window called Frame.Window | +--java. The dimensions of the border area can be obtained using the getInsets method. you won’t create Window objects directly. Frame Class Frame java. 116 of 149 .) When a Frame window is created by a program rather than an applet. a valid insets value cannot be obtained until the frame is made displayable by either calling pack or show. it will contain in warning message. The title of the Frame is empty. decorated by the underlying window system and capable of being moved around the screen independent of other GUI windows. initially invisible Frame object with the specified title.Object | +--java. to the user that an applet window has been created. described next.Component | +--java. since these dimensions are platformdependent. A top-level window is not contained within any other object. The size of the frame includes any area designated for the border. public Frame(String title) : Constructs a new. however. a normal window is created. It is an independent window. it sits directly on the desktop. Constructors There are only two forms of the Frame constructor: public Frame() : Constructs a new instance of Frame that is initially invisible.lang. and resizing corners. Any application that requires a GUI must use one or more frames to contain the desired components. It is a subclass of Window and has a titlebar. such as “Warning Applet Window”.awt. Generally. The default layout for a frame is BorderLayout.awt. borders.awt. 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 user’s knowledge. If you create a Frame object from within an applet. Frame Frame encapsulates what is commonly thought of as a “Window”.awt.Container | +--java. menu bar. Instead.Frame public class Frame extends Window implements MenuContainer A Frame is a top-level window with a title and a border.

Its signature is shown here: void setSize(int new Width.cyan). and top-level or child windows for applications. you will use it to create child windows within applets. fr.setVisible(true). int newHeight) void setSize(Dimensions newSize) The new size of the window is specified by newWidth and NewHeight. newTitle is the new title for the window.setBounds(10. Setting the Window’s Dimensions The setSize() method is used to set the dimensions of the window.*. Its signature is shown here: void setVisible(boolean visibleFlag) The component is visible if the argument to this method is true. Closing a Frame window 117 of 149 . You can change the title in a frame window using setTitle().10.awt. fr. } public static void main(String str[]) { fram fr=new fram("My frame"). the type of window you will most often create is derived from Frame . public class fram extends Frame { public fram(String str) { super(str). or by the width and height fields of the Dimension object passed in newSize . void setTitle(String newTitle) here . } } Working with Frame Windows After the applet. Otherwise. As mentioned. it will not be visible until you call setVisible().setBackground(Color.350). it is hidden. which has this general form.Java Programming Example: import java. the dimensions are specified in terms of pixels. After a frame window has been created . fr.500. it creates a standard -style window.

The size of the dialog includes any area designated for the border. Each container object has a layout manager associated with it. your program must remove that window from the screen when it is closed. Java has several predefined Layout Manager classes . The dimensions of the border area can be obtained using the getInsets method.Java Programming When using a frame window. modal .the owner of the dialog public Dialog(Dialog owner. since these dimensions are platform-dependent.the title of the dialog. 118 of 149 . public Dialog(Dialog owner. A Dialog is usually not made visible to the user when it is first created. If no call to setLayout() is made . To intercept a window close event. The layout manager is notified each time you add a component to a container. by calling setVisible(false).] Each layout manager keeps track of a list of components that can be stored by their names.the layout manager is used to position each of the components within it. 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. Inside windowClosing(). 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.String title) Parameters: owner . The layout manager is set by the setlayout() method. A dialog must have either a frame or another dialog defined as its owner when it's constructed.then the default layout manager is used.Whenever a container is resized(or sized for the first time). A layout manager is an instance of any class that implements the Layout Manager interface. a valid insets value cannot be obtained until the dialog is made displayable by either calling pack or show.You can use the layout manager that best fits your application .the title of the dialog. you must implement the windowClosing() method of the Window Listener interface.String title.the owner of the dialog title . however.if true.boolean modal) Parameters: owner . you must remove the window from the screen . Constructor Dialog(Dialog owner) Parameters: owner .the owner of the dialog title . The example in the next section illustrates this technique. All of the components have been positioned by the default layout manager.

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

Thus you can create a panel that contains the deck .respectively. When you instantiate a GridLayout .Thus. The second form allows you to specify the horizontal and vertical space left between components in horz and vert. int numColumns) Grid Layout(int numRows. most of the time .Java Programming Grid layout Grid Layout lays out components in a two-dimensional grid.youadd these panels to the panel for which CardLayout is the that contains the deck . 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. CardLayout provides these two constructors: CardLayout() CardLayout(int horz.and a panel for each card in the deck. 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. int vert) The first form creates a default card layout.and a panel for each card in the deck.The cards are typically held in an object of type Panel.int vert) The first form creates a grid layout with the specified number of rows and columns.The cards that form the deck are also typically objects of type Panel.Either numRows or numColumns can be zero.Next.you define the number of rows and columns.The second form allows you to specify the horizontal and vertical space left between components in horz and vert . The constructors supported by Grid Layout are shown here: Grid Layout(int numRows. When card panels are added to a panel. Next.respectively. Specifying numRows as zero allows for unlimited-length columns. Specifying numColumns as zero allows for unlimited –length rows. You can prepare the other layout and have them hidden. int numColumns.You will use this form of add() when adding cards to a panel: 120 of 149 . you add these panels to the panel for which CardLayout is the layout manager. they are usually given a name. 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.This panel must have CardLayout selected as its layout manager. One common approach is to include one push button for each card in the deck. Use of a card layout requires a bit more work than the other layouts. ready to be activated when needed. This can be useful for user interfaces that have optional components which can be dynamically enabled and disabled upon user input. int horz.

public void init() { cl=new CardLayout(). b1. A reference To the component being added is returned . call previous ().To show. Button b3=new Button("3").applet. setLayout(cl). import java.awt. After you have created a deck .addActionListener(this).The advantage to naming each card is that you can bring a card to the surface by specifying its name. Button b1=new Button("1").The show() method displays the card whose name is passed in cardName. the next card. deck is a reference to the container (usually a panel)that holds the cards.name is the name of the card whose panel is specified by panelObj.Both next() and previous() automatically cycle back to the top or bottom of the deck. add("First".Respectively.Component panelObj). import java.addActionListener(this).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.b3). Here. To show the previous card.and cardName is the name of a card.awt. add("Second". } public void actionPerformed(ActionEvent ae) 121 of 149 .b1).addActionListener(this).*. public class CardLay extends Applet implements ActionListener { CardLayout cl.event.call last() .Calling first() causes the first card in the deck to be shown. b2.*.To show the last card. Button b2=new Button("2").call next(). import java. add("Third".*. b3.Java Programming Component add(string name.b2).

122 of 149 . Objects are drawn and filled in the currently selected graphics color which is black by default. If you enlarge the window the applet brings up. and that the new horizontal space is split evenly among all the columns.GridBagLayout places components in a squares (cells) in agrid .and then uses the components preferred sizes to detemine how big the cells should be. Similarly. This behavior is also specified by the applet. not all columns necessarily have the same width. } } Grid bag layout Grid Bag Layout is the most flexible – and complex—layout manager the AWT provides.you set instance variables in a GridBagConstraints object and tell the GridBagLayout(with the setConstraints() method ) to associate the constraints with the component.Java Programming { cl. The graphics context is an instance of the Graphics class. Not all rows necessarily have the same height. As the above applet shows a GridBagLayout places components in a grid of rows and columns. you’ll notice that the last row gets all the new vertical space .next(this). 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. Essentially.allowing specified components to span multiple rows and columns . When the Graphics object is drawn that exceeds the dimensions of the window output is automatically clipped. The graphics object You need a Graphics object in order to use any of the Java's rendering methods.This resizing behavior is based on weights the applet assigns to individual components in the GridBagLayout. To specify constraints. The way the applet specifies the size and position characteristics of its components is by specifying constraints for each component. You’ll also notice that each component takes up as much as space it can. It knows how to render onto a single target.

0) X Y Drawing and Filling Graphics contexts do not have an extensive repertoire of painting methods. (0. Drawing and filling Clipping. The following are the methods:        drawLine ( ) drawRect ( ) & fillRect ( ) drawOval ( ) & fillOval ( ) drawArc ( ) & fillArc ( ) drawPolygon ( ) & fillPolygon ( ) drawPolyline ( ) drawString ( ) Using images 123 of 149 .Java Programming The four major operations provided by the GRaphics class are     Selecting a color Selecting a font.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. The coordinate system All the methods of the Graphics class specify pixel coordiante positions for the shapes they render.

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

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.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 . or myImage = Toolkit.awt has a factory method called createImage ( ) that is used to create Image objects. These methods don't work if called in a constructor or in a statement that declares an instance variable. 125 of 149 .getDefaultToolkit ( ). You should call these methods from a method called init( ). The createImage( ) method has the folowing two forms: Image createImage( ImageProducer imgProd) Image createImage (int width .Java Programming Creating Images The Component class in java. The corresponding methods are : myImage = getImage( URL ). The Applet and Toolkit classes provide getIamge( ) methods that work for either format. Ex: Canvas c = new Canvas. Loading images using the getImage( ) methods: The Applet class supplies two getImage ( ) methods:  public Image getImage( URL url)  public Image getImage (URL url . Loading images The AWT makes it to easy to load images in either GIF or JPEG format. Image test = c.createImage(100.int height) The first version returns an image object producede by imgProdwhich is an object of aclass that implements the ImageProducer interface.100). 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.String name) Only applets can use these methods .

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

1 introduced a new type of stream called a “Reader” or a “Writer” . Likewise . for example : 127 of 149 .a keyboard.a disk file .for example. They contain the same methods. Fortunately.there was no 16-bit version of the byte array streams. Only File. and Stream Tokenizer are not derived from InputStream or OutputStream. All streams behave in the same manner. even if the actual physical devices they are linked to differ.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. an output stream may refer to the console . A stream is linked to a physical device by the Java I/O system.depending on whether it is an input stream or an output stream .0 .The constructors for CharArrayReader and CharArrayWriter look like this. Unfortunately. 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. All the other stream classes extend these two classes.Java Programming Overview of I/O streams A stream is an abstraction that either produces or consumes information. but they are not called streams. or a network socket. under Java 1.only the char array counterparts. This means that an input stream can abstract many different kinds of input: from a disk file. with java1.a network connection . while the CharArrayWriter performs functions similar to the ByteArrayOutputStream. Random Access File. The CharArrayReader and CharArrayWriter classes function almost identically to their byte array counterparts.1 changes were made to include character array streams.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.The character version of the ByteArrayInputStream is called a CharArrayReader.They contain the same methods . The I/O classes defined by java. This encouraged programmers to treat characters as 8-bit values if they wanted to use the byte array streams.only the char array streams use char values everywhere the byte array streams use byte values. the same I/O classes and methods can be applied to any type of device. FileDescriptor. Thus. Java 1.

Although it is through the concrete subclasses that your programs perform I/O InputStream : InputStream is an abstract class that defines Java’s model of streaming input .int length) public CharArrayWriter() public CharArrayWriter(int size) Byte streams You don’t always have to write to a file or the network to use streams. public ByteArrayInputStream(byte[] bytes) creates a byte input stream using the entire contents of bytes as the data in the stream. you must supply an array of bytes that will serve as the source of the bytes to be read from the stream.Java Programming public CharArrayReader(char []buf) public CharArrayReader(char[] buf. they are input and output streams. int length) creates a byte input stream that reads up to length bytes starting at position offset. Method 128 of 149 Description . public ByteArrayInputStream(byte[] bytes. 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. A ByteArrayOutputStream is an array of bytes that continually grows to fit the data stored in it. public ByteArrayOutputStream Understanding I/O super classes Java’s stream based I/O is built upon two abstract classes InputStream and OutputStream. When you create a ByteArrayInputStream. int offset.Table –1 shows a brief synopsis of the methods in InputStream. They are used to create several concrete stream subclasses. int offset.You can write to and read from arrays of bytes using the ByteArrayInputStream and ByteArrayOutputStream classes.All of the Methods in this class willthrow an IOException on errror conditions. These streams are not filter streams like some of the others.

numBytes) int skip(long numBytes) int available() void close() Output Stream : As with Input Stream.length bytes into buffer and returns the actual number of bytes that were successfully read int offset. mark() and reset() are exceptions . int Attempts to read up to numBytes bytes of input. int offset. int Writes a subrange of numBytes. Method Description void write(int b) rites a single byte to an output W stream . 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.All of the methods in this class return a void value and throw an IOException in the case of errors.Java Programming int read() int read(byte buffer[]) int read(byte buffer[]. 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. Attempts to read up to buffer. void close() Closes the output stream 129 of 149 . bytes numBytes) from the arrya buffer. Output Stream is an abstract class that definesstreaming output . Note that the parameter is an int . void flush() Finalizes the output state so that any buffers are cleared.Table-2 shows a list of each of the methods in OutputStream. Returns an integer representation of the next available byte of input. returning the number of bytes actually skipped Returns the number of bytes of input currently available for reading Closes the input source. returning the number of bytes successfully Skips over numBytes of input. beginning at buffer[offset].

when you have had to write an object to a different source. you will deal with it through its proxy.Java Programming Object serialization Up to this point you have been working with objects.io. you have only written out native types like int or char. To create a new thread. your program will: • • Extend Thread (sub classing thread). Since you can’t directly refer to the ethereal state of a running thread. say out to a network via a socket or to file. However. the Thread instance that spawned it. 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. 130 of 149 . In computer terminology. 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. This section introduces you to threads. The java. the need for them and write programs to implement the concept of Multithreading. more than one thread executing at any point in time is called multithreading. Threads Thread encapsulates a thread of execution. Threads are also known as execution contexts or lightweight processes.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. Saving an object to some type of permanent storage is called persistence. you will learn what threads are. Threading In this session. Implement the Runnable interface. and you have learned to create classes so you can manipulate the objects using their methods. 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 you’ve labored to produce to a file or other stream. The main advantage of multithreading is the speed of execution of the program. What is a thread? A thread can be defined as a single sequential flow of control. Objects from classes that do not implement Serializable cannot save or restore their state.

the thread class is strictly an encapsulation of a virtual CPU. Entry point for the thread. this course module has used this approach. it should be extended only when you are changing or extending the behavior of that CPU model.  Because there are times when you are obliged to implement Runnable. you cannot extend any other class. and the value of making the distinction between the CPU. if you have already extended Thread. Because of this. code and data parts of a running thread. This has been discussed earlier. Wait for a thread to terminate. Suspend a thread for a period of time Start a thread by calling its run method. you create a thread by instantiating an object of type Thread. Method Meaning getName getPriority isAlive join run sleep start Creating a Thread Obtain a thread’s name Obtain a thread’s priority. this forces you to take the approach of implementing Runnable. In some situations. Advantages of extending Thread  The advantage of extending Thread: 131 of 149 . and as such.  Because Java technology allows only single inheritance. such as Applet. itself. Now let us see the advantages of both the ways. Determine if a thread is still running.Java Programming The Thread class defines several methods that help manage threads. Java defines two ways in which this can be accomplished: You can implement the Runnable interface or you can extend the Thread class. you might prefer to be consistent and always do it this way. In the most general sense. Advantages of Implementing Runnable:  From an object-oriented design point of view.

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

. It establishes a communication link between a source port IP address and a destination port IP address.package instead of the TCP and UDP layers. HTTP ( Hypertext Transfer Protocol )..) Link ( device. 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 . UDP.net. FTP (File Transfer Protocol) and Telnet are examples of applications that require a reliable communication channel. Applications that require a reliable point to point channel to communicate use TCP to communicate. It sends packets of data called datagrams from one 133 of 149 . When two applications want to communicate to each other reliably they establish a connection and send data over that connection .…. UDP is a connectionless protocol and it does not establish a link for the duration of the connection .telnet . driver….…) Transport ( TCP /IP .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. UDP The UDP protocol provides for non guaranteed communication between two applications on the network. ….) Network ( IP . TCP/IP A TCP is a connection based protocol that provides a reliable flow of data. You can use the classes in the java.corrupt zip file or some other invalid information.TCP guarantees that data sent from one end of the connection actually gets to the other end in the same order it was sent. ftp . ) When you are programming over the network you are programming at the application layer. These classes provide system independent network communication.

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 ). When using UDP an application program writes the destination port and IP address on the datagram and then sends the datagram to the destination . All data destined for a particular computer arrives through that connection . 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. The port numbers ranging from 0 to 1023 are restricted – they are reserved for 134 of 149 . Understanding ports A computer generally has a single physical connection to the network. This has the effect of registering the application with the system to receive all data destined for that port .Java Programming application to another . No two applications can bind to the same port. 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. In a datagram based communication the datagram packet contains the port number of the destination . the order of delivery is not guaranteed and each message is independent of any others. In connection based communication an application establishes a connection with another application by binding a socket to a port number.Sending datagrams is like sending a letter through the mail service .

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

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

String hostName . A java program can construct a URL object open a connection to it. usually identifies a specific location within a file.String path) URL(URL urlObj . reference : a reference to a named within a resource . The protocol identifier indicates the name of the protocol to be used to fetch the resource .com/ is the resource name. Java URL class has four constructors and each can throw a Malformed URLException .followed by the resource name as follows: protocol ID : resource Name The java.String hostName . The second and third forms of the constructor allow you to break up the URL into its component parts. The example uses the HTTP which is typically used to serve hypertypes documents. filename: the pathname to the file on the machine . When constructing a URL put the protocol identifier first followed by a colon (:) .int port .and read to or write from it.(optional).String path) URL (Stirng protocolName .net package contains a class named URL that Java programs use to represent a URL address. 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 . The resource name contains one or more of the following components: host name : the name of the machine the resource lives on. 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 .sun.String urlSpecifier ) The first URL version specifies a string that is identical to what you see in a browser. port number : the port number to connect to.Java Programming the protocol identifier the resource name In the example http is the protocol identifier and //java. Creation of URL using constructors. The following are the constructors: • • • • URL(String urlSpecifier) URL (String protocolName.( typically optional). The format of the resource name depends entirely on the protocol used.

getFile ( ) ) .net.sun.out. this means that you need to retrieve the data associated with that URL for that particular port.out.getExit( ) ) . System. 138 of 149 .println(“Port : “ + ue.sun. 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.getHost( )).toExternalForm ( ) ) .Java Programming import java.println(“File : “ + ue.com/products/index/”).*.java.com /products/index/ The Port number is –1.java. System.com File : /products/index/ Ext: http: // www.sun.out. System.println(“Ext : “ + ue.getProtocol( ) ) .out. System.println(“Host : “ +ue. } The output of the program is as follows : Protocol : http Port : -1 Host : www.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. System.println(“Exit : “ + ue.java.println(“Protocol : “ + ue.out.out. System. class URL_ex { public static void main(String args[ ] ) throws MalformedURLException { URL ue = new URL(“ http:// www.getPort( ) ) .

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

Figure 2 shows how the JDBC-ODBC bridge is implemented.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. The reason for this is simple.The obvious benefit to this is that any database that has an ODBC driver can be used with Java. The ODBC interface remains constant no matter which database is used. It will be up to you to decide which environment is best for your application. Each type has specific properties that make it more or less useful for a particular environment purpose. it is responsibility of the ODBC driver to communicate with the database. The JDBC driver .even if a native JDBC driver does not exist. 140 of 149 . ODBC like JDBC. This means that this type of JDBC driver only needs to speak one language: ODBC.therefore. Type I: JDBC-ODBC bridge The JDBC-ODBC bridge driver is the only driver currently supplied by JavaSoft. all drivers fit into four distinct categories. 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 . defines an interface. has no knowledge of the actual database it is communicating with. Once JDBC passes the request off to the ODBC driver. The ODBC bridge is the only driver that can be used with multiple databases and is vendor independent.

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 ODBC driver then converts the request again and presents it to the database interface. The driver does this by making calls to the locally installed native(vendor specific)call level interface (CLI). The CLI libraries are responsible for the actual communications with the database server. The results of the request are fed back through the same channels but in reverse. results are then translated from their native format back to JDBC and presented to the client application. the java application submits an SQL statement through the JDBC driver.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.Java Programming Application JDBC Driver ODBC Driver Database Figure 2:JDBC-ODBC Bridge As you can see from the diagram. Application 141 of 149 .The CLI libraries are typically written in “C” but can be in any one of many programming languages. The JDBC driver translates the request to an ODBC call. When a client application makes a request . After the database services the request.

all native CLI libraries are located on the client. All communications between the application and the database server are100% Java to Java. 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. 142 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. 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. it was necessary to have the ODBC driver loaded locally on the client. Figure shows how this would look. With Type I drivers. Type II. All communications between the server processes and the JDBC driver have been through native program interfaces. Similarly. The only difference between Type I. they actually offer little that is new. However the communications between the database itself and the server process is still done via a native database CLI. and Type III drivers is the placement of the native database access libraries. with Type II drivers.

the client is freed from the database-specific protocol translation. Instead of the Java-to-native CLI translation occurring on the client. It is the responsibility of the remote process to present the request to the database. By using Type III drivers . the client side of the driver translates the client request into a driver specific network protocol. As a result of this. you do not download the portion of the driver that communicates with the database-native libraries to the client. it is done on a remote server. When using Type III drivers. The remote server process is a proxy for the client. Since all of the database – 143 of 149 . It is also important to note that with the type III drivers. 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.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.The client piece of a Type III driver only translates requests into the network protocol that the proxy –server process understands. It then sends the request to a listener process on the server.

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

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. public class sqlselect { 145 of 149 .sql.*.

while(rs.close(). System. rs=s.println(“\n Class not found exception”).Driver”).Java Programming public static void main(String args[]) { Statement s.out. try{ try{ Class.out.next()) { System. ResultSet rs.out.out.getMessage() + “\n”).forName(“weblogic.”). } s.getConnection(“jdbc:weblogic:oracle:fool:”. c. } } The seven basic steps to JDBC Import java. } Connection c=DriverManager.println(“\n SQL Exception” + e.jdbc.println(rs. “jbcuse r”.executeQuery(“select * from department”). “jbcisfun”).oci.createStatement(). } } catch(SQLException e) { System.”).sql package 146 of 149 .out. System.println(rs. } catch(Exception e) { System.”).getInt(“department_id”)+ “ .println(rs.close(). s= c.getString(“manager”)+ “ .getString(“dept_name”)+ “ .

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

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

out. Here in the following example .Java Programming { System.out.” System. Exception handling The only two lines of code not discussed so far are the try and catch statements. it is highly recommended.out.println(rs.getString(“dept_name”) + “. open connections can often cause trouble for databases and can also cause security problems.close().getString(“manager”) ) } Close the connection and statement The final steps in any database application should be to close the connection and any open statements. we will catch them and handle them locally by simply printing out the error message: catch(SQLException e) { System.close().out.println(“\n SQLException “ +exception.getMessage() + “\n”). c. While it is not absolutely necessary that you close every connection and its statement object. Example : public static void main ( String args[] ) throws Exception 149 of 149 . } We also could have added a throws clause to the main clause if we wanted to.getInt(“department_id”) + “. Since nearly all of the methods used in the example have the potential to throw SQLException. As noted earlier.println(rs.” System. Simply add the lines as in the following example: s. we must either catch them or allow them to propagate up to the next level.println(rs.