java

79
BCA-501.INTERNET APPLICATIONS AND JAVA Section I Introduction Internet Architecture board The IAB is an independent committee of researchers and professionals with a technical interest in the health and evolution of the Internet system... IAB members are deeply committed to making the Internet function effectively and evolve to meet a large scale, high speed future. The IAB evolved from the Internet Configuration Control Board (ICCB) originally established in 1979 by the ARPANET Program Manager Vinton Cerf, and oversees development of the Internettechnology standards. In 1983, the ICCB was reorganized around a series of technical task forces by Cerf's successor, Dr. Barry Leiner, and named the Internet Activities Board (IAB). The IAB was supported throughout the 1980's by the Federal Research Internet Coordinating Committee (FRICC), an informal group of US Government managers supporting inter-networking that was absorbed into the Federal Networking Council in 1990. In June, 1992, the Internet Activities Board was renamed theInternet Architecture Board by the Internet Society at the INET92 conference in Kobe, Japan. The roles and responsibilities of the IAB are described in RFC 2850, and summarized below: Oversight. Provide oversight of the Internet architecture, protocols, procedures, and standards. RFC management. Provide editorial management and publication of the Request For Comments documents. IESG selection. Appoint the members of the Internet Engineering Steering Group, and the chair of the Internet Engineering Task Force. IETF oversight. Responsible for the IETF's relationships with other standards bodies and related organizations. IANA administration. Provide administration of the Internet Assigned Numbers Authority, which manages the various Internet numbers and parameters. The IAB is composed of 13 members, made up of 12 members nominated by the IETF and approved by the Board of Trustees of the Internet Society, plus the IETF chair who may vote on all official actions except approval of Internet Engineering Steering Group members and IESG appeals. Each member serves for two years, and may serve more than one term. Interestingly, members of the IAB must serve as individuals, and not as representatives of a company, agency, or other organization. The process is further described inIAB and IESG Selection, Confirmation, and Recall Process: Operation of the Nominating and Recall Committees, RFC 3777. Resources. Request For Comments documents by and about the IAB are listed below: RFC 1160; Vinton Cerf; The Internet Activities Board; May 1990 RFC 1601; C. Huitema; Charter of the Internet Architecture Board; Mar 1994 RFC 2026; S. Bradner; The Internet Standards Process -- Revision 3; 9 Oct 1996 RFC 2850; B. Carpenter, Ed.; Charter of the Internet Architecture Board; May 2000 RFC 3869; R. Atkinson, Ed.; S. Floyd, Ed.; IAB Concerns and Recommendations Regarding Internet Research and Evolution; Aug 2004. Understanding the internet What is the Internet?

Upload: sapnasagar

Post on 02-Sep-2015

5 views

Category:

Documents


1 download

DESCRIPTION

java

TRANSCRIPT

BCA-501.INTERNET APPLICATIONS AND JAVASection I IntroductionInternet Architecture boardThe IAB is an independent committee of researchers and professionals with a technical interest in the health and evolution of the Internet system... IAB members are deeply committed to making the Internet function effectively and evolve to meet a large scale, high speed future.TheIABevolved from the Internet Configuration Control Board (ICCB) originally established in 1979 by the ARPANET Program ManagerVinton Cerf, and oversees development of theInternettechnology standards. In 1983, the ICCB was reorganized around a series of technical task forces by Cerf's successor, Dr. Barry Leiner, and named the Internet Activities Board (IAB).The IAB was supported throughout the 1980's by the Federal Research Internet Coordinating Committee (FRICC), an informal group of US Government managers supporting inter-networking that was absorbed into the Federal Networking Council in 1990.In June, 1992, the Internet Activities Board was renamed theInternet Architecture Boardby theInternet Societyat the INET92 conference in Kobe, Japan. The roles and responsibilities of the IAB are described inRFC 2850, and summarized below: Oversight. Provide oversight of the Internet architecture, protocols, procedures, and standards. RFC management. Provide editorial management and publication of theRequest For Commentsdocuments. IESG selection. Appoint the members of the Internet Engineering Steering Group, and the chair of theInternet Engineering Task Force. IETF oversight. Responsible for the IETF's relationships with other standards bodies and related organizations. IANA administration. Provide administration of theInternet Assigned Numbers Authority, which manages the various Internet numbers and parameters.The IAB is composed of 13 members, made up of 12 members nominated by the IETF and approved by the Board of Trustees of the Internet Society, plus the IETF chair who may vote on all official actions except approval of Internet Engineering Steering Group members and IESG appeals. Each member serves for two years, and may serve more than one term. Interestingly, members of the IAB must serve as individuals, and not as representatives of a company, agency, or other organization. The process is further described inIAB and IESG Selection, Confirmation, and Recall Process: Operation of the Nominating and Recall Committees,RFC 3777.Resources. Request For Comments documents by and about the IAB are listed below: RFC 1160; Vinton Cerf;The Internet Activities Board; May 1990 RFC 1601; C. Huitema;Charter of the Internet Architecture Board; Mar 1994 RFC 2026; S. Bradner;The Internet Standards Process -- Revision 3; 9 Oct 1996 RFC 2850; B. Carpenter, Ed.;Charter of the Internet Architecture Board; May 2000 RFC 3869; R. Atkinson, Ed.; S. Floyd, Ed.;IAB Concerns and Recommendations Regarding Internet Research and Evolution; Aug 2004.

Understanding the internetWhat is the Internet? Protocols, computers and communities Information, servers and browsers A packet-switched network using TCP/IP

Strictly speaking, the Internet is a communications protocol, a language which computers use to talk to each other, called TCP/IP. This language is designed to enable computers to exchange data reliably and efficiently, though not necessarily quickly.More generally, the term is used to signify the network of computers connected using TCP/IP: the connecting wires and the equipment used to route the information (the network infrastructure), and the computers themselves.

Even more generally, the Internet is often used to indicate the community of users and computers collectively. Though a very broad definition, this is perhaps the most useful and interesting the Internet is really an information-based society.

Protocols created by the community

Internet protocols are constantly evolving Democratic decisions guard against control by individuals A technocracy?

The TCP/IP and related protocols that are used across the Internet are designed and agreed upon by the users and administrators of the individual parts of the Internet: anyone can contribute to the growth and direction of the Internet, though you do need to know a fair amount of technical detail to get involved. In this way, the Internet is not so much controlled by an organisation, as encouraged in a certain direction by its members. It's a kind of open, contributory democracy. Sometimes, companies will try to force the net to go the way they want, but usually there's enough resistance from the mass of contributors to only go that way if the idea or direction is good for the 'net as a whole.The influence each person has on the direction of the Internet is usually related to their technical knowledge and reputation, with widely respected techies holding the most power. It's perhaps more of a technocracy than a traditional democracy.Protocols serving information to a communityProtocols serving information to a community Internet hosts Clients and servers Exponential growth, and still growing?The Internet, as a network of networks, consists of many computers, called servers or hosts, which are linked by communication lines. The administrators of these hosts may make information or software stored on them publically available, so that others can view, download or use the data. At the last count (Jul 2007), there were an estimated 489 million hosts [http:// www.isc.org/index.pl?/ops/ds/] connected to the Internet.

Dynamic and permanent connectionsHowever, most Internet-connected computers act only as clients ; they access the data storedon other servers, but don't store or share any information themselvesi. It's hard to estimate how many client computers there are in cyberspace, because many connect dynamically or are hidden behind firewalls, but a conservative estimate (according to Nielsen//Netratings [http://www.nielsen-netratings.com]) would be more than 800 million, possibly much higher. According to Internet World Stats [http://www.internetworldstats.com/], nearly 1.5 billion people have some form of Internet access.Dynamic and permanent connections Dynamic vs. static Internet addresses Instant connection vs. dial-up Dedicated cabling vs. telephone linesClients may be permanently connected (often known as always-on), or may connect dynamically when needed.Permanent connections are most commonly made through a local area network (LAN) or a digital subscriber line (DSL or ADSL ), and give instant 24/7 access.A temporary, dynamic connection such as that provided by a modem link needs to be connected each time the Internet is used, which can cause a delay. Modem links also tend to be slower than dedicated digital links, because they use normal voice telephone lines which are not designed to carry digital signals.

DSL connections also carry a digital signal across wiring designed for analogue signals, but do so by overlaying a very high frequency signal (well beyond human hearing) onto the normal connection. This means that not only can the same line carry voice and data simultaneously, but that for short distances, a much higher bandwidth can be carried.

Dedicated wiring for Internet traffic is most commonly found in companies and other organisations, where a LAN is used to connect clients and hosts together. Usually, this forms an enclosed network which connects to the outside world through a single point, which can be controlled and protected against intrusion and viruses. Connection to this type of network is normally instantaneous and 'always-on'.

In fact, the distinction between clients and servers is becoming very blurred, with the advent of peer-to-peer software, personal web servers and other new uses.

How does information travel through the Internet?How does information travel through the Internet?Data is divided up into packetsData routes across the Internet can be switched to avoid congestionEntire mechanism is handled by the TCP/IP protocolsThe Internet is based on packet-switched protocols. Information is carried in packets, which can be imagined as small parcels being passed from computer to computer. Large chunks of data are usually broken up into several smaller packets before being sent through the network. The delivery mechanism, or protocol, that is used to encode the packet ensures safe transit, and provides a way of reconstructing the data when it reaches its destination. The protocols used on the Internet are referred to as TCP/IP, standing for Transmission Control Protocol / Internet Protocol.

As a switched network, the physical connections between computers do not matter as far as Internet traffic is concerned the protocols ensure that guaranteed information delivery is more important than speed or use of a particular route. This means that a sequence of packets might arrive out of order, with some travelling through the net by a faster, shorter route than others. TCP/IP provides the means for your software to piece together those packets into meaningful data. The ability to take different routes through the network is a fundamental part of the original design of TCP/IP, as it allows the Internet to route around damaged areas of the network. The Internet in the Academic World

How the University connects... via the Joint Academic NETwork (JANET) which is managed by UKERNA which provides a high-speed dedicated backbone

The University has a permanent Internet connection, which connects it to the JANET (Joint Academic NETwork). JANET is maintained by UKERNA (UK Education and Research Networking Association), which in turn is part of JISC (the Joint Information Services Committee).

The JANET connection is a high speed, permanent connection over a leased line, which means that, whilst expensive to maintain, it provides enough bandwidth to cope with a large institution and is relatively reliable.

Be careful!

Because the connection is funded and provided by government bodies, there are various conditions implied when you connect. Don't forget to read the terms and conditions!

Connecting using an ISP

Internet Service Provider ... extends the Internet into your computer

An ISP, or Internet Service Provider, is a company that provides you with a point of access to the Internet. When you connect to your ISP, your computer (or your own network) becomes an extension of the Internet itself whilst you remain connected.How does the connection work from home?

Modems and routers Negotiating a connection

To connect from home you need several things. Apart from a computer (obviously!) you'll need a phone connection, a modem or ADSL router, and some Internet software. Things will be easier if you're using a relatively recent operation system, such as Windows Vista/XP or MacOSX, but it's possible to connect with older or more obscure systems. With a modem and the appropriate software, you can dial up another modem connected to another computer, and establish a network connection with it. Usually, this computer is linked into the Internet, and so you're online.

With an ADSL modem or router, a similar procedure happens, but a filter splits the telephone line into voice and data (low and high frequencies) and your router negotiates a connection with the ADSL equipment in the telephone exchange.

Choosing an ISPFrequencies used on an ADSL line: PSTN is the normal telephone ("voice") usage, and the upstream/downstream areas are for data. Note the unequal proportions of the data range (i.e. Assymetric DSL)

Choosing an ISP

Dialup, broadband or mobile? Occasional or extensive use? Tied to single line, or available anywhere?

Within the University, the computers are connected permanently to the Internet. If you want to connect from home, you'll need to connect temporarily to an Internet Service Provider, or ISP, each time you need to access Internet resources. Setting this up is a fairly painless process, though you need to choose your ISP carefully.

What to look for. The first decision to make is the type of connection you want. If you're a very occasional user, then getting a dialup connection is still often the cheapest and simplest. It's also useful if you travel around a lot, as it's not (usually) tied to a particular phone line/number.

Choosing a broadband provider

Most people, however, will want a broadband connection, because it gives a reliable, almost instant connection (or 'always-on' operation) at a high bandwidth. You might also consider a wireless connection using data over a mobile phone network. These offer the ultimate mobile solution, but can be very expensive, often charging per megabyte ofdownload.

Choosing a broadband provider

Reliability, speed, contention ratio, cost Download limits and fair use

For broadband ISPs, there are several important factors to check, including reliability, speed of connection, how many other customers share the total bandwidth (the Contention Ratio), and of course, cost. Most charge a set-up cost, and many have a minumum contract period, so be careful you don't get locked into a poor deal for many months!

There are now also variable packages, where you can control the amount of bandwidth available, paying extra for more capacity if you need it. For more recommendations and relatively independent advice I find ThinkBroadband [http://www.thinkbroadband.com/] (formerly ADSLGuide.org.uk) useful.

A recent development is the capping of Internet connections by limiting the monthly downloads to, say, 10GB. This may seem reasonable at first, but if you wish to listen to Internet radio or download video clips from the BBC, for example, then you'll hit this limit sooner than you expect.Check whether your ISP offers an unlimited or unmetered service.

How fast? How reliable?

Balance speed, reliability and extra featuresThink about your typical usageDon't get locked into a long contractKeep a separate emailbox

Another thing to look out for is the speed and reliability of the connection. This is partly dependent upon the speed of your modem and your computer (see above), but also depends on Connecting through the University

your ISPs facilities too. Again it's worth shopping around to see which service provides fastest access, and the quickest, most reliable connection. There are a number of websites that run independent tests and surveys on each of the major ISPs, so there's no shortage of advice!It's also worth shopping around for extras, such as webspace and email boxes, domain names,and even telephone deals.

Remember, though, that if you use your ISP's email facilities, your email address will changeeach time you change your ISP; it's often better to have a separate, permanent account from anindependent email provider, such as Microsoft's hotmail [http://www.hotmail.com/] or Google'sgmail [http://mail.google.com/mail/help/intl/en/about.html].

Connecting through the University

Basic dial-up service ResNet in student halls/accommodation For accessing the Uni network, Virtual Private Network is better

You can use the University as your ISP. Check the DialUp page [http://www.its.ex.ac.uk/dialup/] for more details.

If you live in University-run accommodation that has a built-in network connection, you can also connect to ResNet [http://www.its.ex.ac.uk/resnet/], the University's residential network. For a small(ish) fee, currently 70 per year, you get an always-on connection into the campus network. Note that this is only a limited service; you get full web and email access, but other services such as chat, filesharing or multimedia streaming may be limited.

Whenever you connect to the campus network you're also bound by the University's rules and regulations [http://www.its.ex.ac.uk/regs.shtml], so don't do anything naughty - someone may be watching!

Configuring your computer Your ISP should provide an installation CD Should also provide settings for manual configuration

Measuring BandwidthIf you're using your own PC, you'll need to configure networking for your operating system (eg Windows XP). The easiest way to do this is to obtain a CD with the tools and settings combined--- most ISPs give these away free. If you know all the details of the connection (usually obtainable from the ISP's tech-support website), you can set up the connection by hand, but this is often not for the faint-hearted!

There are some hints on configuring Windows for the University's dialup [http:// www.its.ex.ac.uk/dialup/] and ResNet [http://www.its.ex.ac.uk/resnet/] services on the IT Services website (the ResNet pages are particularly good).

Measuring Bandwidth

basic unit is the bit per second megabits per second (Mb/s) more commonly used a megabit is around a million bits Don't confuse with megabytes per second (MB/s)

divide Mb/s by 8 to get MB/s

Though the speed and quality of links are not the most important factors for Internet traffic, they will still affect your use of the net. In particular, you'll notice the difference (hopefully) between connecting on Campus, and connecting from home using a modem. Modems are described by their bandwidth; a typical analogue modem may have a bandwidth (or speed) of 56kb/s (kilobits per second), and a broadband modem anything between 256 to 2048 kb/s. This compares to the campus ethernet network, which has bandwidths of between 10 and 2000 Mb/s (megabits per second). Of course, on the campus ethernet, this bandwidth is often shared between many users (eg all computers in a single building) whereas the bandwidth of your analogue modem at home is exclusively yours. Broadband (DSL) connections often state how many others you'll be sharing your bandwidth with - this is called the Contention Ratio.

Mind your bits and bytes

A bit is a single binary digit (a zero or a one). A kilobit (kb) is about thousand bits (actually 1024, or 2 to the power 10), and a megabit (Mb) is around a million bits (1024 x 1024, or 2 to the power 20). You're probably more familiar with bytes, which are a group of eight bits, and can represent a single character or digit. Hard disk drives, for example, are measured in megabytes (MB - very small), gigabytes (GB) or terabytes (TB - very large) - note that in abbreviations, bytes are capital B's and bits are lower case!Who governs/regulates/controls the Internet?Who governs/regulates/controls theInternet?

A collective free-for-all? A collaborative technocracy? A commercial communications network?

This is a difficult question! The Internet grew as a collaborative network of researchers keen to share their discoveries in a simple, accessible way. Because of this, there was no real need to regulate or control the Internet; the information was already free and was of interest only to other researchers, so it didn't need protection. But as the Internet has grown, it has become a more commercial, public entity, and some who use it now wish it to be governed and policed to prevent certain types of abuse.

However, there are various bodies that govern parts of the Internet, which we'll look at in the next few paragraphs.

Domain names

Map numeric addresses to mnemonic names Allocated first-come, first-served (usually) One of first areas of dispute over control

Internet Protocol AddressesInternet Protocol Addresses System of unique numbers needed to find each host Managed by the Internet Assigned Numbers Authority (IANA)

Other bodies and institutions Internet Society (ISOC) oversees other Internet organisations Internet Architecture Board (IAB) manages technical direction of the Internet Internet Engineering Task Force (IETF) standardises technical developments (through RFCs)

Section II Introduction to JavaJava : A simple, object-oriented, distributed interpreted, robust, secure, architecture neutral, portable, high-performance, multi-threaded and dynamic language.- The Java Language: A White Paper Sun Microsystems Java applets were a breakthrough in interactive content on the Web, and many top sites used them to deliver news, present information, and attract visitors. There are still thousands of applets on the Web today. First used to create simple programs on World Wide Web pages, Java can be found today in each of the following places and many more: Web servers Relational databases Mainframe computers Telephones Orbiting telescopes Personal digital assistants Credit card-sized smartcardsAlthough Java remains useful for Web developers trying to enliven sites, it extends far beyond the Web browser. Java is now a popular general-purpose programming language, and some surveys indicate that there are more professional Java programmers than C++ programmers.

FEATURES OF JAVAJava Is Object-OrientedObject-oriented programming also called OOP is a way of conceptualizing a computer program as a set of separate objects that interact with each other. An object contains both information and the means of accessing and changing that information an efficient way to create computer programs that can be improved easily and used later for other tasks. Java inherits many of its object-oriented concepts from C++ and borrows concepts from other objectoriented languages as well.

Java Is Easy to LearnJava was intended to be easier to write, compile, debug, and learn than other object-oriented languages. It was modeled strongly after C++ and takes much of its syntax from that language. Despite Javas similarities to C++, the most complex and error-prone aspects of that language have been excluded from Java. You wont find pointers or pointer arithmetic because those features are easy to use incorrectly in a program and even harder to fix. Additionally, memory management is handled automatically by Java rather than requiring the programmer to allocate and deallocate memory, and multiple inheritance is not supported. Although Java is easier to learn than many other programming languages, a person with no programming experience at all will find Java challenging. It is more complicated than working in something such as HTML or JavaScript, but definitely something a beginner can accomplish.

Java Is Platform NeutralBecause it was created to run on a wide variety of devices and computing platforms, Java was designed to be platform neutral, working the same no matter where it runs. The original goal for Java programs to run without modification on all systems has not been realized. Java developers routinely test their programs on each environment they expect it to be run on, and sometimes are forced into cumbersome workarounds as a result. However, Javas platform-neutral design still makes it much easier to employ Java programs in a diverse range of different computing situations. As with all high-level programming languages, Java programs are originally written as source code, a set of programming statements entered into a text editor and saved as a file.

When you compile a program written in most programming languages, the compiler translates your source file into machine code (Object Code) instructions that are specific to the processor your computer is running. If you compile your code on a Windows system, the resulting program will run on other Windows systems but not on Macs or other machines. If you want to use the same program on another platform, you must transfer your source code to the new platform and recompile it to produce machine code specific to that system. In many cases, changes to the source will be required before it will compile on the new machine, because of differences in its processors and other factors. Java programs are compiled into machine code for a virtual machine a sort of computer-within-acomputer. This machine code is called bytecode, and the virtual machine interprets this code by convertingit into a specific processors machine code. The virtual machine is more commonly known as the Java interpreter, and every environment that supports Java must have an interpreter tailored to its own operating system and processor. Java also is platform neutral at the source level. Java programs are saved as text files before they are compiled, and these files can be created on any platform that supports Java. For example, you could write a Java program on a Windows 98 machine, upload it to a Linux machine over the Internet, and then compile it. Java interpreters can be found in several places. For applets, the interpreter is either built into a Javaenabled browser or installed separately as a browser plug-in. The interpreter does cause some significant performance issues as a rule, Java bytecode executes more slowly than platform-specific machine code produced by a compiled language such as C or C++.

Sun, IBM, Symantec and other Java developers are addressing this with technology such as HotSpot, a new faster virtual machine included with Java 2, and compilers that turn bytecode into platform-specific machine code. Every new generation of processors also increases Javas sometimes-laggard performance. The architecture neutral (or platform independent) feature of Java makes it highly suitable for Internet programming. The way it happens with Java: your source code is translated to machine code (called Bytecode) for an imaginary machine - the Java Virtual Machine (JVM). Figure 2.2 shows compilation of a Java program on different machines.

Error handlingError handling in C is a notorious problem, and one that is often ignoredfinger-crossing is usually involved. If youre building a large, complex program, theres nothing worse than having an error buried somewhere with no clue as to where it came from. Java exception handling is a way to guarantee that an error is noticed, and that something happens as a result.

DistributedJava is designed as a distributed language for creating applications on networks. It has the ability to share both data and programs. Java applications can open and access remote objects on Internet as easily as they do in a local system. This enables multiple programmers at multiple remote locations to collaborateand work together on a single object.

MultithreadedJava supports multithreaded programs. This means that we need not wait for the application to finish one task before starting another. For example, we can listen to an audio clip while scrolling down a page and at the same time download an applet from a distant computer. This feature improves the interactive performance of graphical applications.

JAVA ENVIRONMENTJava environment includes a large number of development tools and hundreds of classes and methods. The development tools are part of system known as Java Development Kit (JDK) and the classes and methods are part of the Java Standard Library, also known as Application Programming Interface (API).javac is the java compiler. It creates bytecode for applications, applets and servlets. The file containing your java source code must end with the file extension .java. The output (bytecode) is stored in one or more files with a .class extensionjava is the Java interpreter. To run an application you must enter the java command followed by the name of the class you want to run (and any command line arguments you want to pass to the program). appletviewer is the utility that runs applets outside a Web browser. You must follow the command with the name of the html document file with tag. jdb is the Java debugger. It has limited functionality. You may find it more useful to include System.out.println statements in your program. javadoc generates a collection of HTML documents that make up online documentation for the classes used in your application. You need to include javadoc comments including tags in your source code to fully utilize this tool.native2ascii is a tool which converts the files from Unicode to ASCII. Useful if you are developing software for the international market.jar is a utility which combines several files into a single Java archive (JAR) file - known as .jar files. A JAR file is like a zip file except that the data is not always compressed and is convenient for distribution. It can combine resources such as sound clips or graphics together with the files that use them. Downloading one JAR file is much more efficient than downloading related files separately.

Steps used to compile a Java Program areStep 1: Create a text file and store Java source code with the extension as .java.Step 2: Use javac, JAVA compiler to get the class fileStep 3: Use java, Interpreter to get the output.

VERSIONS OF JAVASun has released four major versions of the Java language: Java 1.0 A small Web-centered version uniformly available in all popular Web browsers Chapter 26 2 - Java Evolution Java 1.1 A 1997 release with improvements to the user interface, completely rewritten event handling, and a component technology called JavaBeans Java 2 with SDK 1.2 A significantly expanded version released in 1998 with retooled graphical user interface features, database connectivity, and many other improvements Java 2 with SDK 1.3 A 2000 release that adds new core features such as improved multimedia, more accessibility, and faster compilation A Java development kit has always been available at no cost from Suns Java Web site, and thisavailability is one of the factors behind the languages rapid growth. It is the first development tool that supports new versions of Java, often six months to a year before other Java development software.

JAVA PACKAGESA package is a collection of classes which logically fit together and which may interact between themselves. applet - for creating Java programs to run on the Web awt - the original toolkit for graphics and graphical user interfacing swing - extensive set of lightweight components built on top of awt event - for managing program events io - for managing program input and output lang - for routine functions net - for networking util - for additional useful utilities

PROGARM STRUCTUREA java program may contain many classes of which only one class defines a main method. Classes contain data members and methods that operate on the data members of the class. A java program may contain one or more sections as shown in the figure 2.4.Documentation SectionThis section comprises of a set of comment lines giving the names of the program, author and other relevant details about the program. Documentation comment uses /** and */ . This form of comment is used for generating HTML documentation automatically.Package SectionThis statement declares the package name and informs the compiler that the classes defined here belong to this package. Example package packageName;The package statement is optional.Import StatementsSimilar to #include in C/C++ we have import statements in JAVA. This statement instructs the interpreter to load the classes contained in the package specified.import student.*;The above statement instructs the interpreter to load all the classes in the package named student. If the import statement is as follows: import student.PGstudents;Then it instructs the interpreter to load a specific class named PGstudents from the package student. By default all java programs import java.lang.* package. If any other packages are required only then import statements need to be used.Interface StatementAn interface is like a class but includes a group of method declarations. This is also an optional statement and used only when required.Class DefinitionsA java program may contain multiple class definitions. Classes are primary and essential elements of java program. These classes are used to map the objects of real-world problems.Main Method ClassSince every java stand-alone program requires a main method as its starting point, this class is essential part of any Java program.

Applet ProgrammingINTRODUCTIONEvery applet is implemented by creating a subclass of the Applet class. The following figure shows the inheritance hierarchy of the Applet class.

The Simplest Java AppletThe Java programming language and libraries enable you to create applets that are as simple or as complex as you like. In fact, you can write the simplest Java applet in only a few lines of code.MyApplet.java: The Simplest Java Applet.import java.applet.*;public class MyApplet extends Applet{}The first line of Listing tells the Java compiler that this applet will be using some or all of the classes defined in the applet package (the asterisk acts as a wildcard, just as in DOS file names). All of the basic capabilities of an applet are provided for in these classes, which is why you can create a usable applet with so few lines of code. The second line of code declares a new class called MyApplet. This new class is declared as public so that the class can be accessed when the applet is run in a Web browser or in the Appletviewer application. If you fail to declare the applet class as public, the code will compile fine, but the applet will refuse to run. In other words, all applet classes must be public. As you can see, you take advantage of object-oriented programming (OOP) inheritance to declare your applet class by subclassing Javas Applet class. The only difference is that Applet is a class thats included with the Java Developers Kit (JDK), rather than a class you created yourself. Compile the applet shown to get the MyApplet.class file, which is the byte-code file that can be executed by the Java system. To run an applet, just create an HTML document. If you were to run the MyApplet applet, however, you wouldnt see anything much in Appletviewer or in your Web browser.

The APPLET TagWhen you build tags, keep in mind that words such as APPLET and CODEBASE can be typed in either as shown or in any mixture of uppercase and lowercase. Bold font indicates something you should type in exactly as shown (except that letters dont need to be uppercase). Italic font indicates that you must substitute a value for the word in italics. Square brackets ([ and ]) indicate that the contents of the brackets are optional.< APPLET[CODEBASE = codebaseURL]CODE = appletFile //mandatory[ALT = alternateText][NAME = appletInstanceName]WIDTH = pixels //mandatoryHEIGHT = pixels //mandatoryChapter 9 158 - Applet ProgrammingPDF created with pdfFactory Pro trial version www.pdffactory.com[ALIGN = alignment][VSPACE = pixels][HSPACE = pixels]>[< PARAM NAME = appletParameter1 VALUE = value >][< PARAM NAME = appletParameter2 VALUE = value >]. . .[alternateHTML]

CODEBASE = codebaseURLThis optional attribute specifies the base URL of the applet the directory or folder that contains the applets code. If this attribute is not specified, then the documents URL is used.CODE = appletFileThis required attribute gives the name of the file that contains the applets compiled Applet subclass. This file is relative to the base URL of the applet. It cannot be absolute.ALT = alternateTextThis optional attribute specifies any text that should be displayed if the browser understands the APPLET tag but cant run Java applets.NAME = appletInstanceNameThis optional attribute specifies a name for the applet instance, which makes it possible for applets on the same page to find (and communicate with) each other.WIDTH = pixelsHEIGHT = pixelsThese required attributes give the initial width and height (in pixels) of the applet display area, not counting any windows or dialogs that the applet brings up.ALIGN = alignmentThis optional attribute specifies the alignment of the applet. The possible values of this attribute are the same (and have the same effects) as those for the IMG tag: left, right, top, texttop, middle, absmiddle, baseline, bottom, absbottom.VSPACE = pixelsHSPACE = pixelsThese optional attributes specify the number of pixels above and below the applet (VSPACE) and on each side of the applet (HSPACE). Theyre treated the same way as the IMG tags VSPACE and HSPACE attributes.< PARAM NAME = appletParameter1 VALUE = value > tags are the only way to specify applet-specific parameters. Applets read user-specified values for parameters with the getParameter() method.alternateHTMLIf the HTML page containing this tag is viewed by a browser that doesnt understand the tag, then the browser will ignore the and tags, instead interpreting any other HTML code between the and tags. Java-compatible browsers ignore this extra HTML code.Here is an example HTML document for the applet MyAppletMYAPPLET.html: MyApplets HTML Document.Applet Test PageApplet Test Page

LIFE CYCLE OF AN APPLETEvery Java applet you create inherits a set of default behaviors from the Applet class. In most cases, these default behaviors do nothing, unless you override some of Applets methods in order to extend the Chapter 9 160 - Applet Programming applets basic functionality. However, although a simple applet like MyApplet doesnt seem to do much, alot is going on in the background. Figure 9.2 shows different stages in the life cycle of an Applet.

There are five parts to this cycle, each of which has a matching method that you can override to gain access to that cycle of the applets life. The five stages of an applets life cycle are listed here: Initialization stage. This is the part of an applets life cycle in which the applet object is created and loaded. At this point, its appropriate to create objects needed by the applet, as well as initialize v alues that must be valid when the applet runs. The initialization stage occurs only once in the applets life cycle. You can tap into the initialization stage by overriding the Applet classs init() method. Start stage. This stage occurs when the system starts running the applet. The start stage can occur right after the initialization stage or when an applet is restarted. This usually happens when the user switches back to the applets page after viewing a different page in his or her Web browser. Unlike the initialization stage, the start stage can occur several times over the life of the applet. To provide your own start code, override the Applet classs start() method. Paint stage. The paint stage occurs whenever the applets display must be drawn on the screen. This happens right after the applets start stage, as well as whenever the applets display must be restored or changed. This can happen when the applet is exposed fromunderneath another window or when the program changes the applets display in some way and explicitly repaints the applet. Almost every applet you write will have a paint() method, which is the method you override to provide your applet with its display. Stop stage. As you may have guessed, the stop stage is the counterpart to the start stage. Java executes this stage of the applets life cycle when the applet is no longer visible on the screen, such as when the user switches to a different Web page. The default behavior for this cycle, however, is to keep the applet running in the background. If you want to handle the stop cycle differently, you should override the Applet classs stop() method. Destroy stage. This is the counterpart to the initialization stage and occurs when the system is about to remove the applet from memory. Like the initialization cycle, the destroy cycle occurs only once. If your applet has resources that need to be cleaned up before the applet exits, this is the place to do it. You tap into this cycle by overriding the Applet classs destroy() method.

Example: Overriding the Life Cycle MethodsAll this talk about life cycles and overriding methods may have left you a little confused as to how all this actually applies to the applets you want to create. In previous chapters, you managed to create applets without dealing with most of this stuff because the Applet class, from which you derived your own applet classes, handled the life-cycle methods in the default manner proscribed by the Java system. If you look at Listing 15.3, youll see a small applet that overrides all the methods needed to provide custom behaviors for all the applets life-cycle stages.

Overriding the Applet Life-Cycle Methods.import java.applet.*;import java.awt.*;public class MyApplet2 extends Applet{public void init(){// Place initialization cycle code here.}public void start(){// Place start cycle code here.}public void paint(Graphics g){// Place paint cycle code here.}public void stop(){// Place stop cycle code here.}public void destroy(){// Place destroy cycle code here.}}Notice that in order to override the paint() method, you must import the java.awt.* libraries, which contain information about the Graphics class. As you learned when writing previous applets in this book, the Graphics class enables you to display information and graphics in an applets display area. If you look for the previous methods in Javas source code, youll discover that the default implementations of init(), start(), paint(), stop(), and destroy() all do nothing at all. If you want your applet to do something in response to these cycles, you have to provide the code yourself by overriding theappropriate method.

LOCAL AND REMOTE APPLETSOne of Javas major strengths is that you can use the language to create dynamic content for your Web pages. That is, thanks to Java applets, your Web pages are no longer limited to the tricks you can perform with HTML. Now your Web pages can do just about anything you want them to. All you need to do is write the appropriate applets. But writing Java applets is only half the story. How your Web pages users obtain and run the applets is equally as important. Its up to you to not only write the applet (or use someone elses applet), but also to provide users access to the applet. Basically, your Web pages can contain two types of applets: local and remote. In this section, you learn the difference between these applet types, which are named after the location at which they are stored.

Local AppletsA local applet is one that is stored on your own computer system. When your Web page must find a local applet, it doesnt need to retrieve information from the Internet-in fact, your browser doesnt even need to be connected to the Internet at that time.

Specifying a Local Applet.

The codebase attribute specifies a path name on your system for the local applet, whereas the code attribute specifies the name of the byte-code file that contains the applets code. The path specified in the codebase attribute is relative to the folder containing the HTML document that references the applet.

Remote AppletsA remote applet is one that is located on another computer system. This computer system may be located in the building next door or it may be on the other side of the world-it makes no difference to your Java-compatible browser. No matter where the remote applet is located, its downloaded onto your computer via the Internet. Your browser must, of course, be connected to the Internet at the time it needs to display the remote applet. To reference a remote applet in your Web page, you must know the applets URL (where its located on the Web) and any attributes and parameters that you need to supply in order to display the applet correctly. If you didnt write the applet, youll need to find the document that describes the applets attributes and parameters. The applets author usually writes this document.Specifiying a Remote Applet.

The only difference between local applet and remote applet accessing is the value of the codebase attribute. In the first case, codebase specifies a local folder, and in the second case, it specifies the URL at which the applet is located.

CREATING AN APPLETImporting Classes and PackagesThe first two lines of the following listing import two classes used in the applet: Applet and Graphics.import java.applet.Applet;import java.awt.Graphics;public class HelloWorld extends Applet {public void paint(Graphics g) {g.drawString(Hello world!, 50, 25);}}If you removed the first two lines, the applet could still compile and run, but only if you changed the rest of the code like this:public class HelloWorld extends java.applet.Applet {public void paint(java.awt.Graphics g) {g.drawString(Hello world!, 50, 25);}}As you can see, importing the Applet and Graphics classes lets the program refer to them later without any prefixes. The java.applet. and java.awt. prefixes tell the compiler which packages it should search for the Applet and Graphics classes. Both the java.applet and java.awt packages are part of the core Java API API that every Java program can count on being in the Java environment. The java.applet package contains classes that are essential to Java applets. The java.awt package contains the most frequently used classes in the Abstract Window Toolkit (AWT), which provides the Java graphical user interface (GUI). Besides importing individual classes, you can also import entire packages. Heres an example:import java.applet.*;import java.awt.*;public class HelloWorld extends Applet {public void paint(Graphics g) {g.drawString(Hello world!, 50, 25);}}In the Java language, every class is in a package. If the source code for a class doesnt have a package statement at the top, declaring the package the class is in, then the class is in the default package. Within a package, all classes can refer to each other without prefixes. For example, the java.awt Component class refers to the java.awt Graphics class without any prefixes, without importing the Graphics class.

Defining an Applet SubclassThe first bold line of the following listing begins a block that defines the HelloWorld class. import java.applet.Applet;import java.awt.Graphics;public class HelloWorld extends Applet {public void paint(Graphics g) {g.drawString(Hello world!, 50, 25);}}The extends keyword indicates that HelloWorld is a subclass of the class whose name follows: Applet. From the Applet class, applets inherit a great deal of functionality. Perhaps most important is the ability to respond to browser requests. For example, when a Java-capable browser loads a page containing an applet, the browser sends a request to the applet, telling the applet to initialize itself and start executing. An applet isnt restricted to defining just one class. Besides the necessary Applet subclass, an applet can define additional custom classes. When the applet attempts to use a class, the application thats executing the applet first looks on the local host for the class. If the class isnt available locally, its loaded from the location that the Applet subclass originated from.

Implementing Applet MethodsThe bold lines of the following listing implement the paint method.import java.applet.Applet;import java.awt.Graphics;public class HelloWorld extends Applet {public void paint(Graphics g) {g.drawString(Hello world!, 50, 25);}}Every applet must implement one or more of the init, start, and paint methods. Besides the init, start, and paint methods, applets can implement two more methods that the browser calls when a major event occurs (such as leaving the applets page): stop and destroy. Applets can implement any number of other methods, as well. Returning to the above code snippet, the Graphics object passed into the paint method represents the applets onscreen drawing context. The first argument to the Graphics drawString method is the string to draw onscreen. The second and third arguments are the (x,y) position of the lower left corner of the text onscreen. This applet draws the string Hello world! starting at location (50,25). The applets coordinate system starts at (0,0), which is at the upper left corner of the applets display area.

Running an AppletThe bold lines of the following listing comprise the tag that includes the Hello Worldapplet in an HTML page.

MSIT 13 Oops with Java 167PDF created with pdfFactory Pro trial version www.pdffactory.com A Simple Program

Here is the output of my program:

The above tag specifies that the browser should load the class whose compiled code is in the file named HelloWorld.class. The browser looks for this file in the same directory as the HTML document that contains the tag. When the browser finds the class file, it loads it over the network, if necessary, onto the computer the browser is running on. The browser then creates an instance of the class. If you include an applet twice in one page, the browser loads the class file once and creates two instances of the class. The WIDTH and HEIGHT attributes are like the same attributes in an tag: They specify the size in pixels of the applets display area. Most browsers do not let the applet resize itself to be larger or smaller than this display area. For example, every bit of drawing that the Hello World applet does in its paint method occurs within the 150x25-pixel display area that the above tag reserves for it.

HELLOWORLD APPLETNow you will create a Java applet called HelloWorld, which also displays the greeting Hello world!. Unlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, Netscape Navigator, or Microsoft Internet Explorer. To create this applet, youll perform the basic steps as before: create a Java source file; compile the source file; and run the program.

a. Create a Java Source File.Again, you have two options: You can save the files HelloWorld.java and Hello.html on your computer and avoid a lot of typing. Then, you can go straight to step b. Or, you can follow these instructions:1. Start NotePad. Type the following code into a new document:import java.applet.*;import java.awt.*;/*** The HelloWorld class implements an applet that* simply displays "Hello World!".*/public class HelloWorld extends Applet {public void paint(Graphics g) {// Display "Hello World!"g.drawString("Hello world!", 50, 25);}}Save this code to a file called HelloWorld.java.2. You also need an HTML file to accompany your applet. Type the following code into a new NotePad document:

A Simple Program

Here is the output of my program:

Save this code to a file called Hello.html.b. Compile the Source File.At the prompt, type the following command and press Return:javac HelloWorld.javaThe compiler should generate a Java bytecode file, HelloWorld.class.MSIT 13 Oops with Java 169PDF created with pdfFactory Pro trial version www.pdffactory.comc. Run the Program.Although you can view your applets using a Web browser, you may find it easier to test your applets using the simple appletviewer application that comes with the JavaTM Platform. To view the HelloWorld applet using appletviewer, enter at the prompt:

WHAT APPLETS CAN AND CANT DOThis section gives an overview of both the restrictions applets face and the special capabilities they have.Security RestrictionsEvery browser implements security policies to keep applets from compromising system security. This section describes the security policies that current browsers adhere to. However, the implementation of the security policies differs from browser to browser. Also, security policies are subject to change. For example, if a browser is developed for use only in trusted environments, then its security policies will likely be much more lax than those described here. Current browsers impose the following restrictions on any applet that is loaded over the network: An applet cannot load libraries or define native methods. It cannot ordinarily read or write files on the host thats executing it. It cannot make network connections except to the host that it came from. It cannot start any program on the host thats executing it. It cannot read certain system properties. Windows that an applet brings up look different than windows that an application brings up.Each browser has a SecurityManager object that implements its security policies. When a SecurityManager detects a violation, it throws a SecurityException. Your applet can catch this SecurityException and react appropriately.

Applet CapabilitiesThe java.applet package provides an API that gives applets some capabilities that applications dont have. For example, applets can play sounds, which other programs cant do yet. Here are some other things that current browers and other applet viewers let applets do: Applets can usually make network connections to the host they came from. Applets running within a Web browser can easily cause HTML documents to be displayed. Applets can invoke public methods of other applets on the same page. Applets that are loaded from the local file system (from a directory in the users CLASSPATH) have none of the restrictions that applets loaded over the network do. Although most applets stop running once you leave their page, they dont have to.

INTRODUCTIONObject Oriented Programming (OOP) is an approach to program organization and development, which attempts to eliminate some of the pitfalls of conventional programming methods by incorporating the best of structured programming features with several new concepts. The world is object-oriented, and the object-oriented programming paradigm attempts to express computer programs in ways that model how people perceive the world. An introductory description of OOP can be based on the following guideline: The solution to the problem should resemble the problem, and observers of the solution should be able to recognize the problem without necessarily knowing about it in advance. A good example of this guideline from the computing world is the use of OOP to develop a stack class from which stack objects can be instantiated. If a stack is implemented as a class, instantiated as an object, and documented appropriately, programmers familiar with stacks, queues, and other similar data structures will recognize it as a stack without other prior knowledge.We are object-oriented creatures living in an object-oriented world. We tend to think in object-oriented ways. Previous approaches to programming tend to separate the data from the methods used to manipulate that data, or at least dont strongly encourage them to be considered in concert. The world and its applications are not organized into values and procedures separate from one another. People who solve problems in other crafts do not perceive the world that way. They deal with their problem domains by concentrating on the objects and letting the characteristics of those objects determine the procedures to apply to them.

BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMINGObjectsIn the real world, objects are the entities of which the world is comprised. Everything that happens in the world is related to the interactions between the objects in the world. The real world consists of many objects interacting in many ways. While each object may not be overly complex, their myriad of interactions creates the overall complexity of the natural world. It is this complexity that we wish to capture in our software systems. In an object-oriented software system, objects are entities used to represent or model a particular piece of the system. Objects are the primary units used to create abstract models. An object is characterized solely by it behaviors. Essentially this defines an object by the way it interacts with its world. An object that does not interact with anything else effectively does not exist. Access to internally stored data is necessarily through some sort of defined behavior of the object. It is impossible for an outside entity to truly know whether or not a particular piece of data is being stored inside of another object. This does not mean however, that an object may not contain data (information) in fields. The essence of the object is in how the object behaves in relationship to or as a result of its data, should it contain any. The existence of data in an object is an implementation technique used to generate the required behavior of that object.Everything is an object. Think of an object as a fancy variable; it stores data, but you can make requests to that object, asking it to perform operations on itself. In theory, you can take any conceptual component in the problem youre trying to solve (dogs, buildings, services, etc.) and represent it as an object in your program.A program is a bunch of objects telling each other what to do by sending messages. To make a request of an object, you send a message to that object. More concretely, you can think of a message as a request to call a method that belongs to a particular object.Each object has its own memory made up of other objects. Put another way, you create a new kind of object by making a package containing existing objects. Thus, you can build complexity into a program while hiding it behind the simplicity of objects.Every object has a type. Using the parlance, each object is an instance of a class, in which class is synonymous with type. The most important distinguishing characteristic of a class is What messages can you send to it?All objects of a particular type can receive the same messages. This is actually a loaded statement, as you will see later. Because an object of type circle is also an object of type shape, a circle is guaranteed to accept shape messages. This means you can write code that talks to shapes and automatically handle anything that fits the description of a shape. This substitutability is one of the powerful concepts in OOP.

ClassesMany objects differ from each other only in the value of the data that they hold. For example, both a red crayon and a blue crayon are crayons; they differ only in the value of the color attribute, one has a red color and the other a blue color. Our object-oriented system needs a way to capture the abstraction of a crayon, independent of the value of its color. That is, we want to express that a set of objects are abstractly equivalent, differing only in the values of their attributes and perhaps, thus differing in the behaviors that result from those values. Many objects are similar in many overall, generalized ways, differing only in smaller, more specific details. Object-oriented systems use classes to express abstract equivalence. A class is an abstract description of a set of objects. A class thus contains the descriptions of all the behaviors of the objects that it represents. In computer science parlance, we call the individual behaviors of a class its methods. In addition, a class may, but not always, contain descriptions of the internal data held by the objects, called its fields, as well as implementation details about its methods and fields. Turning the description around, we can say that a class is a template or recipe for the creation of a particular type of object. That is, one can use a class to create (instantiate) objects of the type described by the class. Be careful not to make the very beginners common mistake of equating classes and objects. A class is a specification of a set of objects; it is not the actual object.

MessagesA single object alone is generally not very useful. Instead, an object usually appears as a component of a larger program or application that contains many other objects. Through the interaction of these objects, programmers achieve higher-order functionality and more complex behavior. Software objects interact and communicate with each other by sending messages to each other. When object A wants object B to perform one of Bs methods, object A sends a message to object B.Sometimes, the receiving object needs more information so that it knows exactly what to do; for example, when you want to change gears on your bicycle, you have to indicate which gear you want. This information is passed along with the message as parameters. Messages provide two important benefits.An objects behavior is expressed through its methods, so (aside from direct variable access) message passing supports all possible interactions between objects.Objects dont need to be in the same process or even on the same machine to send and receive messages back and forth to each other.

AbstractionThe implicit characteristic of an object-oriented program is Abstraction. Abstraction is the specification of an abstract data type, which includes a specification of the types data representation and behavior. In particular,what kind of data can be stored in an entity of the new type, andwhat are all the ways that that data can be manipulated.For our purposes, an abstract data type is a new type (not intrinsic to the language). It is not one of the primitive data types that are built into the programming language (such as int, long, float, etc.). The representation and behavior of an abstract type is not known to the compiler until the programmer specifies it and presented to the compiler in an appropriate manner.How do we present the specification of an abstract type to the compiler? Java programmers define the data representation and the behavior of a new type using the keyword class. In other words, in Java and C++, the keyword class is used to convert the specification of a new type into something that the compiler can work with. Once the new type is defined, one or more objects of that type can be brought into being (instantiated, caused to occupy memory). Once instantiated, the object is said to have state and behavior. The state of an object is determined by the current values of its data (instance variables) and the behavior of an object is determined by its methods (member functions or instance methods).

EncapsulationAnother major characteristic of an object-oriented program is encapsulation. If abstraction is the design or specification of a new type, then encapsulation is its definition and implementation.

A programmer encapsulates the data representation and behavior of an abstract data type into a class, thereby defining its implementation and interface. According to good object-oriented programming practice, an encapsulated design usually hides its implementation from the class user and reveals only its interface. This is accomplished in different ways with different languages as described below. Just as most of us dont usually need to care about how the steering mechanism of a car is implemented, a user of a class should not need to care about the details of implementation only that it works as advertised. Of course this assumes that the user of the class has access to good documentation describingthe class.

PolymorphismAn important aspect of OOP is polymorphism. This is a Greek word meaning something like one name, many forms. Polymorphism is used to customize the behavior of an instance of a type (an object) based on existing conditions. The purpose of polymorphism as it applies to OOP is to allow one name to be used to specify a general class of actions. Within a general class of actions, the specific action to apply in any particular instance is determined by the type of data involved. More generally, the concept of polymorphism is the idea of one interface, multiple methods. Polymorphism exists when functions are overloaded or overridden to cause them to perform operations not implicitly recognized by the compiler.

Inheritance: Reusing the interfaceBy itself, the idea of an object is a convenient tool. It allows you to package data and functionality together by concept, so you can represent an appropriate problem-space idea rather than being forced to use the idioms of the underlying machine. These concepts are expressed as fundamental units in the programming language by using the class keyword.It seems a pity, however, to go to all the trouble to create a class and then be forced to create a brand new one that might have similar functionality. Its nicer if we can take the existing class, clone it, and then make additions and modifications to the clone. This is effectively what you get with inheritance, with the exception that if the original class (called the base class or superclass or parent class) is changed, the modified clone (called the derived class or inherited class or subclass or child class) also reflects those changes.

BENEFITS OF OOPOOP offers several benefits to both program designer and the user. The new technology promises greater programmer productivity, better quality of software and lesser maintenance cost. The principal advantages are as follows:Easy to partition the work based on Objects.Easy to upgrade.Eliminates redundant code through Inheritance.Reusability leads to higher productivity.Software complexity can be easily managed.Software that is easy to use is hard to build. It is hoped that the object-oriented programming languages like C++ and Java would help manage this problem.

APPLICATIONS OF OOPOOP is useful in many areas of applications. Using the concepts of OOP we can solve any complex problem. The promising areas for application of OOP includes:Real time SystemsSimulation and ModelingObject Oriented DatabasesHypermediaAI and expert systemsCAD/CAM systemNeural networks etc.,It is believed that OOP environment will enable the software industry to improve not only the quality of software systems but also its productivity.

ConstructorsThe allocation, reclamation, and reuse of dynamic memory from the heap is an important aspect of most object-oriented programs, and some non-object-oriented programs as well. The next few sections discuss how these requirements are met with respect to objects in Java and C++. Other object-oriented language use other techniques to accomplish the same objectives: to allocate memory when it is needed by the program,to reclaim that memory when it is no longer needed, andto reuse it as appropriate.Failure to deal with this important issue results in a condition often referred to as memory leakage. Both Java and C++ and possibly other object-oriented languages as well, support the notion of a onstructor. The following Java code fragment shows a constructor at work. //instantiate an object of the class Oop01 in JavaOop01 obj = new Oop01();A constructor is a special method of a class that is used to instantiate (and optionally initialize) a new object of the class type. In the above statement, the invocation of the constructor method is highlighted in boldface. Constructors can be overloaded just like other methods in Java and C++. In this particular statement, the new operator is used to allocate dynamic memory from the heap, and the constructor is used to construct the object in that memory space. The address of the memory containing the object is returned and assigned to the reference variable named obj. If the memory cannot be allocated, an exception will be thrown.In Java and C++, if you do not define a constructor when you define a new class, a default constructor that takes no parameters is defined on your behalf. This is often referred to as the default constructor or the noarg constructor. It is also possible for you to define a constructor for your class which takes no arguments and which performs some special action when it is invoked. Defining a constructor is only slightly different from defining any other method in Java or C++ (it must have the same name as the class, does not have return type, and must not have a return statement). Although you are free to cause your constructor to perform just about any action that you want, the intended purpose of a constructor is to perform some form of initialization (open a file, initialize instance variable values, etc.) If you provide such a noarg constructor, it will be invoked in place of the default constructor when you invoke the constructor as shown in the above code fragment with no arguments. The constructor shown above is a Java constructor. The invocation of a constructor in C++ is even simpler. An example is shown below:Oop01 obj; //instantiate an object of the class Oop01 in C++C++ provides other formats for invoking the constructor in addition to that shown above. It is also possible for you to define one or more overloaded versions of the constructor that do take parameters. These are commonly called parameterized constructors. Typically you will include code in the body of the constructor to use the arguments passed as parameters for some sort of initialization, but again, you can write the code to perform just about any action that you want. The following code fragment shows the important parts of a Java program, similar to the previous one which has been modified to use a parameterized constructor.Oop02(int iV, int cV){ //parameterized constructorinstanceVariable = iV; //initialize the instance variableclassVariable = cV; //initialize the class variable}//end parameterized constructor...public static void main(String[] args){//instantiate an object of the class Oop02Oop02 obj = new Oop02(2,3);This code fragment shows the parameterized constructor method named Oop02 and then shows the statement used in the main method to instantiate and initialize an object of the class Oop02 named obj. As you can see, the parameterized constructor in Java looks just like a method except that it has no return type or return statement.

Adding a Constructor to a Class.class MyClass{int myField;public MyClass(int value){myField = value;}}As you can see, the classs constructor starts with the public keyword. This is important because you want to be able to create an object from the class anywhere in your program, and when you create an object, youre actually calling its constructor. After the public keyword comes the name of the constructor followed by the constructors arguments in parentheses. When you create an object of the class, you must also provide the required arguments. Example: Creating an Object by Calling a Constructor If you want to create an object from MyClass, you must supply an integer value that the class uses to initialize the myField data field. This integer is the MyClass constructors single argument. Youd create an object of the class like this:MyClass myObject = new MyClass(1);This line not only creates an object of the MyClass class, but also initializes the myField data field to 1. The first word in the line tells Java that myObject is going to be an object of the MyClass class. The next word is the objects name. After the equals sign comes the keyword new and the call to the classs constructor.Constructors areautomatically executed when an object is createdused to initialize instance variable belonging to the class -> good programming practice!may be overloaded to give alternative ways of initializing objectsEg Circle c = new Circle(5);Circle b = new Circle();should always provide a constructor for declaring an object with no arguments (builtin in Java 1.1)

Using ObjectsOnce youve created an object, you probably want to use it for something. You may need information from it, want to change its state, or have it perform some action. Objects give you two ways to do these things:1. Manipulate or inspect its variables.2. Call its methods.Referencing an Objects VariablesThe following is the general form of a qualified name, which is also known as a long name: objectReference.variableNameCalling an Objects MethodsYou also use qualified names to call an objects method. To form the qualified name of a method, you append the method name to an object reference, with an intervening period (.). Also, you provide, within enclosing parentheses, any arguments to the method. If the method does not require any arguments, use empty parentheses.objectReference.methodName(argumentList);orobjectReference.methodName();The garbage collector automatically cleans up unused objects. An object is unused if the program holds no more references to it. You can explicitly drop a reference by setting the variable holding the reference to null. This program ClassDemo.java demonstrates the usage of period to access the variable and method of a class.class ClassDemo{public static void main(String arg[]){cal ob=new cal();ob.set(); //referencing an objects methodob.disp();System.out.println(ob.add());System.out.println(ob.sub());}}class cal{int x,y;int add(){return(x+y);}int sub(){return(x-y);}void set(){x=10;y=5;}void disp(){System.out.println(x+\t+y);}}A destructor is a special method typically used to perform cleanup after the program no longer needsan object. C++ supports destructors, but Java does not support destructors. Other object-oriented languagesmay or may not support destructors.

Garbage CollectionJava supports another mechanism for returning memory to the operating system when it is no longer needed by an object: garbage collection. The garbage collector is a part of the runtime system that runs in a low-priority thread reclaiming memory that is no longer needed by objects used by the program. An object becomes eligible for garbage collection in Java when there are no longer any reference variables that reference the object. In Java, you can have one or more reference variables, which reference the same object. That object will not become eligible for garbage collection until all of those reference variables go out of scope, are assigned to a different object, or are assigned a value of null.

INSTANCE AND CLASS VARIABLESInstance VariablesInstance variables are those data members of a class that are defined such that every individual instance of the class (object) has its own set of variables, totally independent of the variables associated with all other objects of the same or different classes. In other words, each object has its own memory space where its own set of variables is stored. Because instance variables are bound to an object, they can be accessed only by way of the object to which they are bound. Assuming that access to an instance variable is not prohibited by access control mechanisms (such as the use of the keyword private), it is usually accessed by joining the name of the object (or the name of a pointer to the object) to the name of the instance variable using the appropriate joining operator. The joining operator for Java is a simple period (sometimes called the dot operator). The joining operator for C++ depends on whether the instance variable is being accessed using the name of the object or the name of a pointer to the object. When the name of the object is used, the joining operator is a simple period. When the name of a pointer to the object is used, the pointer operator (->) is used.Chapter 4 - Classes, 86 Objects and Methods Other languages may use different methods for accessing the instance variables of an object.

Class VariablesClass variables are those data members of a class that are shared among all objects of the class. Its not too far-fetched to think of them as quasi-global variables whose accessibility is restricted only to objects of a particular class, or to the class itself. In other words, only one copy of a class variable exists in memory and all objects of the class can access that copy. An important characteristic of class variables is that they can also be accessed without the requirement to instantiate an object of the type. In this case, they are usually accessed using the name of the class joined to the name of the variable using the appropriate joining operator. The joining operator for Java is a simple period. In Java and C++, class variables are designated as such using the static keyword. (Designation of a class variable in C++ also involves a requirement to re-declare the variable outside the class definition.) Also in Java and C++, member variables declared without the use of the static keyword are instance variables. In other words, by default, all member variables of a class are instance variables unless you designate them as class variables using the static keyword.

INSTANCE AND CLASS METHODSNote the following very important statements: The methods of a class have direct access to the member variables of the same class regardless of their access control designation such as public, private, or protected (except that class methods can usually access only class variables). There is no requirement for the code in a method of the class to use either the name of an object or the name of the class to access the member variables of the same class. The methods of a class come in two varieties: instance methods and class methods. As with instance and class variables, those methods designated static are class methods in Java and C++. Methods not designated static are instance methods.

Instance MethodsAn instance method can only be invoked by way of an object of the class. In that sense, an instance method is bound to an object. However, unlike an instance variable, an object normally doesnt have its own separate copy of an instance method. It would be wasteful of memory resources to provide a separate copy of every instance method for every object of a class. It is very important to understand that when an instance method is invoked on a particular object, and when the code in that method needs to access an instance variable of the class, it will access the particular copy of the instance variable belonging to the object on which it was invoked. It is this ability to temporarily bind the method to the instance variables of the object on which the method is invoked that causes it to behave as an instance method.

The this Pointer or ReferenceInstance methods in Java and C++ (and perhaps other object-oriented languages as well) exhibit another interesting characteristic. In particular, whenever an instance method is invoked, a pointer variable or reference variable named this comes into existence automatically. This reference variable refers to the object on which the method was invoked, and can be used by the code in the method for any purpose that a reference to that object might be needed.

Class MethodsClass methods can only access other class members (class variables or other class methods). They cannot access instance variables or instance methods. The most important thing about class methods is that they can be accessed using the name of the class without a requirement to instantiate an object of the class. As with class variables, class methods can be accessed by joining the name of the class to the name of the method using the appropriate joining operator.

Sample ProgramMuch of what we have been discussing can probably be better understood when seen in the context of an actual program. The following sample program illustrates the use of class and instance variables along with class and instance methods in a Java program. This is not an attempt to teach the Java programming language at this point. Rather, it is simply an attempt to illustrate OOP concepts using an actual Java program as the vehicle. As before, because of the access control complexity caused by the package concept in Java, and the desire to keep this sample program as simple as possible, no attempt was made to hide the implementation. When compiled and executed, this program will produce the following output on the standard output device. You might want to remember this place so that you can refer to it as you examine the program.A - Instance variable contains 5Chapter 4 - Classes, 88 Objects and MethodsB - Class variable contains 10C - Class variable contains 10Before we take a look at the complete program, lets examine some of the interesting code fragments that make up the program. The first interesting code fragment shows the declaration of two member variables of the class. One is a class variable named classVariable and the other is an instance variable named instanceVariable. int instanceVariable; //declare an instance variablestatic int classVariable; //declare a class variableThese are typical variable-declaration statements in Java and C++ consisting of the name of the type followed by the name of the variable. The important thing to note in the context of this discussion is the use of the statickeyword in the declaration of the class variable. The next code fragment shows the definitions of two methods (with the bodies of the methods deleted for brevity). One of these methods is a class method named classMethod and the other is an instancemethod named instanceMethod.void instanceMethod(){//define an instance method//body of method deleted for brevity} //end instanceMethod()static void classMethod(){//define a class method//body of method deleted for brevity} //end classMethod()Again, these are typical method or member function definitions for Java and C++ consisting of the name of the return type (where void means that nothing is returned) followed by the name of the method, followed by the formal argument list (which happens to be empty in this case). The body of the method is then enclosed within a matching pair of curly braces { }. Again, the important thing to note in the context of this discussion is the use of the static keyword in the definition of the class method. The next code fragment is a single statement taken from the body of one of the methods. This statement causes output to be displayed on the standard output device. This single statement incorporates classes, class variables, instance methods, and overloaded operators, and illustrates some of the syntactical complexity that can be encountered in object-oriented programming. System.out.println(A - Instance variable contains + instanceVariable);This is a Java statement. A completely different syntax would be required to achieve the same result in C++.Note first that this statement has three elements joined with periods. The first element is the word System which is the name of one of the classes in the standard Java class library. As background information, the System class is automatically loaded whenever a Java application is started. The name of the System class is joined to the word out using a period. The word out is the name of a member variable of the System class. The member variable named out is a public class variable. This makes it possible to access the variable using the name of the class and the name of the variable joined by the period. Note that the class variable named out is also joined to the word println using the period as the joining operator. The variable out is not only a class variable, it is also a reference variable (as opposed to a primitive variable) and it contains a reference to an object of the PrintStream class. The PrintStream class has an instance method named println(). In fact, there are ten overloaded versions of the println() method in the PrintStream class. The behavior of the version used here is to cause its string argument to be displayed on the standard output device.Now consider the string argument to the println method as shown below: (A - Instance variable contains + instanceVariable) In Java (and C++ as well), literal strings are enclosed in quotation marks. You will note that not everything in this argument is enclosed in quotation marks. Note in particular the plus sign near the middle of the argument. In Java, the plus sign is overloaded so that in addition to being used as an arithmetic addition operator, it is also used to concatenate strings.An overloaded operator exhibits different behavior depending of the types of its operands. Furthermore, the behavior of the overloaded plus operator also includes the ability to coerce its right operand into a string representation if it isnt already a string. In this case, the right operand is not a string, but rather is the instance variable named instanceVariable. Thus the behavior of the overloaded plus operator is to first convert the value of instanceVariable to a string representation and than to concatenate it to the left operand. Some object-oriented languages such as C++ allow the programmer to overload almost all of the operators so as to define the behavior of those operators when used with operands of new abstract data types. However, Java does not provide that capability. In this case, the plus operator is intrinsically overloaded by the system.Now lets take another look at the same two methods as before, this time preserving the bodies of the methods for further examination.void instanceMethod(){ //define an instance methodSystem.out.println(A - Instance variable contains + instanceVariable);System.out.println(B - Class variable contains + classVariable);} //end instanceMethod()static void classMethod(){ //define a class methodSystem.out.println(C - Class variable contains + classVariable);}//end classMethod()Here we see the code in the body of the methods accessing the member variables of the class. Recall that one of the member variables is an instance variable named instanceVariable and the other member variable is a class variable named classVariable. The instance method named instanceMethod is able to access and display both the instance variable and the class variable while the class method named classMethod is only allowed to access and display the class variable. Class methods cannot access instance variables. Now consider the contents of the main method as shown below. Both Java and C++ applications (not applets) require a main method or function as the controlling method of the application. In our simple application, we will use code in the main method to instantiate an object and to access both the instance method and the class method. Recall that in order to access an instance method, it is necessary to access it via an object of the class. The next code fragment is the code in the main method that instantiates an object named obj of the class named Oop01.//instantiate an object of the class Oop01Oop01 obj = new Oop01();This is a typical Java statement for instantiating an object and is similar to one form of statement that can be used to instantiate an object in C++. (C++ provides other forms as well.) This statement uses the new operator to request that the operating system provide memory from the heap to store one copy of an object of type Oop01. If the required memory is successfully allocated, the address of that block of memory will be assigned to the reference variable named obj. If unsuccessful, the Java runtime system will throw an exception. This is a type of exception which can either be ignored, or can be caught and processed by the program. If ignored, it will cause the runtime system to shut down the program. (Exception handling is discussed later in this lesson.)Both Java and C++ support exception handling, but do so in slightly different ways. Once we have access to an object of the class (or more correctly access to a reference variable which refers to an object of the class), we can use that reference variable to access the public member variables and to invoke the public methods of the class. This is illustrated in the following code fragment. The two statements in the following code fragment use the reference variable named obj along with the period to access the instance variable and the instance method of the object. Recall that the instance variables and the instance methods can be accessed only via an object of the class. obj.instanceVariable = 5; //access instance variable via the objectobj.instanceMethod(); //access instance method via the objectEqually important is the fact that the class variable and the class method can be accessed without the requirement to use an object of the class. The two statements in the following code fragment simply use the name of the class to access the class variable and the class method of the class. Oop01.classVariable = 10; //access class variable via the classOop01.classMethod(); //access class method via the classClass variables and class methods can be accessed either via an object of the class, or via the name of the class alone. However, this sample program does not illustrate accessing class variables and methods using an object of the class.Finally, we put it all together in the Java application shown below./*The output from this program is:A - Instance variable contains 5B - Class variable contains 10C - Class variable contains 10**********************************************************/class Oop01{ //define controlling classint instanceVariable; //declare an instance variablestatic int classVariable; //declare a class variablevoid instanceMethod(){ //define an instance methodSystem.out.println(A - Instance variable contains + instanceVariable);System.out.println(B - Class variable contains + classVariable);} //end instanceMethod()static void classMethod(){//define a class methodSystem.out.println(C - Class variable contains + classVariable);} //end classMethod()public static void main(String[] args){//instantiate an object of the class Oop01Oop01 obj = new Oop01();//access instance variable via the objectobj.instanceVariable = 5;//access class variable via the classOop01.classVariable = 10;//access instance method via the objectobj.instanceMethod();//access class method via the classOop01.classMethod();} //end main()} //end class Oop01

METHOD OVERLOADINGA problem arises when mapping the concept of nuance in human language onto a programming language. Often, the same word expresses a number of different meaningsits overloaded. This is useful, especially when it comes to so the listener doesnt need to make any distinction about the action performed. Most human languages are redundant, so even if you miss a few words, you can still determine the meaning. We dont need unique identifierswe can deduce meaning from context. This program Sum.java demonstrates