IMTS PGDCA (Internet & java programming)

Page 1

I ns t i t ut eo fMa na g e me nt & Te c hni c a lSt udi e s

I NTERNET& JAVA

PROGRAMMI NG

PGDCA

www. i mt s i ns t i t ut e . c o m


IMTS (ISO 9001-2008 Internationally Certified)

INTERNET & JAVA PROGRAMMING

INTERNET & JAVA PROGRAMMING

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET AND JAVA PROGRAMMING CONTENTS UNIT I

01-12 Internet connection concepts –Intranets :Connecting LANs to the internet – EMail concepts –E-Mail security. Reasons to secure the messages –Public key cryptography. Using cryptography with E-Mail –Online chatting and Conferencing concepts –WWW concepts. UNIT II 13-34 Fundamentals of Object Oriented Programming –JAVA evolution – OverView of Java Languar –Constants, Variables and Data Types –Operators and Expressions and Decision Making. UNIT III 35-50 Classes, Objects and Methods –Arrays, String and Vectors – Multiple inheritance. UNIT IV 51-71 Packages –Multithreaded programming –Managing Errors and Exceptions. UNIT V 72-86 Applet Programming –Graphics Programming –Managing Errors and Exceptions.

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

1

UNIT I Internet Connection Concepts A network is a system of computers and other devices (such as printers and modems) that are connected in such a way that they can exchange data. A networking system consists of hardware and software. Hardware on a network includes physical devices such as Macintosh personal computer workstations, printers, and Macintosh computers acting as file servers, print servers, and routers; these devices are all referred to as nodes on the network. If the nodes are not all connected to a single physical cable, special hardware and software devices must connect the cables in order to forward messages to their destination addresses. A bridge is a device that connects networking cables without examining the addresses of messages or making decisions as to the best route for a message to take. By contrast, a router contains addressing and routing information that lets it determine from a message's address the most efficient route for the message. A message can be passed from router to router several times before being delivered to its destination. In order for nodes to exchange data, they must use a common set of rules defining the format of the data and the manner in which it is to be transmitted. A protocol is a formalized set of procedural rules for the exchange of information and for the interactions among the network's interconnected nodes. A network software developer implements these rules in software modules that carry out the functions specified by the protocol. Whereas a router can connect networks only if they use the same protocol and address format, a gateway converts addresses and protocols to connect dissimilar networks. A set of networks connected by routers or gateways is called an internet. The term Internet (note the capitalization) is often used to refer to the largest worldwide system of networks, also called the Worldwide Internet. The basic protocol used to implement the WorldWide Internet is called the Internet Protocol, or IP. Because the word internet is used in several different ways, it is important to note capitalization and context whenever you see this word. A networking protocol commonly uses the services of another, more fundamental protocol to achieve its ends. For example, the AppleTalk Data Stream Protocol (ADSP) uses the Datagram Delivery Protocol (DDP) to encapsulate the data and deliver it over an AppleTalk network. The protocol that uses the services of an underlying protocol is said to be a client of the lower protocol; for example, ADSP is a client of DDP. A set of protocols related in this fashion is called a protocol stack. Protocol stacks are described in more detail in "Protocol Stacks and the OSI Model" .

INTRANET What’.s an intranet Multiple definitions exist. "Using Internet-based technologies within an organization to facilitate communication and access to information.. An integrating mechanism for people, processes and information within the enterprise. The corporate "information network". No single definition dominates but basic agreement on the use of web based delivery mechanisms within a private environment Basic intranet structure Internet technologies used behind the corporate firewall or in private environment Including, but not limited to: Internet standard mail, web servers, providing access to information, databases, scheduling, etc. Multimedia is using mime type. An intranet has common IP protocol suite with the the internet but offers significant differences. Packets are private rather than public. More focused Internet and Intranet An intranet has common IP protocol suite with the the internet but offers significant differences.  Packets are private rather than public  More focused Enterprise based mgmt  Stronger policies and a controlling organisation

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

2

 Cost borne by single organisation  Stronger enforcement of policies  More control of the network Why are intranets popular  . Inexpensive to implement  . Easy to use, just point and click  . Saves time and money, better information faster  . Based on open standards  . Scaleable and flexible  . Connects across disparate platforms  . Puts users in control of their data Benefits of intranets  Integrate data from diverse sources  Legacy is removed by a common http protocol and web based presentation  Provide Access to data by all stakeholders in the company.s value chain  Shared data allows presentation to different parts of the organisation including customers Different formats used to Present information for each stakeholders  Use of web design and XML allows range of different presentations to be exploited  . Guarantee Performance, Availability, Serviceability,and Security  . A product of the network being closed. Organisational benefits  . Improved decision making  . Empowered users  . Builds a culture of sharing and collaboration  . Facilitates organizational learning  . Breaks down bureaucracy  . Improved quality of life at work  . Improved productivity. CONNECTING LANs TO THE INTERNET Before you can connect to the Internet and access the World Wide Web, you need to have certain equipment. In brief, you must have a computer (preferably running an up-to-date operating system); a modem and access to a telephone line or a local area network (LAN) that is in turn connected to the Internet; and connection software that will allow you to establish an account with a service provider and access the Internet. A modem is not needed when accessing the Internet through a LAN. Hardware To operate most of the current Web browsers and on-line services, you should have an IBM PC/PC equivalent, UNIX workstation, or Apple Macintosh computer with at least 8 megabytes (MB) of random access memory (RAM) and 10 MB of free disk space. If you are unsure of how much RAM and disk space your computer has, consult your user's manual. NOTE: Although the capacities of both are measured in megabytes, RAM and disk space are NOT the same thing! RAM refers to the electronic microchips in your computer that store data for relatively brief periods, and that give your computer the active capacity to run programs and access data. Disk space refers to space on the magnetic hard disk inside (or connected to) your computer that stores data over the long term. For best results, use a PC with a 486 or Pentium microprocessor; or a Macintosh with an 030, 040 or PowerPC microprocessor. It is possible to connect to the Internet using a computer other than an IBM PC, Macintosh or UNIX workstation, though the access software available for such machines is limited. If you are accessing the Internet outside of a LAN environment, you will need a modem that will connect you with other computers and interpret the data being sent back and forth. Most any modem that is compatible with your computer will do, though the higher the kilobits per second (kbps) rate of your modem, the faster it will transmit data. Modem speed is an important consideration when accessing sites on the Web that contain lots of digitized data. In general, your modem should transmit data at 14.4 kbps or faster to give you optimum performance on the Web. If you are looking to purchase a modem, buy the fastest model you can afford.

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

3

You must also have access to a live telephone line. Most modems accept the same jacks as do ordinary household telephones, allowing you to connect your modem to a wall jack using standard phone cord. Some cable TV providers have begun offering Internet connections via cable. Such connections provide much faster transmission speeds than standard phone lines, though you will need a special modem that allows you to link your computer with the cable. If you are interested in a cable Internet connection, contact your local cable operator to see if the service is available in your area. You can also connect to the Internet through a LAN with Internet access. If you are unsure as to the capacities of your LAN to do this, contact your site's systems administrator. For best results, make sure that your computer is running the most up-to-date operating system that it can handle. If you have an IBM PC/PC compatible computer, it should be running Microsoft Windows version 3.1, Windows NT, Windows 95 or OS/2. If you have a Macintosh, it should be running System 7 or higher. To make your connection complete, you will need connection software that allows your computer to dial into an Internet access provider, establish an account, and work with the data in a straightforward manner. Many access providers will give you software that will allow you to access their systems using an all-in-one custom interface. Others may give you a collection of separate software packages that can be used together. But whatever software they provide, be sure that it is compatible with your computer and operating system before attempting to use it. Some Internet access providers may allow you to establish a serial line interface protocol (SLIP) or point-to-point protocol (PPP) connection, either of which essentially makes your computer a part of the Internet. Unlike many standard dial-up software packages, a SLIP/PPP connection allows you to run independent software packages such as Web browsers, either one at a time or simultaneously. BROWSER As you surf the Web, you will come across sites that state, "This site is best viewed with‌" and then name a particular browser. Many will even provide a link to a site where you can download the specified browser. Sites make these recommendations because some browsers use special protocols, allowing site creators to offer extra features beyond the standard capabilities of hypertext markup language (HTML). Chief among these browsers are Netscape Navigator and Microsoft Internet Explorer. Your Internet service provider will most likely give you a choice of browsers (if you have a SLIP/PPP account, you may use any browser you wish), so try out a couple, and use the browser that best suits your needs.

Extras The Netscape Navigator and Microsoft Internet Explorer browsers allow for the use of plug-ins, or extra software applications that run as if they were an integral part of the browser. To see which plug-ins are currently available for Netscape, go to: http://home.netscape.com/comprod/mirror/index.html To see the plug-ins for Internet Explorer, go to: http://www.microsoft.com/ie/download/ Browsers also use helper applications that, while not as integral as plug-ins, enhance the browser's capabilities by launching when needed. Helper applications allow your browser to play sound and video files, display animation and other graphic formats, or access special Internet features such as TELNET. Most Web sites that require the use of helper applications will provide links to sites where you can download the necessary software. Connection Options

Until recently, the two primary methods of accessing the Internet were through a network connection, allowing users of local area networks (LANs) to go online through their school or workplace systems, and dial-up connections through a modem and phone line. However, new connection options allow for greater speeds and flexibility, while keeping costs to a minimum. The following are some of the newer connection options that you might want to investigate:

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING 

  

4

Cable Internet—These systems allow your computer to connect to the Internet through the same cable that carries your TV signal. Monthly service charges are usually not much more than standard modem connection costs, but you have to rent or purchase a "cable modem." Additionally, your computer will need an Ethernet card (a special circuit board that allows for network connections). Not all cable service operators offer this service; call your local operator for more information. Satellite connections—DirecPC (http://www.direcpc.com/) allows you to download Internet files via a satellite connection. This is an efficient method for receiving large Web graphics and other items, but you still need a modem connection for other features. You must purchase the connection hardware as well as subscribe to the service. Integrated Services Digital Network (ISDN)—An ISDN line is a type of digital phone line that can transmit data many times faster than a conventional modem and phone line. To learn more about ISDN, go to http://www.isdn.ocn.com/index.shtml Wireless connections—Pagers, cellular phones and personal digital assistants (PDAs) now allow varying levels of Internet access, from notification of E-mail to limited Web connections. Many of these services remain in the experimental stage. WebTV—Introduced in late 1996, WebTV (http://www.webtv.net/) provides Web and E-mail access through ordinary television sets. The connection is made through a custom high-speed modem. You must purchase a special set-top unit for your TV, plus subscribe to the connection service. Recently, similar systems by other manufacturers have appeared on the market to compete with WebTV.

E-MAIL CONCEPTS This topic provides you with concepts and procedures for configuring and administering e(TM) mail on your iSeries server. This information assumes that you have worked on the iSeries before and have a working knowledge of TCP/IP, Simple Mail Transfer Protocol (SMTP), and e-mail concepts. For an overview of e-mail on the iSeries, refer to the topics in Understand e-mail. The following image depicts the network for MyCompany and how a mail message passes through the various layers in order to get to its final destination. After the image you will find a step by step description of the path the mail message takes through this network.

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

Jane is using the Netscape SamJones@mycompany.com.

mail

client.

5

She

writes

a

message

and

sends

it

to

Phase 1: SMTP client to SMTP server The SMTP client on Jane's PC uses the configuration data that was entered for the outgoing server and identity. The identity field is used for the From address. The outgoing server is the host that is contacted by the PC SMTP client. Because the address is entered as a domain, the SMTP client queries DNS to get the IP address of the SMTP server, and discovers it is 192.1.1.8. The SMTP client now contacts the SMTP server on the SMTP port (Port 25 at 192.1.8). The dialog that is used between the client and the server is the SMTP protocol. The SMTP server accepts delivery of the mail, and the message is transmitted from the client to the server using TCP/IP. Phase 2: SMTP server delivers the message to the POP server The SMTP server tests the domain of the recipient to see if it is local. Because it is local, the mail is written out to an IFS file and the QMSF Framework Create Message API is used to put the message information in the QMSF queue. The QMSF framework allows the distribution of e-mail, calling exit programs or snap-ins to handle specific mail types. The message information identifies Sam's address as SMTP format, so the framework calls the SMTP Address Resolution exit program. This program again checks that the message is local. Because it is local, it uses the system distribution directory (data entered via WRKDIRE) to find the recipient's SMTP address. It finds Sam's address, and finds the mail service level is system message store in the directory entry for this user, therefore it recognizes it as a POP account. Then SMTP Address Resolution adds his profile information to the message information. It marks the information as POP local delivery. The QMSF Framework then calls the POP Local Delivery exit program, which finds the profile information and the name of the IFS file and delivers the mail to Sam's mailbox. Phase 3: POP Client retrieves message for Sam Jones from the POP server At some time later, Sam decides to check his e-mail. He uses a mail client (Netscape) to check his mailbox. The POP client on his PC is configured to check the POP server at mycompany.com for username SamJones and password (******). The domain name is again changed to an IP address (using DNS). The POP client contacts the POP server using the POP port and the POP3 protocol. The mailbox user name and password are used by the POP server on the iSeries to check that the user name and password match the profile and password of an iSeries user. After it is validated, the profile name is used to find Sam's mailbox. The POP client loads the message, and sends a request back to the POP server to delete the mail from the POP . MIME

(Multipurpose Internet Mail Extensions) MIME is a standardized method for organizing divergent file formats. SMTP is limited to 7-bit ASCII text with a maximum line length of 1000 characters. MIME was developed to support more advanced file types, such as rich text, images, and audio or video files. MIME encodes files of binary type data to appear as simple SMTP data, using headers to distinguish different file types within the message, before sending the message with SMTP. The mail client then receives the message and decodes it to the proper file types by interpreting the MIME headers to read the file. For an example of a MIME encoded message, see MIME content types. AnyMail/400 Frame Work All incoming mail from SMTP for local users (users with mail accounts on this iSeries) is processed by the AnyMail/400 framework. The mail server framework is a mail distribution structure that allows the distribution of e-mail. The mail server framework calls exit programs or snap-ins to handle specific mail types. SNADS (R) System Network Architecture Distribution Services (SNADS) is an IBM asynchronous distribution service that defines a set of rules to receive, route, and send electronic mail in a network of servers. In this topic, SNADS refers to a user's profile in which the Preferred address is set to User ID/Address. The preferred address tells the mail server framework what fields to use in the system distribution directory for the address. For more information about using SNADS, refer to the SNADS topics in Send and receive e-mail.

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

6

The system of room videoconferences is a service that enables real-time audiovisual communication between users on two or more remote locations. In specially equipped rooms, socalled TCRs (Teleconferencing Rooms) users can participate in remote lectures, attend conferences, seminars, professional gatherings and roundtables, as well as participate in different projects. Videoconferences can be applied in different areas, enabling those who use them to significantly save time and travel expenses. Video conferencing is the ideal way to hold a business meeting without the time and expense of travelling. Whether it’s one to one, or several people in different locations, video conferencing keeps the communication flowing. The simplest definition of how video conferencing works is simply by the integration of video, audio and peripherals to enable two or more people to communicate simultaneously over some type of telecommunications lines. In other words, you are transmitting synchronized images and verbal communications between two or more locations in lieu of them being in the same room. Millions of people use video conferencing every day around the globe, but very few people know just how the technical aspects of the process work. The main ingredients of successful video conferencing are video cameras, microphones, appropriate computer software and computer equipment and peripherals that will integrate with the transmission lines to relay the information. The analog information recorded by the microphones and cameras is broken down into discreet units, translating it to ones and zeros. A Codec encodes the information to a digital signal that can then be transmitted to a codec at the other end, which will retranslate these digital signals back into analog video images and audio sounds. In the earlier days of video conferencing, T1, ATM and ISDN lines were used almost exclusively but were really only practical for room-based video conferencing systems. These dedicated lines were expensive and only large corporations tended to have the facilities and money to invest in this type of set-up. As the Internet became more a part of the everyday lives of all businesses, however, it changed how video conferencing was conducted. The TCP/IP connections of the Internet are much less expensive and can carry large quantities of information, including video packets for conferencing, relatively easily. Because of this, video conferencing has become much more prevalent in small businesses and in desktop packages that can be set up with software for computer-to-computer networking. The problem that arises when you convert analog to digital for transmission is the loss of clarity in an image. Analog signals are a continuous wave of amplitudes and frequencies showing shades and ranges of color as well as depth and brightness. When you convert to digital, which is strictly 0’s and 1’s, you then need to develop a grid to represent values, intensities and saturations of different color values so that the image can be interpreted and reformed at the receiving end. This vast amount of digital information requires huge bandwidth and means that the time it would take to transmit video images would be impractical for most applications. That’s where compression is crucial. When determining how video conferencing works, one of the most important elements is the compression ratio. The higher the compression ratio, the more quickly the information is capable of being transmitted. In many cases, however, this also means some loss in clarity or audio/video quality. For instance, a compression ratio of 4:1 would be terribly slow but have a fantastic picture quality. But by the time it was transmitted, everyone at the other end would probably have left the room for a cup of coffee. Lossy compression discards unneeded or irrelevant sections of a signal in order to transmit only the essentials, speeding up the transmission time significantly but sometimes resulting in loss of quality. Compression can either be intra-frame or inter-frame for material that is repetitive or redundant, such as that wall behind the conference participant. Since the wall remains static and never changes, this image is redundant and can be eliminated from transmissions to an extent with proper compression. Intra-frame compression assumes the redundancy will be present in parts of a frame that are close to each other. Inter-frame compression assumes that there is redundancy over time (i.e., like that wall). Either of these can achieve a fairly high degree of accuracy and reduce the bandwidth needed for transmittal of signals. A newer version of compression/decompression is SightSpeed technology, developed by Cornell University. SightSpeed compresses only images considered essential and eliminating what is considered ‘filler,’ relying on the brain to fill in the decompression at the other end. Based on an artificial intelligence model, SightSpeed achieves compression of about 90:1, compared to the typical 15:1 for video conferencing.

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

7

Any video conferencing session you use will provide compression of the transmission signal. The key is determining the balance between speed and video picture quality that is right for your needs. Point to point video conferencing Point to point video conferencing is just what it sounds like – a link between two different points on the planet, or two different video conferencing terminals. It could be between an office in New York City and a conference room in Munich. Point to point video conferencing can easily be initiated by someone on one end contacting the other end as though making a standard telephone call. There are no special arrangements to be made other than knowing that the participants will be there. Multipoint conferencing is more complex Multipoint conferencing is more complicated because it has to coordinate several different locations simultaneously. Since you can’t be in direct contact with several places at once while they are all in contact with others, you need one source that will tie them all together. In video conferencing, this is called a multipoint bridge or multipoint conferencing unit (MCU). An MCU enables multi-location video conferencing by providing a sort of “central processing center” for all of the locations through which all the information flows. The MCU receives all information from the various locations and then sends it out to each location. In some cases the MCU is located on a particular PC, and in other cases it is located on a remote server (the most common structure, particularly for more powerful MCU networks). Audio is usually sent and received simultaneously in all locations with an MCU with no problem because of the relatively small bandwidth needed for transmittal. It is broadcast in what is called “full duplex” mode, meaning everyone can talk and hear at the same time with no cutting off when one person or another speaks. Video transmission, however, can be broadcast in a number of ways with an MCU depending upon the quality of the software and the complexity of the system. Some common types of video transmission for video conferencing include: Continuous Presence video conferencing, which allows up to four conference sites to be seen simultaneously on split screens. This is usually used if you have a small group or individuals in separate locations and will primarily be seeing close-up shots. Universal Control video conferencing is controlled by the initiating conference site. The primary site determines who sees what at all other sites. Voice Activated video conferencing is by far the most common type used today. The image with these systems shifts to the site that is currently activating the microphone so that you can always see whoever is speaking. However, if there is a good deal of background noise participants should mute their microphones when they aren’t talking in order to avoid the image jumping about needlessly. Obviously, communicating through video conferencing can’t be achieved unless both ends of the conference are “speaking the same language.” That is, whatever is being transmitted electronically will need to be reassembled properly and heard and seen clearly at the other end. The Codec system (Coder-Decoder) is useless if both ends aren’t using the same virtual language to interpret the signals. The International Telecommunications Union (ITU) developed a set of standards in 1996 dubbed H.323 to outline specific guidelines for Video Conferencing standards and protocols so that compliance and support across networks would be easier to achieve and maintain. Since then, many manufacturers and developers of video conferencing tools have adopted the H.323 guidelines as their own. Web conferencing solutions such as Click to Meet, Lotus’s SameTime, and WebEx also offer corporate solutions that are based on Internet video conferencing. These systems have shared protocols that can be downloaded and used anywhere at any location for subscribers through the Internet. These are becoming more popular with companies who like the convenience and userfriendliness. They will no doubt become more and more refined over time, vying with and perhaps surpassing the H.323 standards. Overcoming firewall issues There are, of course, obstacles to overcome when you take a look at how video conferencing works. After all, you’re sending vast amounts of translated data either directly or through a gatekeeper system (the MCU) that is switching and transferring information between a variety of computers. Just about any business these days has a firewall system to provide security and protect the system from potential viruses. Trouble is, many firewalls also block the transmission of data for video conferencing.

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

8

Recent innovations have largely circumvented these problems by designing firewall solutions that recognize video conferencing signaling requests and allow the information packets to bypass the firewall or router without disabling the firewall protection for other traffic. Even with this, however, there may be occasions when packets are dropped because of heavy traffic on the system, so investing in a firewall system that can handle substantial traffic is essential to quality video conferencing performance. Chatting Once an individual has access to the Internet, there are a wide variety of different methods of communication and information exchange over the network. These numerous methods of communication and information retrieval are constantly evolving and are therefore difficult to categorize concisely. The most common methods of communications on the Internet (as well as within the major online services) can be roughly grouped into six categories: one-to-one messaging (such as "e-mail"), one-to-many messaging (such as "listserv"), distributed message databases (such as "USENET newsgroups"), real time communication (such as "Internet Relay Chat"), real time remote computer utilization (such as "telnet"), and remote information retrieval (such as "ftp," "gopher," and the "World Wide Web"). Most of these methods of communication can be used to transmit text, data, computer programs, sound, or visual images. Instant messaging allows users to "chat" in real time. Users can send text messages to anyone online and receive instant replies if the user is also online. The "instant" fad gave way to parental fears as children made "friends" online. With no way to confirm if "friends" are who they represent themselves to be, and multiple security holes, instant messaging has taken a back seat in internet communication. WWW Concepts The World Wide Web is a user interface to the Internet. The Internet is a set of computers connected to each other with a network. Each of these computers either knows how to speak, (or knows another computer that knows how to speak), a language called TCP/IP. The World Wide Web is an easy to use, transparent user interface to these computers. You don't need to know where the computers are or how many exist, in order to use the World Wide Web. That is it's allure. The World Wide Web is to the Internet as Microsoft Windows (or a Macintosh) is to DOS. A brief history of the WWW The World Wide Web got started because it was just plain too difficult to get at all of the information that is on the Internet. The only people who could do it were the computer geeks. The learning curve for accessing information on the Internet was indeed very steep. Basically, if you weren't a Unix or VMS guru, you were left out of the Internet. The first effort to make the Internet accessible to less geeky types was called gopher. Gopher was developed for use on terminal screens. It offered a very nice interface to the net. A user could move up and down along the screen and pick choices by highlighting a topic and pressing the enter key. When a useful document was presented, another press of the enter key downloaded it to your local terminal. Unfortunately Gopher didn't really come into it's own. In this age of mice and windows, users demand more, MUCH more than a simple terminal based interface. Think of Gopher as DOS SHELL or PCTOOLS to the Internet. Better than DOS, but nobody uses them any more. Enter Hypermedia. If you have ever used Hypercard on the Mac or a Windows help file you know all about hypermedia. It is a method of presenting a user with text (or other things) that can be clicked with a mouse. There are two different types of text presented, normal text which is to be read, and highlighted text which can be clicked (or invoked somehow). So, now that you are bored to tears, the World Wide Web is a hypermedia interface similar to Hypercard or Windows Help, to the Internet. A user is presented with text, pictures, movies, sound and just about anything someone can dream up, that is clickable. So the Internet has finally become something people can use. Much to the despair of the geeks...

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

9

Acronyms and terms from Hell - What do they MEAN? The computer industry is famous for its acronyms. In fact there is even a course in the CS department titled "How to acronymize your creation, and make it impossible to decipher." (Maybe I'm kidding, maybe I'm not). Here are some of the more popular Web related acronyms and their meanings: WWW "A Hah!" you say, "I know what that one is, you already used it!" Correct, it stands for World Wide Web. Also known as W3, or W cubed, or just "The Web". HTML HyperText Markup Language. We won't get into HTML too much in this class, but suffice to say you will hear it a lot when using with the Web. It is the what web pages are written in. URL Uniform Resource Locator. It is a standard for specifying an object on the Internet, such as a file or image. It's the thing in the "Location box" on your web browser. (We will get into it much more later). URLs or web addresses are the internet paths used by computers to locate the file that you want to see. Note: URLs are case sensitive and do not contain any spaces. URLs or web addresses can be broken down into various components, e.g.

Other domains include:  edu = education institute  com = commercial enterprise  gov = government  org = organization  net = network provider  mil = military Examples include: . http://www.ohiou.edu/ gopher://oucsace.cs.ohiou.edu/ news:ohiou mailto:rbarrette@ohiou.edu

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

10

HTTP / HTTPD / HTTPS HyperText Transfer Protocol / Daemon / Secure Server .HTTP is the high-level protocol that web browsers and server speak that rides on top of TCP/IP (the language of the Internet). A Daemon is a server, so in this case an HTTP server. HTTPS is relatively recent and is a secure server. Anything you send to the server (we will get into sending things later) is encrypted so that no one can read what you are sending. This is critical to commerce over the web. No one wants their credit card numbers going across the net in clear text. One link, two link, red link, blue link A link is something in a hypertext document that can be clicked. It is usually marked in a different color than the rest of the text, and/or is underlined. This is a link. Clicking on a link will usually take you somewhere else in the web, sometimes far, sometimes near. The important thing is that it doesn't matter. Surfing the web The process of sitting in front of a computer and using a web browser. Each of you is surfing the web right this very second. Neat huh? Homepage vs. Webpage There really is no intrinsic difference between the two and you will hear them used interchangeably. It really is a matter of personal taste. For me, I prefer to refer to the "main" page in a set of documents as the homepage, and the rest are just web pages. But it really doesn't matter, what is important is that it is a page of text with links in it written in HTML. Where to start Okay, now that we have all of that nasty stuff under control, lets start using the real web in front of you. Whats in a web browser There are lots of different web browsers available for all kinds of computers and operating systems. The one we are going to focus on is called Netscape. Netscape is by far the most popular web browser, and is written by the same people who wrote the original NCSA Mosaic over a year ago. What's nice is that Netscape is available for free for those of us that are fortunate enough to work at educational institutions. Another benefit is that Netscape looks much the same whether you are sitting in front of a Macintosh, Windows, or Unix Workstation computer. Most people don't bother to look at their browser when they start using the web. Netscape itself is rather boring, there is too much neat stuff on the web itself! But some old guy in China once said "Learn how to use the knife before you cut with it". I believe in this philosophy myself. Netscape is a tool, we need to know how to use it in order to surf the web effectively. Besides, you don't want to be roadkill on the Information Superhighway do you? Netscape menus I'm only going to cover the menu items that I feel are important. There is quite a bit of redundancy in the menus and toolbar, so I will cover just about everything, don't worry. Anything I don't mention will be in the toolbar or isn't important immediately. Important menu items: File Menu Save As... Use this to save a document, image or file you like to disk. Open File...

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

11

Use this to open an HTML file that exists on your local machine. This is very useful for those of you planning web development. Print Print the current page. I don't recommend doing this, but unfortunately we live in an age where people don't see something as "real" unless it is printed and in their hands. Until we get over it, this function will exist. Exit Quit surfing. This is an extremely important function, it will save you time and money. Mostly it will be the only thing that will prevent you from becoming a webaholic. Edit Menu Cut,Copy,Paste Useful for cutting and pasting URL's. Some are just plain too long to type so use this to email that URL you love so much to a friend. Just highlight and copy and paste it into your email. Find again Mostly you want to notice the keystroke combination after this item. The Find function is on the toolbar, and that is where we will use it, but the Find again keystroke is useful. View Menu Source This will put the current document into your local notepad as its original HTML source. Quite possibly the most useful menu item, but only if you are doing web development. Surfers can ignore. Go Menu View History A good way to look at where you have surfed during the current session. If you have been doing it a while and your list is truncated, the history will have every page you have visited since you invoked Netscape last. List of Links This is a short history of where you have been recently. Very useful for "hopping" around pages you are looking at without using next and back repeatedly. Why hit back ten times when you can just click the go menu once? Bookmarks Menu This menu is so mind-bogglingly useful we are going to cover it in lots of detail later. Keep it in the back of your mind. Options Menu Preferences... Several preferences exist in this menu. Most of the defaults are satisfactory but I will take you through the ones you should change. Usually a quick browse through the choices will make it obvious. Things like your name and email address are critical for full functionality so make sure you enter them into the correct places. Show Toolbar Make sure this is ON Show Location Make sure this is ON Show Directory Buttons I turn this off because there is a menu that has all of the buttons in it, and I want the extra 1/4 of an inch of space to view documents. Auto-Load Images With a direct ethernet connection, this should be ON, at home under SLIP you may want to turn it OFF Show FTP file information Useful, leave it ON Save Options Saves your choices so the next time you fire up Netscape, they will be the same. Directory Menu Go To Newsgroups This will take you to the newsgroup selection screen so you can read Usenet News. This course doesn't cover News, but Netscape is an effective News reader and Poster. Browse at your leisure.

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

12

Netscape buttons Also known as the Toolbar. Most of them are self explanatory, and I will explain them in class. Location box This box shows the current URL. I like to leave it on, because if you ever want to go directly to a specific web page you can just type in the URL right there and hit enter. Much faster than pulling down the open menu. It is also great for cutting and pasting URL's that friends send you in emails, or that you see in newsgroups. How to find what you are looking for One of the first questions everyone asks when sitting in front of the web, is "How do I find information on ... ?". Where ... is some topic they are interested in. There are two very effective ways to do this. Search Engines The first method, and the by far the most efficient, is to use a "Search Engine". A Search Engine is a tool that is accessed via the web that will attempt to search for information you are interested in. The most popular one is completely useless anymore, so the one I would recommend is called "Yahoo". What's nice about Yahoo is that it also has a list of other places you can search. We will take a look at Yahoo during class. Hunt and Peck The second method is to just surf. Surf like the wind, surf like crazy, surf like you've never surfed before! Make use of your Bookmarks, (the next section covers using bookmarks), and also be sure you have a clock sitting right there in front of your face. If you do not, the hours will slip away, I promise. 

  

Finally www can be summarized as follows, There is no single tool for the web that will search everything and there is no single search tool that will always provide the best answer. You need to choose several that suit you and learn to use them effectively. Always evaluate the information that you find. Always reference ideas/work that you find and use from other people. Never cite something and pretend it is yours – that is called plagiarism. Finally – know when to give up! Not everything is available on the web. Is the web the best place to look? Don’t forget that print was here first – check your library or talk to your librarian!

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

13

UNIT II Java is an object-oriented programming language with a built-in application programming interface (API) that can handle graphics and user interfaces and that can be used to create applications or applets. Because of its rich set of API's, similar to Macintosh and Windows, and its platform independence, Java can also be thought of as a platform in itself. Java also has standard libraries for doing mathematics. Much of the syntax of Java is the same as C and C++. One major difference is that Java does not have pointers. However, the biggest difference is that you must write object oriented code in Java. Procedural pieces of code can only be embedded in objects. In the following we assume that the reader has some familiarity with a programming language. In particular, some familiarity with the syntax of C/C++ is useful. In Java we distinguish between applications, which are programs that perform the same functions as those written in other programming languages, and applets, which are programs that can be embedded in a Web page and accessed over the Internet. Our initial focus will be on writing applications. When a program is compiled, a byte code is produced that can be read and executed by any platform that can run Java. The Java Programming Language The Java programming language is a high-level language that can be characterized by all of the following buzzwords:

Each of the preceding buzzwords is explained in The Java Language Environment , a white paper written by James Gosling and Henry McGilton. In the Java programming language, all source code is first written in plain text files ending with the .java extension. Those source files are then compiled into .class files by the javac compiler. A .class file does not contain code that is native to your processor; it instead contains bytecodes — the 1 machine language of the Java Virtual Machine (Java VM). The java launcher tool then runs your application with an instance of the Java Virtual Machine.

An overview of the software development process. Because the Java VM is available on many different operating systems, the same .class files TM are capable of running on Microsoft Windows, the Solaris Operating System (Solaris OS), Linux, or Mac OS. Some virtual machines, such as the Java HotSpot virtual machine, perform additional steps at runtime to give your application a performance boost. This include various tasks such as finding performance bottlenecks and recompiling (to native code) frequently used sections of code.

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

14

Through the Java VM, the same application is capable of running on multiple platforms. The Java Platform A platform is the hardware or software environment in which a program runs. We've already mentioned some of the most popular platforms like Microsoft Windows, Linux, Solaris OS, and Mac OS. Most platforms can be described as a combination of the operating system and underlying hardware. The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms. The Java platform has two components: ď ś The Java Virtual Machine ď ś The Java Application Programming Interface (API) Java Virtual Machine; it's the base for the Java platform and is ported onto various hardwarebased platforms. The API is a large collection of ready-made software components that provide many useful capabilities. It is grouped into libraries of related classes and interfaces; these libraries are known as packages. The next section, What Can Java Technology Do? highlights some of the functionality provided by the API.

The API and Java Virtual Machine insulate the program from the underlying hardware As a platform-independent environment, the Java platform can be a bit slower than native code. However, advances in compiler and virtual machine technologies are bringing performance close to that of native code without threatening portability.

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

15

Object-Oriented Programming Concepts If you've never used an object-oriented programming language before, you'll need to learn a few basic concepts before you can begin writing any code. This lesson will introduce you to objects, classes, inheritance, interfaces, and packages. Each discussion focuses on how these concepts relate to the real world, while simultaneously providing an introduction to the syntax of the Java programming language. What Is an Object? An object is a software bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life. This lesson explains how state and behavior are represented within an object, introduces the concept of data encapsulation, and explains the benefits of designing your software in this manner. What Is a Class? A class is a blueprint or prototype from which objects are created. This section defines a class that models the state and behavior of a real-world object. It intentionally focuses on the basics, showing how even simple classes can cleanly model state and behavior. What Is Inheritance? Inheritance provides a powerful and natural mechanism for organizing and structuring your software. This section explains how classes inherit state and behavior from their superclasses, and explains how to derive one class from another using the simple syntax provided by the Java programming language. What Is an Interface? An interface is a contract between a class and the outside world. When a class implements an interface, it promises to provide the behavior published by that interface. This section defines a simple interface and explains the necessary changes for any class that implements it. What Is a Package? A package is a namespace for organizing classes and interfaces in a logical manner. Placing your code into packages makes large software projects easier to manage. This section explains why this is useful, and introduces you to the Application Programming Interface (API) provided by the Java platform. Language Basics Variables You've already learned that objects store their state in fields. However, the Java programming language also uses the term "variable" as well. This section discusses this relationship, plus variable naming rules and conventions, basic data types (primitive types, character strings, and arrays), default values, and literals. Variables An object stores its state in fields. int cadence = 0; int speed = 0; int gear = 1; TheN What Is an Object?, discussion introduced you to fields, but you probably have still a few questions, such as: What are the rules and conventions for naming a field? Besides int, what other data types are there? Do fields have to be initialized when they are declared? Are fields assigned a

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

16

default value if they are not explicitly initialized? Let me explore the answers to such questions in this lesson, but before that, there are a few technical distinctions you must first become aware of. In the Java programming language, the terms "field" and "variable" are both used; this is a common source of confusion among new developers, since both often seem to refer to the same thing. The Java programming language defines the following kinds of variables: Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another. Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change. Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class. Parameters You've already seen examples of parameters, both in the Bicycle class and in the main method of the "Hello World!" application. Recall that the signature for the main method is public static void main(String[] args). Here, the args variable is the parameter to this method. The important thing to remember is that parameters are always classified as "variables" not "fields". This applies to other parameter-accepting constructs as well (such as constructors and exception handlers). A type's fields, methods, and nested types are collectively called its members. Naming Every programming language has its own set of rules and conventions for the kinds of names that you're allowed to use, and the Java programming language is no different. The rules and conventions for naming your variables can be summarized as follows: Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_". The convention, however, is to always begin your variable names with a letter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where autogenerated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it's technically legal to begin your variable's name with "_", this practice is discouraged. White space is not permitted. Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code selfdocumenting; fields named cadence, speed, and gear, for example, are much more intuitive than abbreviated versions, such as s, c, and g. Also keep in mind that the name you choose must not be a keyword or reserved word. If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

17

word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere. OPERATORS Assignment, Arithmetic, and Unary Operators The Simple Assignment Operator One of the most common operators that you'll encounter is the simple assignment operator "=". You saw this operator in the Bicycle class; it assigns the value on its right to the operand on its left: int cadence = 0; int speed = 0; int gear = 1; This operator can also be used on objects to assign object references, as discussed in Creating Objects. The Arithmetic Operators The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. The only symbol that might look new to you is "%", which divides one operand by another and returns the remainder as its result. + additive operator (also used for String concatenation) subtraction operator * multiplication operator / division operator % remainder operator The following program, ArithmeticDemo, tests the arithmetic operators. class ArithmeticDemo { public static void main (String[] args){ int result = 1 + 2; // result is now 3 System.out.println(result); result = result - 1; // result is now 2 System.out.println(result); result = result * 2; // result is now 4 System.out.println(result); result = result / 2; // result is now 2 System.out.println(result); result = result + 8; // result is now 10 result = result % 7; // result is now 3 System.out.println(result); } } You can also combine the arithmetic operators with the simple assignment operator to create compound assignments. For example, x+=1; and x=x+1; both increment the value of x by 1.

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

18

The + operator can also be used for concatenating (joining) two strings together, as shown in the following ConcatDemo program: class ConcatDemo { public static void main(String[] args){ String firstString = "This is"; String secondString = " a concatenated string."; String thirdString = firstString+secondString; System.out.println(thirdString); } } By the end of this program, the variable thirdString contains "This is a concatenated string.", which gets printed to standard output. The Unary Operators The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean. + ++ -!

Unary plus operator; indicates positive value (numbers are positive without this, however) Unary minus operator; negates an expression Increment operator; increments a value by 1 Decrement operator; decrements a value by 1 Logical complement operator; inverts the value of a boolean

The following program, UnaryDemo, tests the unary operators: class UnaryDemo { public static void main(String[] args){ int result = +1; // result is now 1 System.out.println(result); result--; // result is now 0 System.out.println(result); result++; // result is now 1 System.out.println(result); result = -result; // result is now -1 System.out.println(result); boolean success = false; System.out.println(success); // false System.out.println(!success); // true } } The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference. The following program, PrePostDemo, illustrates the prefix/postfix unary increment operator: class PrePostDemo { public static void main(String[] args){ int i = 3; i++; System.out.println(i); // "4"

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING ++i; System.out.println(i); // "5" System.out.println(++i); System.out.println(i++); System.out.println(i); // "7"

19

// "6" // "6"

} } Equality, Relational, and Conditional Operators The Equality and Relational Operators The equality and relational operators determine if one operand is greater than, less than, equal to, or not equal to another operand. The majority of these operators will probably look familiar to you as well. Keep in mind that you must use "==", not "=", when testing if two primitive values are equal. == equal to != not equal to > greater than >= greater than or equal to < less than <= less than or equal to The following program, ComparisonDemo, tests the comparison operators: class ComparisonDemo { public static void main(String[] args){ int value1 = 1; int value2 = 2; if(value1 == value2) System.out.println("value1 == value2"); if(value1 != value2) System.out.println("value1 != value2"); if(value1 > value2) System.out.println("value1 > value2"); if(value1 < value2) System.out.println("value1 < value2"); if(value1 <= value2) System.out.println("value1 <= value2"); } } Output: value1 != value2 value1 < value2 value1 <= value2 The Conditional Operators The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed. && Conditional-AND || Conditional-OR The following program, ConditionalDemo1, tests these operators: class ConditionalDemo1 { public static void main(String[] args){ int value1 = 1; int value2 = 2; if((value1 == 1) && (value2 == 2)) System.out.println("value1 is 1 AND value2 is 2"); if((value1 == 1) || (value2 == 1)) System.out.println("value1 is 1 OR value2 is 1");

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

20

} } Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement (discussed in the Control Flow Statements section of this lesson). This operator is also known as the ternary operator because it uses three operands. In the following example, this operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result." The following program, ConditionalDemo2, tests the ?: operator: class ConditionalDemo2 { public static void main(String[] args){ int value1 = 1; int value2 = 2; int result; boolean someCondition = true; result = someCondition ? value1 : value2; System.out.println(result); } } Because someCondition is true, this program prints "1" to the screen. Use the ?: operator instead of an if-then-else statement if it makes your code more readable; for example, when the expressions are compact and without side-effects (such as assignments).

The Type Comparison Operator instanceof The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface. The following program, InstanceofDemo, defines a parent class (named Parent), a simple interface (named MyInterface), and a child class (named Child) that inherits from the parent and implements the interface. class InstanceofDemo { public static void main(String[] args) { Parent obj1 = new Parent(); Parent obj2 = new Child(); System.out.println("obj1 instanceof Parent: " + (obj1 instanceof Parent)); System.out.println("obj1 instanceof Child: " + (obj1 instanceof Child)); System.out.println("obj1 instanceof MyInterface: " + (obj1 instanceof MyInterface)); System.out.println("obj2 instanceof Parent: " + (obj2 instanceof Parent)); System.out.println("obj2 instanceof Child: " + (obj2 instanceof Child)); System.out.println("obj2 instanceof MyInterface: " + (obj2 instanceof MyInterface)); } } class Parent{} class Child extends Parent implements MyInterface{} interface MyInterface{} Output: obj1 instanceof Parent: true obj1 instanceof Child: false

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

21

obj1 instanceof MyInterface: false obj2 instanceof Parent: true obj2 instanceof Child: true obj2 instanceof MyInterface: true When using the instanceof operator, keep in mind that null is not an instance of anything. Bitwise and Bit Shift Operators The Java programming language also provides operators that perform bitwise and bit shift operations on integral types. The operators discussed in this section are less commonly used. Therefore, their coverage is brief; the intent is to simply make you aware that these operators exist. The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111". The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator ">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension. The bitwise & operator performs a bitwise AND operation. The bitwise ^ operator performs a bitwise exclusive OR operation. The bitwise | operator performs a bitwise inclusive OR operation. The following program, BitDemo, uses the bitwise AND operator to print the number "2" to standard output. class BitDemo { public static void main(String[] args) { int bitmask = 0x000F; int val = 0x2222; System.out.println(val & bitmask); // prints "2" } } Summary of Operators The following quick reference summarizes the operators supported by the Java programming language. Simple Assignment Operator =

Simple assignment operator

Arithmetic Operators + * / %

Additive operator (also used for String concatenation) Subtraction operator Multiplication operator Division operator Remainder operator

Unary Operators + ++

Unary plus operator; indicates positive value (numbers are positive without this, however) Unary minus operator; negates an expression Increment operator; increments a value by 1

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING -!

22

Decrement operator; decrements a value by 1 Logical compliment operator; inverts the value of a boolean

Equality and Relational Operators == != > >= < <=

Equal to Not equal to Greater than Greater than or equal to Less than Less than or equal to

Conditional Operators && || ?:

Conditional-AND Conditional-OR Ternary (shorthand for if-then-else statement)

Type Comparison Operator Instanceof -Compares an object to a specified type Bitwise and Bit Shift Operators ~ << >> >>> & ^ |

Unary bitwise complement Signed left shift Signed right shift Unsigned right shift Bitwise AND Bitwise exclusive OR Bitwise inclusive OR

Questions 1. Consider the following code snippet. 2. arrayOfInts[j] > arrayOfInts[j+1] Which operators does the code contain? 3. Consider the following code snippet. 4. int i = 10; 5. int n = i++%5; a. What are the values of i and n after the code is executed? b. What are the final values of i and n if instead of using the postfix increment operator (i++), you use the prefix version (++i))? 6. To invert the value of a boolean, which operator would you use? 7. Which operator is used to compare two values, = or == ? 8. Explain the following code sample: result = someCondition ? value1 : value2; Exercises 1. Change the following program to use compound assignments: 2. class ArithmeticDemo { 3. 4. public static void main (String[] args){ 5. 6. int result = 1 + 2; // result is now 3 7. System.out.println(result); 8. 9. result = result - 1; // result is now 2 10. System.out.println(result);

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

23

11. 12. result = result * 2; // result is now 4 13. System.out.println(result); 14. 15. result = result / 2; // result is now 2 16. System.out.println(result); 17. 18. result = result + 8; // result is now 10 19. result = result % 7; // result is now 3 20. System.out.println(result); 21. 22. } 23. } 24. 25. In the following program, explain why the value "6" is printed twice in a row: 26. class PrePostDemo { 27. public static void main(String[] args){ 28. int i = 3; 29. i++; 30. System.out.println(i); // "4" 31. ++i; 32. System.out.println(i); // "5" 33. System.out.println(++i); // "6" 34. System.out.println(i++); // "6" 35. System.out.println(i); // "7" 36. } 37. } Expressions, Statements, and Blocks Now that you understand variables and operators, it's time to learn about expressions, statements, and blocks. Operators may be used in building expressions, which compute values; expressions are the core components of statements; statements may be grouped into blocks. Expressions An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value. You've already seen examples of expressions, illustrated in bold below: int cadence = 0; anArray[0] = 100; System.out.println("Element 1 at index 0: " + anArray[0]); int result = 1 + 2; // result is now 3 if(value1 == value2) System.out.println("value1 == value2"); The data type of the value returned by an expression depends on the elements used in the expression. The expression cadence = 0 returns an int because the assignment operator returns a value of the same data type as its left-hand operand; in this case, cadence is an int. As you can see from the other expressions, an expression can return other types of values as well, such as boolean or String. The Java programming language allows you to construct compound expressions from various smaller expressions as long as the data type required by one part of the expression matches the data type of the other. Here's an example of a compound expression: 1*2*3 In this particular example, the order in which the expression is evaluated is unimportant because the result of multiplication is independent of order; the outcome is always the same, no matter in which order you apply the multiplications. However, this is not true of all expressions. For example, the following expression gives different results, depending on whether you perform the addition or the division operation first: x + y / 100 // ambiguous You can specify exactly how an expression will be evaluated using balanced parenthesis: ( and ). For example, to make the previous expression unambiguous, you could write the following: (x + y) / 100

// unambiguous, recommended

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

24

If you don't explicitly indicate the order for the operations to be performed, the order is determined by the precedence assigned to the operators in use within the expression. Operators that have a higher precedence get evaluated first. For example, the division operator has a higher precedence than does the addition operator. Therefore, the following two statements are equivalent: x + y / 100 x + (y / 100) // unambiguous, recommended When writing compound expressions, be explicit and indicate with parentheses which operators should be evaluated first. This practice makes code easier to read and to maintain. Statements Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon (;).  Assignment expressions  Any use of ++ or - Method invocations  Object creation expressions Such statements are called expression statements. Here are some examples of expression statements. aValue = 8933.234; // assignment statement aValue++; // increment statement System.out.println("Hello World!"); // method invocation statement Bicycle myBike = new Bicycle(); // object creation statement In addition to expression statements, there are two other kinds of statements: declaration statements and control flow statements. A declaration statement declares a variable. You've seen many examples of declaration statements already: double aValue = 8933.234; //declaration statement Finally, control flow statements regulate the order in which statements get executed. You'll learn about control flow statements in the next section, Control Flow Statements Blocks A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed. The following example, BlockDemo, illustrates the use of blocks: class BlockDemo { public static void main(String[] args) { boolean condition = true; if (condition) { // begin block 1 System.out.println("Condition is true."); } // end block one else { // begin block 2 System.out.println("Condition is false."); } // end block 2 } } Questions 1. 2. 3. 4. 5. 6.

Operators may be used in building ___, which compute values. Expressions are the core components of ___. Statements may be grouped into ___. The following code snippet is an example of a ___ expression. 1*2*3 Statements are roughly equivalent to sentences in natural languages, but instead of ending with a period, a statement ends with a ___. 7. A block is a group of zero or more statements between balanced ___ and can be used anywhere a single statement is allowed. Exercises Identify the following kinds of expression statements:  aValue = 8933.234;

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING   

25

aValue++; System.out.println("Hello World!"); Bicycle myBike = new Bicycle();

Enum Types An enum type is a type whose fields consist of a fixed set of constants. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week. Because they are constants, the names of an enum type's fields are in uppercase letters. In the Java programming language, you define an enum type by using the enum keyword. For example, you would specify a days-of-the-week enum type as: public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on. Here is some code that shows you how to use the Day enum defined above: public class EnumTest { Day day; public EnumTest(Day day) { this.day = day; } public void tellItLikeItIs() { switch (day) { case MONDAY: System.out.println("Mondays are bad."); break; case FRIDAY: System.out.println("Fridays are better."); break; case SATURDAY: case SUNDAY: System.out.println("Weekends are best."); break; default: System.out.println("Midweek days are so-so."); break; } } public static void main(String[] args) { EnumTest firstDay = new EnumTest(Day.MONDAY); firstDay.tellItLikeItIs(); EnumTest thirdDay = new EnumTest(Day.WEDNESDAY); thirdDay.tellItLikeItIs(); EnumTest fifthDay = new EnumTest(Day.FRIDAY); fifthDay.tellItLikeItIs(); EnumTest sixthDay = new EnumTest(Day.SATURDAY); sixthDay.tellItLikeItIs(); EnumTest seventhDay = new EnumTest(Day.SUNDAY); seventhDay.tellItLikeItIs(); } } The output is: Mondays are bad. Midweek days are so-so. Fridays are better. Weekends are best. Weekends are best.

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

26

Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system. for (Planet p : Planet.values()) { System.out.printf("Your weight on %s is %f%n", p, p.surfaceWeight(mass)); } Note: All enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else. In the following example, Planet is an enum type that represents the planets in the solar system. They are defined with constant mass and radius properties. Each enum constant is declared with values for the mass and radius parameters. These values are passed to the constructor when the constant is created. Java requires that the constants be defined first, prior to any fields or methods. Also, when there are fields and methods, the list of enum constants must end with a semicolon. Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself. In addition to its properties and constructor, Planet has methods that allow you to retrieve the surface gravity and weight of an object on each planet. Here is a sample program that takes your weight on earth (in any unit) and calculates and prints your weight on all of the planets (in the same unit): public enum Planet { MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH (5.976e+24, 6.37814e6), MARS (6.421e+23, 3.3972e6), JUPITER (1.9e+27, 7.1492e7), SATURN (5.688e+26, 6.0268e7), URANUS (8.686e+25, 2.5559e7), NEPTUNE (1.024e+26, 2.4746e7); private final double mass; // in kilograms private final double radius; // in meters Planet(double mass, double radius) { this.mass = mass; this.radius = radius; } private double mass() { return mass; } private double radius() { return radius; } // universal gravitational constant (m3 kg-1 s-2) public static final double G = 6.67300E-11; double surfaceGravity() { return G * mass / (radius * radius); } double surfaceWeight(double otherMass) { return otherMass * surfaceGravity(); } public static void main(String[] args) { double earthWeight = Double.parseDouble(args[0]); double mass = earthWeight/EARTH.surfaceGravity(); for (Planet p : Planet.values()) System.out.printf("Your weight on %s is %f%n",

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

27

p, p.surfaceWeight(mass)); } } If you run Planet.class from the command line with an argument of 175, you get this output: $ java Planet 175 Your weight on MERCURY is 66.107583 Your weight on VENUS is 158.374842 Your weight on EARTH is 175.000000 Your weight on MARS is 66.279007 Your weight on JUPITER is 442.847567 Your weight on SATURN is 186.552719 Your weight on URANUS is 158.397260 Your weight on NEPTUNE is 199.207413 Control Flow Statements The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code. This section describes the decision-making statements (if-then, if-then-else, switch), the looping statements (for, while, do-while), and the branching statements (break, continue, return) supported by the Java programming language. The if-then and if-then-else Statements The if-then Statement The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. For example, the Bicycle class could allow the brakes to decrease the bicycle's speed only if the bicycle is already in motion. One possible implementation of the applyBrakes method could be as follows: void applyBrakes(){ if (isMoving){ // the "if" clause: bicycle must moving currentSpeed--; // the "then" clause: decrease current speed } } If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end of the if-then statement. In addition, the opening and closing braces are optional, provided that the "then" clause contains only one statement: void applyBrakes(){ if (isMoving) currentSpeed--; // same as above, but without braces } Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more brittle. If a second statement is later added to the "then" clause, a common mistake would be forgetting to add the newly required braces. The compiler cannot catch this sort of error; you'll just get the wrong results. The if-then-else Statement The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. You could use an if-then-else statement in the applyBrakes method to take some action if the brakes are applied when the bicycle is not in motion. In this case, the action is to simply print an error message stating that the bicycle has already stopped. void applyBrakes(){ if (isMoving) { currentSpeed--; } else { System.err.println("The bicycle has already stopped!"); } } The following program, IfElseDemo, assigns a grade based on the value of a test score: an A for a score of 90% or above, a B for a score of 80% or above, and so on. class IfElseDemo { public static void main(String[] args) {

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

28

int testscore = 76; char grade; if (testscore >= 90) { grade = 'A'; } else if (testscore >= 80) { grade = 'B'; } else if (testscore >= 70) { grade = 'C'; } else if (testscore >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("Grade = " + grade); } } The output from the program is: Grade = C You may have noticed that the value of testscore can satisfy more than one expression in the compound statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the appropriate statements are executed (grade = 'C';) and the remaining conditions are not evaluated. The switch Statement Unlike if-then and if-then-else, the switch statement allows for any number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Classes and Inheritance) and a few special classes that "wrap" certain primitive types: Character, Byte, Short, and Integer (discussed in Simple Data Objects ). The following program, SwitchDemo, declares an int named month whose value represents a month out of the year. The program displays the name of the month, based on the value of month, using the switch statement. class SwitchDemo { public static void main(String[] args) { int month = 8; switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; default: System.out.println("Invalid month.");break; } } } In this case, "August" is printed to standard output. The body of a switch statement is known as a switch block. Any statement immediately contained by the switch block may be labeled with one or more case or default labels. The switch statement evaluates its expression and executes the appropriate case. Of course, you could also implement the same thing with if-then-else statements: int month = 8; if (month == 1) { System.out.println("January"); } else if (month == 2) { System.out.println("February"); }

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

29

. . . // and so on Deciding whether to use if-then-else statements or a switch statement is sometimes a judgment call. You can decide which one to use based on readability and other factors. An if-thenelse statement can be used to make decisions based on ranges of values or conditions, whereas a switch statement can make decisions based only on a single integer or enumerated value. Another point of interest is the break statement after each case. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, case statements fall through; that is, without an explicit break, control will flow sequentially through subsequent case statements. The following program, SwitchDemo2, illustrates why it might be useful to have case statements fall through: class SwitchDemo2 { public static void main(String[] args) { int month = 2; int year = 2000; int numDays = 0; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numDays = 31; break; case 4: case 6: case 9: case 11: numDays = 30; break; case 2: if ( ((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0) ) numDays = 29; else numDays = 28; break; default: System.out.println("Invalid month."); break; } System.out.println("Number of Days = " + numDays); } } This is the output from the program. Number of Days = 29 Technically, the final break is not required because flow would fall out of the switch statement anyway. However, we recommend using a break so that modifying the code is easier and less errorprone. The default section handles all values that aren't explicitly handled by one of the case sections. The while and do-while Statements The while statement continually executes a block of statements up to a particular condition is true. Its syntax can be expressed as: while (expression) { statement(s) } The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

30

evaluates to false. Using the while statement to print the values from 1 through 10 can be accomplished as in the following WhileDemo program: class WhileDemo { public static void main(String[] args){ int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } } } You can implement an infinite loop using the while statement as follows: while (true){ // your code goes here } The Java programming language also provides a do-while statement, which can be expressed as follows: do { statement(s) } while (expression); The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following program: class DoWhileDemo { public static void main(String[] args){ int count = 1; do { System.out.println("Count is: " + count); count++; } while (count <= 11); } } The for Statement The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows: for (initialization; termination; increment) { statement(s) } When using this version of the for statement, keep in mind that:  The initialization expression initializes the loop; it's executed once, as the loop begins.  When the termination expression evaluates to false, the loop terminates.  The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value. The following program, ForDemo, uses the general form of the for statement to print the numbers 1 through 10 to standard output: class ForDemo { public static void main(String[] args){ for(int i=1; i<11; i++){ System.out.println("Count is: " + i); } } } The output of this program is: Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

31

Count is: 6 Count is: 7 Count is: 8 Count is: 9 Count is: 10 Notice how the code declares a variable within the initialization expression. The scope of this variable extends from its declaration to the end of the block governed by the for statement, so it can be used in the termination and increment expressions as well. If the variable that controls a for statement is not needed outside of the loop, it's best to declare the variable in the initialization expression. The names i, j, and k are often used to control for loops; declaring them within the initialization expression limits their life span and reduces errors. The three expressions of the for loop are optional; an infinite loop can be created as follows: for ( ; ; ) { // infinite loop // your code goes here } The for statement also has another form designed for iteration through Collections and arrays This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read. To demonstrate, consider the following array, which holds the numbers 1 through 10: int[] numbers = {1,2,3,4,5,6,7,8,9,10}; The following program, EnhancedForDemo, uses the enhanced for to loop through the array: class EnhancedForDemo { public static void main(String[] args){ int[] numbers = {1,2,3,4,5,6,7,8,9,10}; for (int item : numbers) { System.out.println("Count is: " + item); } } } In this example, the variable item holds the current value from the numbers array. The output from this program is the same as before: Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Count is: 6 Count is: 7 Count is: 8 Count is: 9 Count is: 10 We recommend using this form of the for statement instead of the general form whenever possible. Branching Statements The break Statement The break statement has two forms: labeled and unlabeled. You saw the unlabeled form in the previous discussion of the switch statement. You can also use an unlabeled break to terminate a for, while, or do-while loop, as shown in the following BreakDemo program: class BreakDemo { public static void main(String[] args) { int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 }; int searchfor = 12; int i; boolean foundIt = false; for (i = 0; i < arrayOfInts.length; i++) { if (arrayOfInts[i] == searchfor) { foundIt = true;

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

32

break; } } if (foundIt) { System.out.println("Found " + searchfor + " at index " + i); } else { System.out.println(searchfor + " not in the array"); } } } This program searches for the number 12 in an array. The break statement, shown in boldface, terminates the for loop when that value is found. Control flow then transfers to the print statement at the end of the program. This program's output is: Found 12 at index 4 An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled break terminates an outer statement. The following program, BreakWithLabelDemo, is similar to the previous program, but uses nested for loops to search for a value in a two-dimensional array. When the value is found, a labeled break terminates the outer for loop (labeled "search"): class BreakWithLabelDemo { public static void main(String[] args) { int[][] arrayOfInts = { { 32, 87, 3, 589 }, { 12, 1076, 2000, 8 }, { 622, 127, 77, 955 } }; int searchfor = 12; int i; int j = 0; boolean foundIt = false; search: for (i = 0; i < arrayOfInts.length; i++) { for (j = 0; j < arrayOfInts[i].length; j++) { if (arrayOfInts[i][j] == searchfor) { foundIt = true; break search; } } } if (foundIt) { System.out.println("Found " + searchfor + " at " + i + ", " + j); } else { System.out.println(searchfor + " not in the array"); } } } This is the output of the program. Found 12 at 1, 0 The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is transferred to the statement immediately following the labeled (terminated) statement. The continue Statement The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. The following program, ContinueDemo , steps through a String, counting the

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

33

occurences of the letter "p". If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a "p", the program increments the letter count. class ContinueDemo { public static void main(String[] args) { String searchMe = "peter piper picked a peck of pickled peppers"; int max = searchMe.length(); int numPs = 0; for (int i = 0; i < max; i++) { //interested only in p's if (searchMe.charAt(i) != 'p') continue; //process p's numPs++; } System.out.println("Found " + numPs + " p's in the string."); }} Here is the output of this program: Found 9 p's in the string. To see this effect more clearly, try removing the continue statement and recompiling. When you run the program again, the count will be wrong, saying that it found 35 p's instead of 9. A labeled continue statement skips the current iteration of an outer loop marked with the given label. The following example program, ContinueWithLabelDemo, uses nested loops to search for a substring within another string. Two nested loops are required: one to iterate over the substring and one to iterate over the string being searched. The following program, ContinueWithLabelDemo, uses the labeled form of continue to skip an iteration in the outer loop. class ContinueWithLabelDemo { public static void main(String[] args) { String searchMe = "Look for a substring in me"; String substring = "sub"; boolean foundIt = false; int max = searchMe.length() - substring.length(); test: for (int i = 0; i <= max; i++) { int n = substring.length(); int j = i; int k = 0; while (n-- != 0) { if (searchMe.charAt(j++) != substring.charAt(k++)) { continue test; } } foundIt = true; break test; } System.out.println(foundIt ? "Found it" : "Didn't find it"); } } Here is the output from this program. Found it The return Statement The last of the branching statements is the return statement. The return statement exits from the current method, and control flow returns to where the method was invoked. The return statement has two forms: one that returns a value, and one that doesn't. To return a value, simply put the value (or an expression that calculates the value) after the return keyword. return ++count;

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

34

The data type of the returned value must match the type of the method's declared return value. When a method is declared void, use the form of return that doesn't return a value. return; Summary of Control Flow Statements The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. Unlike ifthen and if-then-else, the switch statement allows for any number of possible execution paths. The while and do-while statements continually execute a block of statements while a particular condition is true. The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once. The for statement provides a compact way to iterate over a range of values. It has two forms, one of which was designed for looping through collections and arrays. Questions 1. The most basic control flow statement supported by the Java programming language is the ___ statement. 2. The ___ statement allows for any number of possible execution paths. 3. The ___ statement is similar to the while statement, but evaluates its expression at the ___ of the loop. 4. How do you write an infinite loop using the for statement? 5. How do you write an infinite loop using the while statement? Exercises 1. Consider the following code snippet. 2. if (aNumber >= 0) 3. if (aNumber == 0) System.out.println("first string"); 4. else System.out.println("second string"); 5. System.out.println("third string"); a. What output do you think the code will produce if aNumber is 3? b. Write a test program containing the previous code snippet; make aNumber 3. What is the output of the program? Is it what you predicted? Explain why the output is what it is; in other words, what is the control flow for the code snippet? c. Using only spaces and line breaks, reformat the code snippet to make the control flow easier to understand. d. Use braces, { and }, to further clarify the code.

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

35

Unit III CLASS, OBJECTS AND METHODS Java is a true object-oriented language and therefore the underlying structure of all java programs is classes. Anything we wish to represent in a java program must be encapsulated in a class that defines the state and behaviour of the basic program components known as objects. Classes create objects and objects use methods to communicate between them. Classes provide a convenient method for packing together a group of logically related data items and functions that work on them. In java, the data items are called fields and the functions are called methods. Calling a specific method in an object is described as sending the object a message. A class is essentially a description of how to make an object that contains fields and methods. It provides a sort of template for an object and behaves like a basic data type such as int. It is therefore important to understand how the fields and methods are defined in a class and how they are used to build a java program that incorporates the basic OOP concepts such as encapsulation, inheritance and polymorphism. DEFINING A CLASS A class is a user-defined data type with a template that serves to define its properties. Once the class type has been defined, user can create “variables� of that type using declarations that are similar to the basic type declarations. In java, these variables are termed as instances of classes, which are the actual objects. The basic form of a class definition is:

class classname [extends superclassname] { [ variable declaration; ] [ methods declaration; ] } Everything inside the square brackets is optional. This means that the following would be a valid class definition: Class Empty { } ADDING VARIABLES Data is encapsulated in a class by placing data fields inside the body of the class definition. These variables called instance variables because they are created whenever an object of the class is instantiated. We can declare the instance variables exactly the same way as we declare local variables.

Example: class Rectangle { int length; int width; } The class Rectangle contains two integer type instance variables. It is allowed to declare them in one line as int length, width; Remember these variables are only declared and therefore no storage space has been created in the memory. Instance variables are also known as member variables.

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

36

ADDING METHODS A class with only data fields (and without methods that operate on that data) has no life. The objects created by such a class cannot respond to any messages. We must therefore add methods that are necessary for manipulating the data contained in the class. Methods are declared inside the body of the class but immediately after the declaration of instance variables. The general form of a method declaration is

type methodname (parameter-list) { method-body; }

Method declarations have four basic parts:  The name of the method (method name)  The type of the value the method returns (type)  A list of parameters (parameter-list)  The body of the method The type specifies the type of value the method would return. This could be a simple data type such as int as well as any class type. It could even be void type, if the method does not return any value. The method name is a valid identifier. The parameter list is always enclosed in parentheses. This list contains variable names and types of all the values we want to give to the method as input. The variables in the list are separated by commas. In the case where no input data are required, the declaration must retain the empty parentheses. Examples: (int m, float x, float y) / / Three parameters ( ) / / Empty list The body actually describes the operations to be performed on the data. Let us consider the Square class again and add a method getData( ) to it. class Square { int length; int widht; void getData (int x, int y ) { length = x ; width = y ; } } Note that the method has a return type of void because it does not return any value. We pass two integer values to the method which is then assigned to the instance variables length and width. The getData method is basically added to provide values to the instance variables. Notice that we are able to use directly length and width inside the method. CREATING OBJECTS An object in Java is essentially a block of memory that contains space to store all the instance variables. Creating an object is also referred to as instantiating an object. Objects in Java are created using the new operator. The new operator creates an object of the specified class and returns a reference to that object. Here is an example of creating an object of type Rectangle Square rect1 ; // declare rect1 = new Square( ); // instantiate

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

37

The first statement declares a variable to hold the object reference and the second one actually assigns the object reference to the variable. ACCESSING CLASS MEMBERS After creating objects one should assign values to these variables in order to use them in our program. All variables must be assigned values before they are used. Since we are outside the class, we cannot access the instance variables and the methods directly. To do this, we must use the concerned object and the dot operator as shown below:

objectname. variable name objectname.methodname (parameter-list); Here object name is the name of the object, variable name is the name of the instance variable inside the object that we wish to access, method name is the method that we wish to call, and parameter-list is a comma separated list of “actual values” (or expressions) that must match in type and number with the parameter list of the method name declared in the class. CONSTRUCTORS We know that all objects that are created must be given initial values. We have done this earlier using two approaches. The first approach uses the dot operator to access the instance variables and then assigns values to them individually. It can be a tedious approach to initialize all the variables of all the objects. The second approach takes the help of a method like getData to initialize each object individually using statements like, rect1. getData (15, 10); It would be simpler and more concise to initialize an object when it is first created. Java supports a special type of method, called constructor, that enables an object to initialize itself when it is created. Constructors have the same name as the class itself. Secondly, they do not specify a return type, not even void. This is because they return the instance of the class itself. METHODS OVERLOADING In java, it is possible to create methods that have the same name, but different parameter lists and different definitions. This is called method overloading. Method overloading is used when objects are required to perform similar tasks but using different input parameters. When we call a method in a object, java matches up the method name first and then the number and type of parameters to declare which one of the definitions to execute. This process is known as polymorphism: To create an overloaded method, all we have to do is to provide several different method definitions in the class, all with the same name, but with different parameter lists. The different may either be in the number or type of arguments. That is, each parameter list should be unique. Note that the method’s return type does not play any role in this. Here is an example of creating an overloaded method. STATIC MEMBERS We have seen that a class basically contains two sections. One declares variable and the other declares methods. These variables and methods are called instance variables and instance methods. This is because every time the class is instantiated, a new copy of each of them is created. They are accessed using the objects (with dot operator). Let us assume that we want to define a member that is common to all the objects and accessed without using a particular object. That is, the member belongs to the class as a whole rather than the objects created from the class. Such members can be defined as follows: static int count ; static int max (int x, int y); The members that are declared static as shown above are called static members. Since these members are associated with the class itself rather than individual objects, the static variables and static methods are often referred to as class variables and class methods in order to distinguish them from their counterparts, instance variables and instance methods.

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

38

Static variables are used when we want to have a variable common to all instances of a class. One of the most common examples is to have a variable that could keep a count of how many objects of a class have been created. Remember, Java creates only one copy for a static variable which can be used even if the class is never actually instantiated. Like static variables, static methods can be called without using the objects. They are also available for use by other classes. Methods that are of general utility but do not directly affect an instance of that class are usually declared as class methods. Java class libraries contain a large number of class methods. For example, the Math class of Java library defines many static methods to perform math operations that can be used in any program. We have used earlier statements of the types float x = Math.sqrt (25.0); The method sqrt is a class method (or static method) defined in Math class. INHERITANCE: EXTENDING A CLASS Reusability is yet another aspect of OOP paradigm. It is always nice if we could reuse something that already exists rather than creating the same all over again. Java supports this concept. Java classes can be reused in several ways. This is basically done by creating new classes, reusing the properties of existing ones. The mechanism of deriving a new class from an old one is called inheritance. The old class is known as the base class or super class or parent class and the new one is called the subclass or derived class or child class. The inheritance allows subclasses to inherit all the variables and methods of their parent classes. Inheritance may take different forms:  Single inheritance (only one super class)  Multiple inheritance (several super classes)  Hierarchical inheritance (one super class, many subclasses)  Multilevel inheritance (Derived from a derived class) These forms of inheritance are shown in Fig. 8.3. Java does not directly implement multiple inheritance. However, this concept is implemented using a secondary inheritance path in the form of interfaces. Defining a Subclass A subclass is defined as follows:

class subclassname extends superclassname { variables declaration ; methods declaration ; } The keyword extends signifies that the properties of the superclassname are extended to the subclassname. The subclass will now contain its own variables and methods as well those of the superclass. This kind of situation occurs when we want to add some more properties to an existing class without actually modifying it.

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

39

A

B

B

(a) Single inheritance

C

D

(b) Hierarchical inheritance

A

A

B

B

C

(c) Multilevel inheritance

(d) Multiple inheritance

Subclass Constructor A subclass constructor is used to construct the instance variables of both the subclass and the superclass. The subclass constructor uses the keyword super to invoke the constructor method of the superclass. The keyword super is used subject to the following conditions.  Super may only be used within a subclass constructor method  The call to superclass constructor must appear as the first statement within the subclass constructor  The parameters in the super call must match the order and type of the instance variable declared in the superclass. Multilevel Inheritance A common requirement in object-oriented programming is the use of a derived class as a super class. Java supports this concept and uses it extensively in building its class library. This concept allows us to build a chain of classes as shown in Fig

A

Superclass

Father

A

Intermediate superclass

Child

A

Grandfather

Subclass

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

40

Multilevel inheritance The class A serves as a base class for the derived class B which in turn serves as a base class for the derived class C. The chain ABC is known as inheritance path. A derived class with multilevel base classes is declared as follows. class A { ............ ............ } Class B extends A // First level { ............ ............ } class C extends B // Second level { ............ ............ } This process may be extended to any number of levels. The class C can inherit the members of both A and B. Hierarchical Inheritance Another interesting application of inheritance is to use it as a support to the hierarchical design of a program. Many programming problems can be cast into a hierarchy where certain features of one level are shared by many other below the level. As an example, Fig. 8.6 shows a hierarchical classification of accounts in a commercial bank. This is possible because all the accounts posses certain common features. OVERRIDING METHODS We have seen that a method defined in a super class is inherited by its subclass and is used by the objects created by the subclass. Method inheritance enables us to define and use methods repeatedly in subclasses without having to define the methods again in subclass. However, there may be occasions when we want an object to respond to the same method but have different behaviour when that method is called. That means, we should override the method defined in the superclass. This is possible by defining a method in the subclass that has the same name, same arguments and same return type as a method in the superclass. Then, when that method is called, the method defined in the subclass in invoked and executed instead of the one in the superclass. This is known as overriding. FINAL VARIABLES AND METHODS All methods and variables can be overridden by default in subclasses. If we wish to prevent the subclass from overriding the members of the superclass, we can declare them as final using the keyword final as a modifier. Example: final int SIZE = 100; final void showstatus( ) {...........} Making a method final ensures that the functionality defined in this method will never be altered in any way. Similarly, the value of a final variable can never be changed. Final variables, behave like class variables and they do not take any space on individual objects of the class. FINAL CLASSES Sometimes we may like to prevent a class being further subclassed for security reasons. A class that cannot be subclassed is called a final class. This is achieved in Jaga using the keyword final as follows : final class Aclass {..........} final class Bclass extends someclass {......} Any attempt to inherit these classes will cause an error and the compiler will not allow it.

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

41

Declaring a class final prevents any unwanted extensions to the class. It also allows the compiler to perform some optimisations when a method of a final class is invoked. FINALIZER METHODS We have seen that a constructor method is used to initialize an object when it s declared. This process is known as initialization. Similarly, Java supports a concept called finalization. Which is just opposite to initialization. We know that Java run-time is an automatic garbage collecting system. It automatically frees up the memory resources used by the objects. But objects may hold other non-object resources such as file descriptors or window system fonts. The garbage collector cannot free these resources. In order to free these resources we must use a finalizer method. This is similar to destructors in C++. The finalizer method is simply finalize( ) and can be added to any class. Java calls that method whenever it is about to reclaim the space for the object. The finalize method should explicitly define the tasks to be performed. ABSTRACT METHODS AND CLASSES We have seen that by making a method final we ensure that the method is not redefined in a subclass. That is, the method can never be subsclassed. java allows us to do something that is exactly opposite to this. That is, we can indicate that a method must always be redefined in a subclass, thus making overriding compulsory. This is done using the modifier keyword abstract in the method definition. Example: abstract class Shape { ........... ........... abstract void draw( ); ........... ........... } When a class contains one or more abstract method, it should also be declared abstract as shown in the example above. While using abstract class, we must satisfy the following conditions:  We cannot use abstract classes to instantiate objects directly. For example, Shape S = new Shape( ); is illegal because Shape is an abstract class.  The abstract methods of an abstract class must be defined in its subclass.  We cannot declare abstract constructors or abstract static methods. ARRAYS, STRINGS AND VECTORS STRINGS Strings manipulation is the most common part of many Java programs. Strings represent a sequence of characters. The easiest way to represent a sequence of characters in Java is by using a character array. Example:

X[0][1 ] X[0 ] X[1 ] X[2 ]

X[1][3 ]

Variable size arrays Char charArray [ ] = new char [ 4 ]; X[2][ CharArray [ 0 ] = ‘J ‘; CharArray [ 1 ] = ‘a’ ; 2] CharArray [ 2 ] = ‘v’ ; CharArray [ 3 ] = ‘a’ ; Although character arrays have the advantage of being able to query their length, they themselves are not good enough to support the range of operations we may like to perform on strings.

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

42

For example, copying one character array into another might require a lot of book keeping effort. Fortunately, Java is equipped to handle these situations more efficiently. In Java, strings are class objects and implemented using two classes, namely, String and StringBuffer. A Java string is an instantiated object of the String class. Java strings, as completed to C strings, are more reliable and predictable. This is basically due to C’s lack of bounds-checking. A Java string is not a character array and is not NULL terminated. Strings may be declared and created as follows:

string stringName; stringName = new String (“ string”); Example: String firstName; firstName = new String(“Anil”); These two statements may be combimed as follows: String firstname = new String (“Anil”); Like arrays, it is possible to get the length of string using the length method of the string class. int m = firstName.length( ); Note the use of parentheses here. Java strings can be concatenated using the + operator. Examples: String fullName = name1 + name2; String city1 = “New” + “Delhi”; Where name1 and name2 are Java strings containing string constants. Another example is: System, out.println (firstName + “Kumar”); String Arrays We can also create and use arrays that contain strings. The statement String itemArray[ ] = new String[3]; will create an itemArray of size 3 to hold three string constants. We can assign the strings to the item Array element by element using three different statements or more efficiently using a for loop. String Methods The String class defines a number of methods that allow us to accomplish a variety of string manipulation tasks. Table 9.1 lists some of the most commonly used string methods, and their tasks. Program 9.3. shows the use of the method compareTo( ) to sort an array of strings in alphabetical order. Some Most Commonly Used String Methods Method Call

Task performed

s2 = s1.toLowerCase; s2 = s1.toUpperCase; s2 = s1.replace (‘x’, ‘y’); s2 = s1.trim ( );

Converts the string s1 to all lowercase Converts the string s1 to all Uppercase Replace all appearances of x with y Remove white spaces at the beginning and end of the string s1 Returns ‘true’ if s1 = s2, ignoring the case of characters Gives the length of s1 Gives nth character of s1 Returns negative if s1<s2, positive if s1 > s2, and zero if s1 is equal s2 Concatenates s1 and s2 th Gives substring starting from n character th th Gives substring starting from n character up to m th (not including m ) Creates a string object of the parameter p (simple type or object) Creates a string representation of the object p Gives the position of the first occurrence of ‘x’ in the string s1 Gives the position of ‘x’ that occurs after nth position in the

s1.equals (s2) s1.length () s1.ChartAt (n) s1.compareTo (s2) s1.concat (s2) s1.substring (n) s1.substring (n, m) String.Valueof (p) s1.toString ( ) s1.indexof (‘x’) s1.indexof(‘x’, n)

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

String.Valueof (Variable)

43

string s1 Converts the parameter value to string representation

StringBuffer Class StringBuffer is a peer class of String. While String creates strings of fixed_length, StringBuffer creates strings of flexible length that can be modified in terms of both length and content. We can insert characters and substrings in the middle of a string, or append another string to the end. Table 9.2 lists some of the methods that are frequently used in string manipulations. Commonly Used StringBuffer Methods Method Task s1.setChartAt (n, ‘x’)

Modifies the nth character to x

s1.append (s2)

Appends the string s2 to s1 at the end

s1.insert (n, s2)

Inserts the string s2 at the position n of the string s1

s1.setLength (n)

Sets the length of the string s1 to n. If n<s1.length ( ) s1 is truncated. If n>s1.length ( ) zeros are added to s1

VECTORS C and C++ programmers will know that generic utility functions with variable arguments can be used to pass different arguments depending upon the calling situations. Java does not support the concept of variable arguments to a function. This feature can be achieved in Java through the use of the Vector class contained in the Java.util package. This class can be used to create a generic dynamic array known as vector that can hold objects of any type and any number. The objects do not have to be homogenous. Arrays can be easily implemented as vectors. Vectors are created like arrays as follows: Vector intVect = new Vector ( ) ; Vector list = new Vector ( 3);

// declaring without size // declaring with size

Note that a vector can be declared without specifying any size explicitly. A vector can accommodate an unknown number of items. Even, when a size is specified, this can be overlooked and a different number of items may be put into the vector. Remember, in contrast, an array must always have its size specified. Vectors possess a number of advantages over arrays. 1. It is convenient to use vectors to store objects. 2. A vector can be used to store a list of objects that may vary in size. 3. We can add and delete objects from the list as and when required. A major constraint in using vectors is that we cannot directly store simple data types in a vector; we can only store objects. Therefore, we need to convert simple types to objects. This can be done using the wrapper classes discussed in the next section. The vector class supports a number of methods that can be used to manipulate the vectors created. Important ones are listed in Table 9.3. Important Vector Methods Method Call Task performed list.addElement (item)

Adds the item specified to the list at the end

list.elementAt (10)

Gives the name of the 10 object

list.size ( )

Gives the number of objects present

list.removeElement (item)

Removes the specified item from the list

list.removeElementAt (n)

Removes the item stored in the nth position of the list

th

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

44

list.removeAllElements ( )

Removes all the elements in the list

list.copyInto (array)

Copies all items from list to array

list.insertElementAt (item, n)

Inserts the item at nth position

Program illustrates the use of arrays, strings and vectors. This program converts a string vector into an array of strings and displays the strings. Program working with vectors and arrays import java.util.*; // Importing Vector class class LanguageVector { public static void main(String args [ ]) { Vector list = new Vector ( ); int length = args.length; for (int i = 0; i < length; i++) { list.addElement (args [i]); } list.insertElementAt (“COBOL”,2); int size = list.size( ); string listArray[ ] = new String [size]; list.copyInto (listArray); System.out.println(“List of Languages:); for (int i = 0; i < size; i++) { System.out.println (listArray[i]); } } } WRAPPER CLASSES As pointed out earlier, vectors cannot handle primitive data types like int, float, long, char, and double. Primitive data types may be converted into object types by using the wrapper classes contained in the java.lang package. Table shows the sample data types and their corresponding wrapper class types. Wrapper Classes for Converting Simple Types Simple Type

Wrapper Class

boolean

Boolean

char

character

double

Double

float

Float

int

Integer

long

Long

The wrapper classes have a number of unique methods for handling primitive data types and objects. They are listed in the following tables. Converting Primitive Numbers to Object Numbers

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

45

Using Constructor Methods Constructor Calling

Note:

Conversion Action

Inter intVal = new Integer (i);

Primitive integer to Integer object

Float FicatVal = new Float (f);

Primitive float to Float object

Double DoubleVal = new Double (d);

Primitive double to Double object

Long LongVal = new Long (1);

Primitive long to Long object

i,f,d and l are primitive data values denoting int, float, double and long data types. They may be constants or variables. Converting Object Numbers to Primitive Numbers Using typeValue( ) methods Method Calling

Conversion Action

int i = IntVal.intValue( );

Object to primitive integer

float f = FloatVal.floatValue ( );

Object to primitive float

long 1 = longVal.longValue ( );

Object to primitive long

double d = DoubleVal.doubleValue( );

Object to primitive double

Converting Numbers to Strings Using String ( )Methods Method Calling

Conversion Action

str = Integer.tostring ( i )

Primitive integer to string

str = Float.toString (f);

Primitive float to string

str = Double.toString (d);

Primitive double to string

str = Long.toString (1);

Primitive long to string

Converting String Objects to Numeric Objects Using the Static Method ValueOf( ) Method Calling

Note:

Conversion Action

DoubleVal = Double.Valueof(str);

Converts string to Double object

FloatVal = Float.ValueOf (str);

Converts string to Float object

IntVal = Integer.Valueof (str);

Converts string to Integer object

LongVal = Long.ValueOf (str);

Converts string to Long object

These numeric objects may be converted to primitive numbers using the typeValue ( ) method as shown in Table 9.6. Method Calling

Conversion Action

int i = Integer.parseInt (str);

Converts string to primitive integer

long 1 = Long.parseLong (str);

Converts string to primitive long

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

46

Interfaces: Multiple Inheritances DEFININ INTERFACES An interface is basically a kind of class. Like classes, interfaces contain methods and variables but with a major difference. The difference is that interfaces define only abstract methods and final fields. This means that interfaces do not specify any code to implement these methods and data fields contain only constants. Therefore, it is the responsibility of the class the implements an interface to define the code for implementation of these methods. The syntax for defining an interface is very similar to that for defining a class. The general form of an interface definition is:

interface InterfaceName { variable declaration; methods declaration; } Here, Interface is the key word and InterfaceName is any valid Java variable (just like class names). Variables are declared as follows:

static final type variableName = Value; Note that all variables are declared as constants. Methods declaration will contain only a list of methods without any body statements. Example:

return-type methodName1 (parameter_list); Here is an example of an interface definition that contains two variables and one method.

interface Item { static final int code = 1001; static final String name = “Fan�; void display ( ); }

Note that the code for the method is not included in the interface and the method declaration simply ends with a semicolon. The class that implements this interface must define the code for the method.

Another example of an interface is:

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

47

interface Area { final static float pi = 3.142F; float computer (float x, float y); void show ( ); }

EXTENDING INTERFACES Like classes, interfaces can also be extended. That is, an interface can be subinterfaced from other interfaces. The new subinterface will inherit all the members of the superinterface in the manner similar to subclasses. This is achieved using the keyword extends as shown below:

interface name 2 extends name 1 { body of name2 } For example, we can put all the constants in one interface and the methods in the other. This will enable us to use the constants in classes where the methods are not required. Example:

interface ItemConstants { int code = 1001; string name = “Fan”; } interface Item extends ItemConstants { void display ( ); }

The interface Item would inherit both the constants code and name into it. Note that the variables name and code are declared like simple variables. It is allowed because all the variable in an interface are treated as constants although the keywords final and static are not present. We can also combine several interfaces together into a single interface. Following declarations are valid:

interface ItemConstants { int code = 1001; String name = “Fan”; } interface ItemMethods { void display ( ); } interface Item extends ItemConstants, ItemMethods { ...........

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

48

........... } While interfaces are allowed to extend to other interfaces, subinterfaces cannot define the methods declared in the superinterfaces. After all, subinterfaces are still interfaces, not class. Instead, it is the rensponsibility of any class that implements the derived interface to define all the methods. Note that when an interface extends two or more interfaces, they are separated by commas. It is important to remember that an interface cannot extend classes. This would violate the rule that an interface can have only abstract methods and constants. IMPLEMENTING INTERFACES Interfaces are used as “superclasses” whose properties are inherited by classes. It is therefore necessary to create a class that inherits the given interface. This is done as follows:

class classname implements interfacename { body of classname } Here the class classname “implements” the interface interfacename. A more general form of implementation may look like this:

class classname extends superclass implements interface1, interface2,.... } body of classname }

This shows that a class can extend another class while implementing interfaces. When a class implements more than one interface, they are separated by a comma Implementation of interfaces as class types is illustrated by Program. In this program, first we create an interface Area and implement the same in two different classes, Rectangle and Circle. We create an instance of each class using the new operator. Then we declare an object of type Area, the interface class. Now, we assign the reference to the Rectangle object rect to area. When we call the compute method of area, the computer method of Rectangle class is invoked. We repeat the same thing with the Circle object. Program 1 Implementing interfaces // InterfaceTest.java interface Area // Interface defined { final static float pi = 3.14F; float compute (float x, float y); } class Rectangle implements Area // Interface impleented { public float computer (float x, float y) { return (x * y); } } class Circle implements Area // Another implementation { public float computer (float x, float y) { return (pi *x*x);

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

49

} } class InterfaceTest { public static void main (String args[ ]) { Rectangle rect = new Rectangle( ); Circle cir = new Circle( ); Area area;

// Interface object

area = rect; System.out.println(“Area of Rectangle =” + area.computer(10,20)); area = cir; System.out.println(“Area of Circle = “ + area.computer(10,0)); } } Any number of dissimilar classes can implement an interface. However, to implement the methods, we need to refer to the class objects as types of the interface rather than types of their respective classes. Note that if a class that implements an interface does not implement all the methods of the interface, then the class becomes an abstract class and cannot be instantiate.

Interface

Class

A

Implementation

A

Extension

Class

B

Class

Extension

B

Extension

Interface

E Implementati on

(a) C

Class

Interface

B

Interface

D

Class

C

A

A

Implementati on Class (c)

(b)

C

Class

Interfa ce Extensio n

C (d)

B

Interface Implementati

ACCESSING INTERFACE VARIABLES on Interfaces can be used to declare a set of constants that can be used in different classes. D Clas This is similar to creating header files in C++ to contain a large number of constants. Since such s methods. The interfaces do not contain methods, there is no need to worry about implementing my constant values will be available to any class that implements the interface. The values can be used

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

50

in any method, as part of any variable declaration, or anywhere where we can use a final value. Example: interface A { int m = 10; int n = 50; } class B implements A { int x = m; void methodB (int size) { .......... .......... if (size < n) .......... } }

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

51

UNIT IV Packages : Putting Classes Together We have repeatedly stated that one of the main features of OOP is its ability to reuse the code already created. One way of achieving this is by extending the classes and implementing the interfaces.This is limited to reusing the classes within a program. What if we need to use classes from other programs without physically copying them into the program under development? This can be accomplished in Java by using what is known as packages, a concept similar to “class libraries” in other languages. Another way of achieving the reusability in Java, therefore, is to use packages. Packages we Java’s way of grouping a variety of classes and/or interfaces together. The grouping is usually done according to functionality. In fact, packages act as “containers” for classes. By organizing our classes into packages we achieve the following benefits: 1. The classes contained in the packages of other programs can be easily reused. 2. In packages, classes can be unique compared with classes in other packages. That is, two classes in two different packages can have the same name. They may be referred by their fully qualified name, comprising the package name and the class name. 3. Packages provide a way to “hide” classes thus preventing other programs or packages from accessing classes that are meant for internal use only. 4. Packages also provide a way for separating “design” from “coding”. First we can design classes and decide their relationships, and then we can implement the Java code needed for the methods. It is possible to change the implementation of any method without affecting the rest of the design. For most applications, we will need to use two different sets of classes, one for the internal representation of our program’ data, and the other for external presentation purposes. We may have to build our own classes for handling our data and use existing class libraries of designing user interfaces. Java packages are therefore classified into two types. The first category is known as Java system packages and the second is known as user defined packages. We shall consider both the categories of packages in this chapter and illustrate how to use them in our programs. SYSTEM PACKAGES Java system provides a large number of classes grouped into different packages according to functionality. Most of the time we use the packages available with the Java system. Figure 11.1 shows the functional breakdown of packages that are frequently used in the programs. Table 11.1 shows the classes the belong to each package.

Java

Java system packages

lang

util

io

awt

net

applet

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

52

Java System Packages and Their Classes Package name

Contents

java.lang

Language support classes. These are classes that Java compiler itself uses and therefore they are automatically imported. They include classes for primitive types, strings, math functions, threads and exceptions.

java.util

Language utility classes such as vectors, has tables, random numbers, date, etc.

java.io

Input/output support classes. They provide facilities for the input and output of data.

java.awt

Set of classes for implementing graphical user interface. They include classes for window, buttons, lists, menus and so on.

java.net

Classes for networking. They include classes for communicating with local computers as well as with internet servers.

java.applet

Classes for creating and implementing applets.

USING SYSTEM PACKAGES The packages are organised in a hierarchical structure as illustrated in Fig. This shows that the package named java contains the package awt, which in turn contains various classes required for implementing graphical user interface.

awt Color

Package containing awt package

Graphics

Font

    Image

Package containing classes

Classes containing methods

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

53

There are two ways of accessing the classes stored in a package. The first approach is to use the fully qualified class name of the class that we want to use. This is done by using the package name containing the class and then appending the class name to it using the dot operator. For example, if we want to refer to the class Color in the awt package, then we may do so as follows: java.awt.Colour Notice that awt is a package within the package java and the hierarchy is represented by separating the levels with dots. This approach is perhaps the best and easiest one if we need to access the class only once or when we need not have to access any other classes of the package. But, in many situations, we might want to use a class in a number of places in the program or we may like to use many of the classes contained in a package. We may achieve this easily as follows:

import packagename.classname; or import packagename.*; These are known as import statements and must appear at the top of the file, before any class declarations. The first statement allows the specified class in the specified package to be imported. For example, the statement import java.awt.Color; imports the class Colour and therefore the class name can now be directly used in the program. There is no need to use the package name to qualify the class. The second statement imports every class contained in the specified package. For example, the statement import java.awt.*; will bring all classes of java.awt package.

NAMING CONVENTIONS Packages can be named using the standard Java naming rules. By convention, however, packages begin with lowercase letters. This makes it easy for users to distinguish package names from class names when looking at an explicit reference to a class. We know that all class names, again by convention, begin with an uppercase letter. For example, look at the following statement: double y = java.lang.Math.sqrt(x);

package class method name name name This statement uses a fully qualified class name Math to invoke the method sqrt( ). Note that methods begin with lowercase letters. Consider another example: java.awt.Point pts[ ]; This statement declares an array of Point type objects using the fully qualified class name. Every package name must be unique to make the best use of packages. Duplicate names will cause run-time errors. Since multiple users work on Internet, duplicate package names are unavoidable. Java designers have recognised this problem and therefore suggested a package naming convention that ensures uniqueness. This suggests the use of domain names as prefix to the preferred package names. For example: cbe.psg.mypackage Here cbe denotes city name and psg denotes organisation name. Remember that we can create a hierarchy of packages within packages by separating level with dots.

CREATING PACKAGES We have seen in detail how Java system packages are organised and used. Now, let us see how to create our own packages. We must first declare the name of the package using the package keyboard followed by a package name. This must be the first statement in a Java source file (except

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

54

for comments and white spaces). Then we define a class, just as we normally define a class. Here is an example: package firstPackage; // package declaration public class FirstClass // class definition { .......... .......... (body of class) .......... } Here the package name is firstPackage. The class FirstClass is now considered a part of this package. This listing would be saved as a file called FirstClass.java, and located in a directory named first Package. When the source file is compiled, Java will create a.class file and store it in the same directory. Remember that the .class files must be located in a directory that has the same name as the package, and this directory should be a subdirectory of the directory where classes that will import the package are located. To recap, creating our own package involves the following steps: 1. Declare the package at the beginning of a file using the form

package packagename; 2. 3. 4. 5.

Define the class that is to be put in the package and declare in public. Create a subdirectory under the directory where the main source files are stored. Store the listing as the classname .java file in the subdirectory created. Compile the file. This creates .class file in the subdirectory. Remember that case is significant and therefore the subdirectory name must match the package name exactly. As pointed out earlier, Java also supports the concept of package hierarchy. This is done by specifying multiple names in a package statement, separated by dots. Example: package firstPackage.secondPackage; This approach allows us to group related classes into a package and then group related packages into a larger package. Remember to store this package in a subdirectory named firstPackage\secondPackage. A Java package file can have more than one class definitions. In such cases, only one of the classes may be declared public and that class name with .java extension is the source the file name. When a source file with more than one class definition is compiled. Java creates independent .class files for those classes. ACCESSING A PACKAGE It will be recalled that we have discussed earlier that a Java system package can be accessed either using a fully qualified class name or using a shortcut approach through the import statement. We use the import statement when there are many references to a particular package or the package name is too long and unwieldy. The same approaches can be used to access the user-defined packages as well. The import statement can be used to search a list of packages for a particular class. The general form of import statement for searching a class is as follows:

import package1 [ .package2 ] [. package3]. classname; Here package1 is the name of the top level package, package2 is the name of the package that is inside the package1, and so on. We can have any number of packages in a package hierarchy. Finally, the explicit classname is specified.

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

55

Note that the statement must end with a semicolon (;). The import statement should appear before any class definitions in a source file. Multiple import statements are allowed. The following is an example of importing a particular class: import firstPackage.secondPackage.MyClass; After defining this statement, all the members of the class Myclass can be directly accessed using name or its objects (as the case may be) directly without using the package name. We can also use another approach as follows: import packagename.*; Here, packagename may denote a single package or a hierarchy of packages as mentioned earlier. The star (*) indicates that the compiler should search this entire package hierarchy when it encounters a class name. This implies that we can access all classes contained in the above package directly. The major drawback of the shortcut approach is that it is difficult to determine from which package a particular member came. This is particularly true when a large number of packages are imported. But the advantage is that we need not have to use long package names repeatedly in the program.

USING A PACKAGE Let us now consider some simple programs that will use classes from other packages. The listing below shows a package named package 1 containing a single class ClassA. package package1; public class ClassA { public void displayA( ) { System.out.println(“Class A�); } } This source file should be named ClassA.java and stored in the subdirectory package1 as stated earlier. Now compile this java file. The resultant ClassA.class will be stored in the same directory. Now consider the listing shown below: import package1.ClassA; class PackageTest1 { public static void main(String args[ ]) { ClassA objectA = new ClassA( ); objectA.displayA( ); } } This listing shows a simple program that imports the class ClassA from the package package1. The source file should be saved as PackageTest1.java and then compiled. The source file and the compiled file would be saved in the directory of which package1 was a subdirectory. Now we can run the program and obtain the results. During the compilation of packageTest1.java the compiler checks for the file ClassA.class in the package1 directory for information it needs, but i does not actually include the code from ClassA.class in the file PackageTest1.class. When the PackageTest1 program is run, Java looks for the file PackageTest1.class and loads it using something called class loader. Now the interpreter knows that it also needs the code in the file ClassA.class and loads it as well. Now let us consider another package named package2 containing again a single class as shown below: package package2; public class ClassB

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

56

{ protected in m = 10 public void displayB ( ) { System.out.println(“Class B”); System.out.println(“m = “ + m); } } As usual, the source file and the compiled file of this package are located in the subdirectory package2. MULTITHREADED PROGRAMMING Those who are familiar with the modern operating systems such as Windows 95 may recognize that they can execute several programs simultaneously. This ability is known as multitasking. In system’s terminology, it is called multithreading. Multithreading is a conceptual programming paradigm where a program (process) is divided into two or more subprograms (process), which can be implemented at the same time in parallel. For example, one subprogram can display an animation on the screen while another may build the next animation to be displayed. This is something similar to dividing a task into subtasks and assigning them to different people for execution independently and simultaneously. In most of our computers, we have only a single processor and therefore, in reality, the processor is doing only one thing at a time. However, the processor switches between the processes so fast that it appears to human beings that all of them are being done simultaneously. Java programs that we have seen and discussed so far contain only a single sequential flow of control. This is what happens when we execute a normal program. The program begins, runs through a sequence of executions, and finally ends. At any given point of time, there is only one statement under execution. A thread is similar to a program that has a single flow of control. It has a beginning, a body, and an end, and executes commands sequentially. In fact, all main programs in our earlier examples can be called single-threaded programs. Every program will have at least one thread as shown in Fig. 12.1. A unique property of Java is its support for multithreading. That is, Java enables us to use multiple flows of control in developing programs. Each flow of control may be thought of as a separate tiny program (or module) known as a thread that runs in parallel to others as shown in Fig.12.2. A program that contains multiple flows of control is known as multithreaded program. Figure illustrates a Java program with four threads, one main and three others. The main thread is actually the main method module, which is designed to create and start the other three threads, namely A, B and C.

class ABC { ........... ........... ...........

Beginning Single-threaded body of execution End

........... ........... ........... ........... Once initiated by the main thread, the threads A, B, and C run concurrently and share the ........... three threads, namely A, B and C. Once initiated by the main thread, the threads A, B and C run concurrently and share the ........... resources jointly. It is like people living in joint families and sharing certain resources among all of } of a language to support multithreads is referred to as concurrency. Since threads them. The ability

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

57

in Java are subprograms of a main application program and share the same memory space, they are known as lightweight threads or lightweight processes. It is important to remember that ‘threads running in parallel’ does not really mean that they actually run at the same time. Since all the threads are running on a single processor, the flow of execution is shared between the threads. The Java interpreter handles the switching of control between the threads in such a way that it appears they are running concurrently. Multithreading is a powerful programming tool that makes Java distinctly different from its fellow programming languages. Multithreading is useful in a number of ways. It enables programmers to do multiple things at one time. They can divide a long program (containing operations that are conceptually concurrent) into threads and execute them in parallel. For example, we can send tasks such as printing into the background and continue to perform some other task in the foreground. This approach would considerably improve the speed of our programs. Threads are extensively used in Java-enabled browsers such as HotJava. These browsers can download a file to the local computer, display a Web page in the window, output another Web page to a printer and so on. Any application we are working on that requires two or more things to be done at the same time is probably a best one for use of threads. CREATING THREADS Creating threads in Java is simple. Threads are implemented in the form of objects that contain a method called run( ). The run( ) method is the heart and soul of any thread. It makes up the entire body of a thread and is the only method in which the thread’s behaviour can be implemented. A typical run( ) would appear as follows:

public void run ( ) { ............ ............ (statements for implementing thread) ............ } The run( ) method should be invoked by an object of the concerned thread. This can be achieved by creating the thread and initiating it with the help of another thread method called start( ). A new thread Can be created in two ways. 1. By creating a thread class: Define a class that extents Thread class and override its run( ) method with the code required by the thread. 2. By converting a class to a thread: Define a class that implements Runnable interface. The Runnable interface has only one method, run( ), that is to be defined in the method with the code to be executed by the thread. The approach to be used depends on what the class we are creating requires. If it requires to extend another class, then we have no choice but to implement the Runnable interface, since java classes cannot have two superclasses. EXTENDING THE THREAD CLASS We can make our class runnable as a thread by extending the class java.lang.Thread. This gives us access to all the thread method directly. It includes the following steps: 1. Declare the class as extending the Thread class. 2. Implement the run( ) method that is responsible for executing the sequence of code that the thread will execute. 3. Create a thread object and call start( ) method to initiate the thread execution. Declaring the Class The Thread class can be extended as follows: class MyThread extends Thread { .......... .......... ..........

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

58

} Now we have a new type of thread MyThread. Implementing the run( ) Method The run( ) method has been inherited by the class MyThread. We have to override this method in order to implement the code to be executed by our thread. The basic implementation of run( ) will look like this: public void run( ) { ......... ......... // Thread code here ......... } When we start the new thread, Java calls the thread’s run( ) method, so it is the run( ) where all the action takes place. Starting New Thread To actually create and run an instance of our thread class, we must write the following: MyThread aThread = new MyThread( ); aThread.start( ); //invokes run( ) method The first line instantiates a new object of class MyThread. Note that this statement just creates the object. The thread that will run this object is not yet running. The thread is in a newborn state. The second line calls the start( ) method causing the thread to move into the runnable state. Then, the Java runtime will schedule the thread to run by invoking its run( ) method. Now, the thread is said to be n the running state. STOPPING AND BLOCKING A THREAD Stopping a Thread Whenever we want to stop a thread from running further, we may do so by calling its stop( ) method, like: aThread.stop( ); This statement causes the thread to move to the dead state. A thread will also move to the dead state automatically when it reaches the end of its method. The stop( ) method may be used when the premature death of a thread is desired. Blocking a Thread A thread can also be temporarily suspended or blocked from entering into the runnable and subsequently running state by using either of the following thread methods: sleep( ) // blocked for a specified time suspend( ) // blocked until further orders wait( ) // blocked until certain condition occurs These methods cause the thread to go into the blocked (or not-runnable) state. The thread will return to the runnable state when the specified time is elapsed in the case of sleep( ), the resume( ) method is invoked in the case of suspend( ), and the notify( ) method is called in the case of wait( ). LIFE CYCLE OF A THREAD During the life time of a thread, there are many states it can enter. They include: 1. Newborn state 2. Runnable state 3. Running state 4. Blocked state 5. Dead state A thread is always in one of these five states. It can move from one state to another via a variety of ways as shown in Fig..

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

New Thread

59

Newbor n stop

start

stop Active Thread

Running

Running

Dea d

yield

suspend sleep wait

Idle Thread (Not Runnable)

Killed Threa d

stop

resume notify

Blocked

Newborn State When we create a thread object, the thread is born and is said to be in newborn state. The thread is not yet scheduled for running. At this state, we can do only one of the following things with it:  Schedule it for running using start( ) method.  Kill it using stop( ) method. If scheduled, it moves to the runnable state (fig.). if we attempt to use any other method at this stage, an exception will be thrown.

Newbor n

Runnabl e state

Dead state

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

60

Runnable State The runnable state means that the thread is ready for execution and is waiting for the availability of the processor. That is, the thread has joined the queue of threads that are waiting for execution. If all threads have equal priority, then they are given time slots for execution in round robin fashion, i.e., first-come, first-serve manner. The thread that relinquishes control joins the queue at the end and again waits for its turn. This process of assigning time to threads is known as time-slicing. However, if we want a thread to relinquish control to another thread of equal priority before its turn comes, we can do so by using the yield( ) method (Fig.). yield

Runnin g Thread

Runnable Threads

Running State Running means that the processor has given its time to the thread for its execution. The thread runs until it relinquishes control on its own or it is preempted by a higher priority thread. A running thread may relinquish its control in one of the following situations. 1. It has been suspended using suspend( ) method. A suspended thread can be revived by using the resume( ) method. This approach is useful when we want to suspend a thread for some time due to certain reason, but do not want to kill it.

Suspend

resume Relinquishing control using suspend( ) method 2.Running It has been made to sleep. We can put a thread to sleep for a specified time period using the Runnable Suspende method sleep(time) where time is in milliseconds. This means that the thread is out of the d as this time queue during this time period. The thread re-enters the runnable state as soon period is elapsed.

sleep(t)

after t

Relinquishing control using sleep( ) method Running Runnable Sleeping 3. It has been told to wait until some event occurs. This is done using the the wait( ) method. The thread can be scheduled to run again using the notify( ) method.

wait

notify

Running Relinquishing control using wait( ) method Waiting Blocked State A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the running state. The happens when the thread is suspended, sleeping, or waiting in FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

61

order to satisfy certain requirements. A blocked thread is considered “not runnable” but not dead and therefore fully qualified to run again. Dead State Every thread has a life cycle. A running thread ends its life when it has completed executing its run( ) method. It is a natural death. However, we can kill it by sending the stop message to it at any state thus causing a premature death to it. A thread can be killed as soon it is born, or while it is running, or even when it is in “not runnable” (blocked) condition. USING THREAD METHODS We have discussed how Thread class methods can be used to control the behaviour of a thread. We have used the methods start( ) and run( ),yield( ), sleep( ) and stop( ) methods in example program. THREAD EXCEPTIONS Note that the call to sleep( ) method is enclosed in a try block and followed by a catch block. This is necessary because the sleep( ) method throws an exception, which should be caught. If we fail to catch the exception, program will not compile. Java run system will throw IllegalThreadStateException whenever we attempt to invoke a method that a thread cannot handle in the given state. For example, a sleeping thread cannot deal with the resume( ) method because a sleeping thread cannot receive any instructions. The same is true with the suspend( ) method when it is used on a blocked (Not Runnable) thread. Whenever we call a thread method that is likely to throw an exception, we have to supply an appropriate exception handler to catch it. The catch statement may take one of the following forms: catch (ThreadDeath e) { ........... ........... // Killed thread } catch (InterruptedException e) { ........... ........... // Cannot handle it in the current state } catch (Illegal1Argument Exception e) { ........... ........... // Illegal method argument } catch (Exception e) { ........... ........... // Any other } Exception handling is discussed in detail in Chapter 13.

THREAD PRIORITY In Java, each thread is assigned a priority, which affects the order in which it is scheduled for running. The threads that we have discussed so far are of the same priority. The threads of the same priority are given equal treatment by the Java scheduler and, therefore, they share the processor on a first-come, first-serve basis. Java permits us to set the priority of a thread using the setPriority( ) method as follows:

ThreadName.setPriority(intNumber); The intNumber is an integer value to which the thread’s priority is set. The Thread class defines several priority constants:

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

62

MIN_PRIORITY = 1 NORM_PRIORITY =5 MAX_PRIORITY = 10 The intNumber may assume one of these constant or any value between 1 and 10. Note that the default setting is NORM_PRIORITY. Most user-level processes should use NORM_PRIORITY, plus or minus 1. Back-ground tasks such as network I/O and screen repainting should use a value very near to the lower limit. We should be very cautious when trying to use very high priority values. This may defeat the very purpose of using multithreads. By assigning priorities to threads, we can ensure that they are given the attention (or lack of it) they deserve. For example, we may need to answer an input as quickly as possible. Whenever multiple threads are ready for execution, the Java system chooses the highest priority thread and executes it. For a thread of lower priority to gain control, one of the following things should happen: 1. It stops running at the end of run( ). 2. It is made to sleep using sleep( ). 3. It is told to wais using wait( ). However, if another thread of a higher priority comes along, the currently running thread will be preempted by the incoming thread thus forcing the current thread to move to the runnable state. Remember that the highest priority thread always preempts any lower priority threads. SYNCHRONIZATION So far, we have seen threads that use their own data and methods provided inside their run( ) methods. What happens when they try to use data and methods outside themselves? On such occasions, they may compete for the same resources and may lead to serious problems. For example, they may compete for the same resources and may lead to serious problems. For example, one thread may try to read a record from a file while another is still writing to the same file. Depending on the situation, we may get strange results. Java enables us to overcome this problem using a technique known as synchronization. In case of Java, the keyword synchronised helps to solve such problem by keepings a watch on such locations. For example, the method that will read information from a file and the method that will update the same file may be declared as synchronized. Example: synchronized void update ( ) { ........... ........... // code here is synchronized ........... } When we declare a method synchronized, Java creates a “monitor� and hands it over to the thread that calls the method first time. As long as the thread holds the monitor, no other thread can enter the synchronized section of code. A monitor is like a key and the thread that holds the key can only open the lock. It is also possible to mark a block of code as synchronized as shown below: synchronized (lock-object) { .......... // code here is synchronized .......... } Whenever a thread has completed its work of using synchronized method (or block of code), it will hand over the monitor to the next thread that is ready to use the same resource. An interesting situation may occur when two or more threads are waiting to gain control of a resource. Due to some reason, the condition on which the waiting threads rely on to gain control does not happen. This results in what is known as deadlock. For example, assume that the thread A must access Method 1 before it can release Method2, but the thread B cannot release Method1 until it gets hold of Method2. Because these are mutually exclusive conditions, a deadlock occurs. The code below illustrates this: Thread A

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

63

synchronized method2 ( ) { synchronized method1 ( ) { .......... .......... } } Thread B synchronized method1 ( ) { synchronized method2 ( ) { .......... .......... } } IMPLEMENTING THE ‘RUNNABLE’ INTERFACE We stated earlier that we can create threads in two ways: one by using the extended Thread class and another by implementing the Runnable interface. We have already discussed in detail how the Thread class is used for creating and running threads. In this section, we shall see how to make use of the Runnable interface to implement threads. The Runnable interface declares the run( ) method that is required for implementing threads in our programs. To do this, we must perform the steps listed below: 1. Declare the class as implementing the Runnable interface. 2. Implement the run( ) method. 3. Create a thread by defining an object that is instantiated from this “runnable” class as the target of the thread. 4. Call the thread’s start( ) method to run the thread. Program illustrates the implementation of the above steps. In main method, we first create an instance of X and then pass this instance as the initial value of the object threadX (an object of Thread Class). Whenever, the new thread threadX starts up, its run( ) method calls the run( ) method of the target object supplied to it. Here, the target object is runnable. If the direct reference to the thread threadX is not required, then we may use a shortcut as shown below: new Thread (new x( )).start( ); Program 4 Using Runnable interface class X implements Runnable //Step 1 { //Step 2 public void run( ) { for(int i = 1; i<=10; i++) { System.out.println(“tThreadX : “+i); } System.out.println(“End of ThreadX”); } } class RunnableTest { public static void main(String args[ ]) { X runnable = new X( ); Thread threadX = new Thread(runnable);//Step 3 threadx.start( ); // Step 4 system.out.println(“End of main Thread:); } }

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

64

MANAGING ERRORS AND EXCEPTIONS Rarely does a program run successfully at its very first attempt. It is common to make mistakes while developing as well as typing a program. A mistake might lead to an error causing the program to produce unexpected results. Errors are the wrongs that can make a program go wrong. An error may produce an incorrect output or may terminate the execution of the program abruptly or even may cause the system to crash. It is therefore important to detect and manage properly all the possibly error conditions in the program so that the program will not terminate or crash execution. TYPES OF ERRORS Errors may broadly be classified into two categories:  Compile-time errors  Run-time errors Compile-Time Errors All syntax errors will be detected and displayed by the Java compiler and therefore these errors are known as compile-time errors. Whenever the compiler displays an error, it will not create the .class file. It is therefore necessary that we fix all the errors before we can successfully compile and run the program. Program Illustration of compile-time errors /* This program contains an error */ class Error1 { public static void main(String args[ ]) { System.out.println(“Hello Java!”) // Missing; } } The Java compiler does a nice job of telling us where the errors are in the program. For example, if we have missed the semicolon at the end of print statement in Program 13.1, the following message will be displayed in the screen:

Error1.java :7: ‘;’ expected System.out.println (“Hello Java!”) ^ 1 error We can now go to the appropriate line, correct the error, and recompile the program. Sometimes, a single error may be the source of multiple errors later in the compilation. For example, use of an undeclared variable in a number of places will cause a series of errors of type “undefined variable”. We should generally consider the earliest errors as the major source of our problem. After we fix such an error, we should recompile the program and look for other errors. Most of the compile-time errors are due to typing mistakes. Typographical errors are hard to find. We may have to check the code word by word, or even character by character. The most common problems are:  Missing semicolons  Missing (or mismatch of) brackets in classes and methods  Misspelling of identifiers and keywords  Missing double quotes in strings  Use of undeclared variables  Incompatible types in assignments/initialization  Bad references to objects  Use of = in place of = = operator Other errors we may encounter are related to directory paths. An error such as java : command not found

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

65

means that we have not set the path correctly. We must ensure that the path includes the directory where the Java executables are stored. Run-Time Errors Sometimes, a program may compile successfully creating the .class file but may not run properly. Such programs may produce wrong results due to wrong logic or may terminate due to errors such as stack overflow. Most command run-time errors are:  Dividing an integer by zero  Accessing an element that is out of the bounds of an array.  Trying to store a value into an array of an incompatible class or type.  Trying to cast an instance of a class to one of its subclasses.  Passing a parameter that is not in a valid range or value for a method.  Trying to illegally change the state of a thread.  Attempting to use a negative size for an array.  Using a null object reference as a legitimate object reference to access a method or a variable.  Converting invalid string to a number.  Accessing a character that is out of bounds of a string.  And many more When such errors are encountered, Java typically generates an error message and aborts the program. Program 13.2 illustrates how a run-time error causes termination of execution of the program. Program Illustration of run-time errors class Error2 { public static void main(String args[ ]) { int a = 10; int b = 5; int c = 5; int x = a/(b-c); //Division by zero System.out.println(“x = “ + x); int y = a/(b+c); System.out.println(“y = “ + y); { } Program is syntactically correct and therefore does not cause any problem during compilation. However, while executing, it displays the following message and stops without executing further statements. java.lang.ArithmeticException: / by zero at Error2.main(Error2.java:10) When Java run-time tries to execute a division by zero, it generates an error condition, which causes the program to stop after displaying an appropriate message. EXCEPTIONS An exception is a condition that is caused by a run-time error in the program. When the Java interpreter encounters an error such as dividing an integer by zero, it creates an exception object and throws it( (i.e., informs us that an error has occurred). If the exception object is not caught and handled property, the interpreter will display an error message as shown in the output of Program 13.2 and will terminate the program. If we want the program to continue with the execution of the remaining code, then we should try to catch the exception object thrown by the error condition and then display an appropriate message for taking corrective actions. This task is known as exception handling. The purpose of exception handling mechanism is to provide a means to detect and report an “exceptional circumstance” so that appropriate action can be taken. The mechanism suggests incorporation of a separate error handling code that performs the following tasks: 1. Find the problem (Hit the exception). 2. Inform that an error has occurred (Throw the exception)

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

66

3. Receive the error information (Catch the exception) 4. Take corrective actions (Handle the exception) The error handling code basically consists of two segments, one to detect errors and to throw exceptions and the other to catch exceptions and to take appropriate actions. When writing programs, we must always be on the lookout for places in the program where an exception could be generated, Some common exception that we must watch out for catching are listed in Table 13.1. Exception Type

Cause of Exception

Arithmetic Exception

Caused by math errors such as division by zero

ArrayIndexOutofBoundsException

Caused by bad array indexes

ArrayStoreException

Caused when a program tries to store the wrong type of data in an array

FileNotFoundException

Caused by an attempt to access a nonexistent file

Table 13.1 (Continued) Exception Type

Cause of Exception

IOException

Caused by general I/O failures, such as iniability to read from a file

NullPointerException

Caused by referencing a null object

NumberFormatException

Caused when a conversion between strings and number falls

OutOfMemoryException

Caused when there’s not enough memory to allocate a new object

SecurityException

Caused when an applet tries to perform an action not allowed by the browser’s security setting

StackOverflowException

Caused when the system runs out of stack space

StringIndexOutOFBoundsException

Caused when a program attempts to access a nonexistent character position in a string

SYNTAX OF EXCEPTION HANDLING CODE The basic concepts of exception handling are throwing an exception and catching it. This is illustrated in Fig.

try Block

Throws exceptio n object

Statement that causes an exception

Exception object creator

try Block

Statement that OR CALL ON +91-9999554621 FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM causes an exception


INTERNET & JAVA PROGRAMMING

67

Exception handler Exception handling mechanism Java uses a keyword try to preface a block of code that is likely to cause an error condition and “throw” an exception. A catch block defined by the keyword catch “catches” the exception “thrown” by the try block and handles it appropriately. The catch block is added immediately after the try block. The following example illustrates the use of simple try and catch statements. ............ ............ try { statement; //generates an exception } catch (Exception type e) { statement; //processes the exception } .......... .......... The try block can have one or more statements that could generate an exception. If any one statement generates an exception, the remaining statements in the block are skipped and execution jumps to the catch block that is placed next to the try block. The catch block too can have one or more statements that are necessary to process the exception. Remember that every try statement should be followed by at least one catch statement; otherwise compilation error will occur. Note that the catch statement works like a method definition. The catch statement is passed a single parameter, which is reference to the exception object thrown (by the try block). If the catch parameter matches with the type of exception object, then the exception is caught and statements in the catch block will be executed. Otherwise, the exception is not caught and the default exception handler will cause the execution to terminate. Program Using try and catch for exception handling class Error3 { public static void main(String args[ ]) { int a = 10; int b = 5; int c = 5; int x, y ; try { x = a / (b-c); // Exception here } catch (ArithmeticException e) { System.out.println(“Division by zero”); } y = a / (b+c); System.out.println(“y = “ + y); } } Program displays the following output: Division by zero y=1

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

68

Note that the program did not stop at the point of exception condition. It catches the error condition, prints the error message, and then continues the execution, as if nothing has happened. Program :Catching invalid command line arguments class CLineInput { public static void main(String args[ ]) { int invalid = 0; //Number of invalid arguments int number, count = 0; for (int i = 0; i <args.length, i++) { try { number = Integer.parseInt(args[i]); } catch (NumberFormatException e) { invalid = invalid +1; //Caught an invalid number System.out.println(“Invalid Number: “+args[i]) Continue; //Skip the remaining part of the loop } count = count + 1; } System.out.println(“valid Numbers=”+ count); System.out.println(“Invalid Numbers = “+invalid); } } Note the use of the wrapper class Integer to obtain an int number from a string: number = integer.parseInt(args[i]) Remember that the numbers are supplied to the program through the command line and therefore they are stored as strings in the array args [ ]. Since the above statement is placed in the try block, an exception is thrown if the string is improperly formatted and the number is not included in the count. When we run the program with the command line: java CLineInput 15 25.75 40 Java 10.5 65 it produces the following output: Invalid number : 25.75 Invalid number : Java Invalid number : 10.5 Valid numbers = 3 Invalid number = 3 MULTIPLE CATCH STATEMENTS It is possible to have more than one catch statement in the catch block as illustrated below: ............ ............ try { statement; //generates an exception } catch (Exception-Type-1 e) { statement; //processes exception type 1 } catch (Exception-Type-2 3) statement; //processes exception type 2 } .

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING . . catch (Exception-Type-N 3) statement; } ........... ...........

69

//processes exception type N

When an exception in a try block is generated, the Java treats the multiple catch statements like cases in a switch statement. The first statement whose parameter matches with the exception object will be executed, and remaining statements will skipped. Note that Java does not require any processing of the exception at all. We can simply have a catch statement with an empty block to avoid program abortion. Example: catch (Exception e); The catch statement simply ends with a semicolon, which does nothing. This statement will catch an exception and then ignore it. Program Using multiple catch block class Error4 { public static void main(String args[ ]) { int a[ ] = {5,10}; int b = 5; try { int x = a[2] / b – a[1]; } catch(Arithmetic Exception e) { System.out.println(“Division by zero”); } catch(ArrayIndexOutofBoundsException e) { System.out.println(“Array index error”); } int y = a[1] / a[0]; System.out.println(“y = “ + y); } } Program uses a chain of catch blocks and, when run, produces the following output: Array index error y=2 Note that the array element a[2] does not exist because array a is defined to have only two elements, a[0] and a[1]. Therefore, the index 2 is outside the array boundary thus causing the block. Catch(ArrayIndexOutOfBoundsException e) to catch and handle the error. Remaining catch blocks are skipped. USING finally STATEMENT Java supports another statement known as finally statement that can be used to handle an exception that is not caught by any of the previous catch statements. finally block can be used to handle any exception generated within a try block. It may be added immediately after the try block or after the last catch block shown as follows: try

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

70

{ ......... ......... } finally { ......... ......... } try { ......... ......... } catch (....) { ......... ......... } catch (....) { ......... ......... } . finally { ......... ......... } When a finally block is defined, this is guaranteed to execute, regardless of whether or not an exception is thrown. As a result, we can use it to perform certain house-keeping operations such as closing files and releasing system resources. In above program we may include the last two statements inside a finally block as shown below: finally { int y = a[1]/a[0]; System.out.println(“y = “+y)’ } This will produce the same output. THROWING OUR OWN EXCEPTIONS There may be items when we would like to throw our own exceptions. We can do this by using the keyword throw as follows:

throw new Throwable_subclass; Examples: throw new ArithmeticException( ); throw new NumberFormatException( ); Program demonstrates the use of user-defined subclass of Throwable class. Note that Exception is a subclass of Throwable and therefore MyException is a subclass ofThrowable class. An object of a class that extent Throwable can be thrown and caught. Program Throwing out own exception import java.lang.Exception; class MyException(String message) { MyException(String message)

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

71

{ super(message); } } class TestMyException { public static void main(String args[ ]) { int x = 5, y = 1000; try { float z = (float) x / (float) y ; if (x <0.01) { throw new MyException(“Number is too small”); } } catch (MyException e) { System.out.println(“Caught my exception”); System.out.println(e.getMessage( )); } finally { System.out.println(“I am always here”); } } } A run of program produces: Caught my exception Number is too small I am always here The object e which contains the error message “Number is too small” is caught by the catch block which then displays the message using the getMessage( ) method. USING EXCEPTIONS FOR DEBUGGING As we have seen, the exception-handling mechanism can be used to hide errors from rest of the program. it is possible that the programmers may misuse this technique for hiding errors rather than debugging the code. Exception handling mechanism may be effectively used to locate the type and place of errors. Once we identify the errors, we must try to find out why these errors occur before we cover them up with exception handlers.

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

72

UNIT V APPLET PROGRAMMING INTRODUCTION Applets are small Java programs that are primarily used in Internet computing. They can be transported over the Internet from one computer to another and run using the Applet Viewer or any Web browser that supports java. An applet, like any application program, can do many things for us. It can perform arithmetic operations, display graphics, play sounds, accept user input, create animation, and play interactive games. Java was revolutionized the way the Internet users retrieve and use documents on the world wide network. Java has enabled them to create and use fully interactive multimedia Web documents. A web page can now contain not only a simple text or a static image but also a Java applet which, when run, can produce graphics, sounds and moving images. Java applets therefore have begun to make a significant impact on the World Wide Web. APPLET LIFE CYCLE Every Java applet inherits a set of default behaviors from the Applet class. As a result, when an applet is loaded, it undergoes a series of changes in its state as shown in Fig. The applet states include:  Born or initialization state  Running state  Idle state  Dead or destroyed state

Begin (Load Applet)

Born

start( )

Display

Initializatio n

stop( )

Running

start( )

Idle

paint( )

Stopped

destroy ( ) Dead

End

Destroyed Initialization State Applet enters the initialization state when it is first loaded. This is achieved by calling the init ( ) method of Applet Class. The applet is born. At this stage, we do the following, if required. Exitmay of Browser  Create objects needed by the applet  Set up initial values  Load images of fonts  Set up colors The initialization occurs only once in the applet’s life cycle. To provide any of the behaviours mentioned above, we must override the init( ) method: public void init ( ) { ......... ......... (Action) ......... } Running State FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

73

Applet enters the running state when the system calls the start( ) method of Applet Class. This occurs automatically after the applet is initialized. Starting can also occur if the applet is already in “stopped” (idly) state. For example, we may leave the Web page containing the applet temporarily to another page and return back to the page. This again starts the applet running Note that, unlike int( ) method, the start ( ) method may be called more than once. We may override the start( ) method to create a thread to control the applet. public void start( ) { ......... ......... (Action) ......... } Idle or Stopped State An applet becomes idle when it is stopped from running. Stopping occurs automatically when we leave the page containing the currently running applet. We can also do so by calling the stop( ) method explicitly. If we use a thread to run the applet, then we must use stop ( ) method to terminate the thread. We can achieve this by overriding the stop( ) method. public void stop( ) { ............ ............ (Action) ............ } Dead State An applet is said to be dead when it is removed from memory. This occurs automatically by invoking the destroy ( ) method when we quit the browser. Like initialization, destroying stage occurs only once in the applet’s life cycle. If the applet has created any resources, like threads, we may override the destroy ( ) method to clean up these resources. public void destroy ( ) { ........... ........... (Action) ........... } Display State Applet moves to the display state whenever it has to perform some output operations on the screen. This happens immediately after the applet enters into the running state. The paint ( ) method is called to accomplish this task. Almost every applet will have a paint ( ) method. Like other methods in the life cycle, the default version of paint ( ) method does absolutely nothing. We must therefore override this method if we want anything to be displayed on the screen. public void paint (graphics g) { ......... ......... (Display statements) ......... } It is to be noted that the display state is not considered as a part of the applet’s life cycle. In fact, the paint( ) method is not defined in the Applet class. It is inherited from the Component class, a super class of Applet. CREATING AN EXECUTABLE APPLET Executable applet is nothing but the .class file of the applet, which is obtained by compiling the source code of the applet. Compiling an applet is exactly the same as compiling an application. Therefore, we can use the Java compiler the applet. Let us consider the HelloJava applet created in Section 14.4. This applet has been stored in a file called HelloJava.java. Here are the steps required for compiling the Hellojava applet. 1. Move to the directory containing the source code and type the following command: javac HelloJava.java 2. The compiled output file called HelloJava.class is placed in the same directory as the source.

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

74

3. If any error message is received, then we must check for errors, correct them and compile the applet again. APPLET TAG Note that we have included a pair of <APPLET....> and </APPLET> tags in the body section discussed above. The <APPLET ...> tag supplies the name of the applet to be loaded and tells the browser how much space the applet requires. The ellipsis in the tag <APPLET ...> indicates that it contains certain attributes that must specified. The <APPLET> tag given below specifies the minimum requirements to place the JellowJava applet on a Web page: <APPLET CODE = helloJava.class WIDTH = 400 HEIGHT = 200> </APPLET > This HTML code tells the browser to load the compiled Java applet HelloJava.class, which is in the same directory as this HTML file. And also specifies the display area for the applet output as 400 pixels width and 200 pixels height. We can make this display area appear in the centre of the screen by using the CENTRE tags as shown below: <CENTER> <APPLET ......... ......... ......... </APPLET> </CENTER> Note that <APPLET> tag discussed above specifies three things: 1. Name of the applet 2. Width of the applet (in pixels) 3. Height of the applet (in pixels) ADDING APPLET TO HTML FILE Now we can put together the various components of the Web page and create a file known as HTML file. Insert the <APPLET> tag in the page at the place where the output of the applet must appear. Following is the content of the HTML file that is embedded with the <APPLET> tag of our HelloJava applet. <HTML> <! This page include a welcome title in the title bar and also displays a welcome message. Then it specifies the applet to be loaded and executed. > <HEAD> <TITLE> Welcome to Java Applets <TITLE> </HEAD> <BODY> <CENTER> <H1> welcome to the world of Applets</H1> </CENTER> <BR> <CENTER> <APPLET> CODE = HelloJava.class WIDTH = 400 HEIGHT = 200> </APPLET> </CENTER> </BODY> </HTML>

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

75

RUNNING THE APPLET Now that we have created applet files as well as the HTML file containing the applet, we must have the following files in our current directory: HelloJava.java HelloJava.class HelloJava.html To run an applet, we require one of the following tools: 1. Java-enabled Web browser (such as HotJava or Netscape) 2. Java appletviewer If we use a Java-enabled Web browser, we will be able to see the entire Web page containing the applet. If we use the appletviewer tool, we will only see the applet output. Remember that the appletviewer is not a full-fledged Web browser and therefore it ignores all of the HTML tags except the part pertaining to the running of the applet The appletviewer is available as a part of the Java Development Kit that we have been using so far. We can use it to run our applet as follows: appletviewer HelloJava.html Notice that the argument of the appletviewer is not the java file or the .class file, but rather .html file. The output of our applet will be as shown in Fig.

Applet Viewer : HelloJava.class

Applet

Hello Java

apletloader.started

DISPLAYING NUMERICAL VALUES In applets, we can display numerical values by first converting them into strings and then using the drawString( ) method of Graphics class. We can do this easily by calling the ValueOf( ) method of String class. Program 14.5 illustrates how an applet handles numerical values. Program Displaying numerical values import java.awt.*; import java.applet.*; public class Numvalues extends Applet { public void paint(Graphics g) { int value1 = 10; int value2 = 20; int sum = value1 + value2: string s = “sum: “+ string.valueOf(sum); g.drawString(s, 100, 100); } }

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

76

GETTING INPUT FROM THE USER Applets work in a graphical environment. Therefore, applets treat inputs as text strings. We must first create an area of the screen in which user can type and edit input items (which may be any data type). We can do this by using the TextField class of the applet package. Once text fields are created for receiving input, we can type the values in the fields and edit them, if necessary. Next steps is to retrieve the items from the fields for display of calculations, if any. Remember, the text fields contain items in string form. They need to be converted to the right form, before they are used in any computations. The results are then converted back to strings for display. GRAPHICS PROGRAMMING THE GRAPHICS CLASS Java’s Graphics class includes methods for drawing many different types of shapes, from simple lines to polygons to text in a variety of fonts. We have already seen how to display text using the paint( ) method and a Graphics object. To draw a shape on the screen, we may call one of the methods available in the Graphics class. Table shows the most commonly used drawing methods in the Graphics class. All the drawing methods have arguments representing end points, corners, or starting locations of a shape as values in the applet’s coordinate system. To draw a shape, we only need to use the appropriate method with the required arguments. Table Drawing Methods of the Graphics Class Method Description clearrect( ) Erases a rectangular area of the canvas. copyArea( ) Copies a rectangular area of the canvas to another area. drawArc( ) Draws a hollow arc. drawLine( ) Draws a straight line. drawOval( ) Draws a hollow oval. drawPolygon( ) Draws a hollow polygon. drawRect( ) Draws a hollow rectangle. drawRoundRect( ) Draws a hollow rectangle with rounded corners. drawString( ) Displays a text string. fillArc( ) Draws a filled arc. fillOval( ) Draws a filled oval. fillpolygon( ) Draws a filled polygon. fillRect( ) Draws a filled rectangle. fillRoundRect( ) Draws a filled rectangle with rounded corners. getColor( ) Retrieves the current drawing colour. getFont( ) Retrieves the currently used font. getFontMetrics( ) Retrieves information about the current font. setColor( ) Sets the drawing colour. setFong( ) Sets the font. LINES AND RECTANGLES The simplest shape we can draw with the Graphics class is a line. The drawLine( ) method takes two pair of coordinates, (x1, y1) and (x2, y2) as arguments and draws a line between them. For example, the following statement draws a straight line from the coordinate point (10,10) to (50,50): g.drawLine(10,10, 50,50); The g is the Graphics object passed to paing( ) method. Similarly, we can draw a rectangle using the drawRect( ) method. This method takes four arguments. The first two represent the x and y coordinates of the top left corner of the rectangle, and the remaining two represent the width and the height of the rectangle. For example, the statement g.drawrect(10, 60,

40, 30);

(x, y)

width

height

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

77

Rectangle will draw a rectangle starting at (10,60) having a width of 40 pixels and a height of 30 pixels, Remember that the drawRect( ) method draws only the outline of a box. We can draw a solid box by using the method fillRect( ). This also takes four parameters (as drawRect) corresponding to the starting point, the width and the height of the rectangle. For example, the statement g.fillRect(60, 10, 30, 80); will draw a solid rectangle starting at (60,10) with a width of 30 pixels and a height of 80 pixels. We can also draw rounded rectangles (which are rectangles with rounded edges), using the methods drawRoundRect( ) and fillRoundRect( ). These two methods are similar to drawRect( ) and fillRect( ) except that they take two extra arguments representing the width and height of the angle of corners. These extra parameters indicate how much of corners will be rounded. Example: g.drawRoundRect(10,100,80,50,10,10); f.fillRoundRect(20,110,60,30,5,5) Program is an applet code that draws three lines, a rectangle, a filled rectangle, a rounded rectangle and filled rounded rectangle. Note that the filled rounded one is drawn inside the rounded rectangle. CIRCLES AND ELLIPSES The Graphics class does not have any method for circles or ellipses. However, the drawOval( ) method can be used to draw a circle or an ellipse. Ovals are just like rectangles with overly rounded corners as shown in Fig.15.3. Note that the figure is surrounded by a rectangle that just touches the edges. The drawOval( ) method takes four arguments: the first two represent the top left corner of the imaginary rectangle and the other two represent the width the height of the oval itself. Note that if the width and height are the same, the oval becomes a circle. The oval’s coordinates are actually the coordinates of an enclosing rectangle. Like rectangle methods, the drawoval( ) method draws outline of an oval, and the fillOval( ) method draws a solid oval. The code segment shown below draws a filled circle within an oval

height

public void paint (Graphics g) { g.drawOval(20,20,200,120); g.setColor(Color.green); g.fillOval(70,30,100,100);

width

//This is a circle

We can draw an object using a color object as follows: g.setColor(Color.green); After setting the color, all drawing operations will occur in that color. DRAWING ARCS An arc is a part of an oval. In fact, we can think of an oval as a series of arcs that are connected together in an orderly manner. The drawArc( ) designed to draw arcs six arguments. The first four are the same as the arguments for drawOval( ) method and the last two represent the starting angle of the arc and the number of degrees (sweep angle) around the arc. In drawing arcs, Java actually formulates the arc as an oval and then draws only a part of it as dictated by the last two arguments. Java considers the three O’clock position as zero degree position and degrees increase in anti-clockwise direction as shown in Fig.15.5. So, to draw an arc from 12.00

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

78

O’ clock position to 6:00 O’clock position, the starting angle would be 90, and the sweep angle would be 180.

90

180

0

180

270

We can also draw an arc in backward direction by specifying the sweep angle as negative. For example, if the last argument is -135 and the starting angle is 45, then the arc is drawn as shown in Fig.15.6.

45

135

We can use the fillArc( ) method to fill the arc. 270Filled arcs are drawn as if they were sections of a pie. Instead of joining the two end points, they are joined to the centre of the oval. DRAWING POLYGONS Polygons are shapes with many sides. A polygon may be considered a set of lines connected together. The end of the first line is the beginning of the second line, the end of the second is the beginning of the third, and so on. This suggests that we can draw a polygon with n sides using the drawLine( ) method n times in succession. For example, the code given below will draw a polygon of three sides. The output of this code is shown in Fig. 15.8. public void paint(Graphics g) { g.drawLine(10, 20, 170, 40); g.drawLine(170, 40, 80, 140); g.drawLine(80, 140, 10, 20); } Note that the end point of the third line is the same as the starting point of the polygon.

(10, 20) (170, 40) FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621

(80,


INTERNET & JAVA PROGRAMMING

79

We can draw polygons more conveniently using the drawPolygon( ) method of Graphics class. This method takes three arguments:  An array of integers containing x coordinates  An array of integers containing y coordinates  An integer for the total number of points It is obvious that x and y arrays should be of the same size and we must repeat the first point at the end of the array for closing the polygon. The polygon shown in Fig. can be drawn using the drawPolygon( ) method as follows: public void paint(Graphics g) { int xPoints[ ] = {10,170,80,10}; int yPoints[ ] = {20,40,140,20}; int nPoints[ ] = xPoints.length; g.drawPolygon (xPoints, yPoints, nPoints); } Example For Applet and Graphics Programming. Example 1 Generating a Face Applet Drawings import java.awt.*; import java.applet.*; /*<APPLET CODE="face.class" WidTH=200 HEIGHT=200></APPLET>*/ public class face extends Applet { public void paint(Graphics g) { g.setColor(Color.green); g.drawOval(40,40,120,150); g.drawOval(57,75,30,20); g.drawOval(110,75,30,20); g.fillOval(68,81,10,10); g.fillOval(121,81,10,10); g.drawOval(85,100,30,30); g.fillArc(60,125,80,40,180,180); g.drawOval(25,92,15,30); g.drawOval(160,92,15,30); } } OUTPUT

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

7.2 ARITHMETIC MANIPULATION USING AWT CONTROLS import java.awt.*; import java.applet.*; import java.io.*; import java.awt.event.*; /*<applet code = arith.class height=400 width=700> </applet>*/ public class arith extends Applet implements ActionListener { String s,s1,s2,s3; TextField t1,t2,t3; Label l,l1,l2,l3; Button b1,b2,b3,b4,b5; public void init() { setLayout(null); l =new Label(" ARITHMETIC CALCULATION"); l1 =new Label(" ENTER THE FIRST NUMBER"); l2 =new Label(" ENTER THE SECOND NUMBER"); l3 =new Label(" RESULT"); t1 = new TextField(8); t2 = new TextField(8); t3 = new TextField(8); b1 = new Button("ADDITION"); b2 = new Button("SUBTRACTION"); b3 = new Button("MULTIPLICATION"); b4 = new Button("DIVISION"); b5 = new Button("CLEAR"); l.setBounds(200,10,300,40); l1.setBounds(50,50,160,40); l2.setBounds(50,100,190,40); l3.setBounds(50,150,140,40);

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621

80


INTERNET & JAVA PROGRAMMING t1.setBounds(250,50,100,30); t2.setBounds(250,100,100,30); t3.setBounds(250,150,100,30); b1.setBounds(50,250,100,30); b2.setBounds(200,250,100,30); b3.setBounds(350,250,100,30); b4.setBounds(500,250,100,30); b5.setBounds(650,250,100,30); add(l); add(l1); add(l2); add(l3); add(t1); add(t2); add(t3); add(b1); add(b2); add(b3); add(b4); add(b5); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); b5.addActionListener(this); } public void actionPerformed(ActionEvent e) { s = e.getActionCommand(); s1=t1.getText(); s2=t2.getText(); Double b = new Double(s1); Double m = new Double(s2); if(s.equals("ADDITION")) s3= Double.toString(b.doubleValue()+m.doubleValue()); if(s.equals("SUBTRACTION")) s3= Double.toString(b.doubleValue()-m.doubleValue()); if(s.equals("MULTIPLICATION")) s3= Double.toString(b.doubleValue()*m.doubleValue()); if(s.equals("DIVISION")) s3= Double.toString(b.doubleValue()/m.doubleValue()); t3.setText(s3); if(s.equals("CLEAR")) { t1.setText(" "); t2.setText(" "); t3.setText(" "); } }} OUTPUT

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621

81


INTERNET & JAVA PROGRAMMING

82

Managing Input and Output Files File Operations Files are the primary source and destination for data within most programs. Fo;e I/O operation is common in any language. Java devotes a whole range of methods found in a class called file in the java.io package to perform these operations. A File is the only object in the I/O (Input/Output) package that references an actual disk file. The file name should follow the conventions of the platform on which it is loaded. The file class only describes the properties of a file object. It dies bit specify how it retrieves data from stored files. Java Applets do not provide much scope for the I/O operations. However I/O operations can be made use of in the Java applications. Java treats files and directories as objects of the File class. A directory is also treated as a file object with an additional property – a list of file names that can be displayed using the list ( ) method. Path separator, path separator character, file separator, file separator character, etc. depend on the platform on which we are working. For example, if a Windows based platform is being used, the path separator should be “/”. Here if “/”, is used, it has to be escaped by mentioning within a string. Constructors Objects of the file class can be created using three types of file constructors. The first type accepts the name of the file as a string as shown below: File f1 = new file (“c:/java/temp”); In the above type of constructor, it is assumed that a window based platform is being used. The file name id temp and that it is under c:\java directory. The next type of initializing a file is: File f2 = new file (“c:/java”, “temp”); In the above type, the first parameter specifies the directory path and the second denotes the name of the file to be located under that directory. The last type of constructor also takes two string parameters as shown below: File f3 = new file (“java”, “temp”); In the above type, the first parameter is a directory name under which the file name contained in the second parameter is to be created. Methods of the File Class Some of the methods available with the file class, which help in understanding the properties of a file, are discussed below. getName( ) Method As the name suggests, this method is used to obtain the name of the file specified. getPath( ) / getAbsoluterPath Method These methods facilitate us to obtain the path of the file specified and the absolute path of the file specified, respectively.

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

83

getParent( ) Method The getParent( ) method returns a String object that contains the parent directory. Exists( ) Method The exists( ) method is used to check if the named file exists in the specified directory or not. isFile ( ) / isDirectory( ) Method These are used to check if the named file is an ordinary file or a directory, respectively. Example helps in understanding the usage of the methods discussed above.  Open a new file in the editor and enter the following code: 1. import java.io.*; 2. class FileMethids1 { 3. public static void main (String args [ ]) { 4. File f1 = new File (“c:\ \ jaa”, “abc.txt”); 5. system.out.println (“Fill name : “ + f1.gerName( )); 6. system.out.println (“path : “ + f1.getpath ( )); 7. system.out.println (“Absilute path: “ + f1.getAbsolutepath ( )); 8. system.out,println (f1.exists( ) ? “file exists”: “file does not exist”); 9. system.out.println (f1.isDirectory( ) ? “file is a directory” : “file is not a directory”); 10. system.out.println (f1.isFile ( )? “file exists”: “file is an ordinary file”); 11. } 12. }  Save the file as FileMethods1.java  Compile the file using javac FileMethods1.java  Create a file named abc.txt in the c:\java directory  Run the file using java FileMethods1 The output of the program is shown below: File name : abc. Txt Path : c:\java\abc.txt Absolute path : c:\java\abc.txt File exists File is not a directory File is an ordinary file The above example provides a list of details about the file named c:\java\abc.txt provided it exists in that directory. canRead( ) / canWrite( ) Methods These methods are used to check if we can read from the specified file or write into the specified file respectively. These methods return a Boolean value depending on their readability/ writability. lastModified( ) Method This method returns the last modification time of the file. Example illustrates the usage of the canRead (), canWrite () methods. Example  Open a new file in the editor and type the following code: import hava.io.*; class checkperm { pulic static void main (String args []) { File f1 = new File (“c:\ \ java”, “abc.txt”); If (f1.canRead ( )) System.out.println (“we can read from this file”); Else System.out.print;n(“we can write to this file”); If (f1.canWrite( )) System.out.printin (“We cannot write to this file”); Else System.out.prontln (“We cannot write to this file”); System.out.println (“The file was last modified at “+ f1.lastModified at” + seconds after Januay 1 1970”); } } If the file has both read and writes permissions then the output appears as follows:

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

84

length( ) Method This method is used to know the file size in bytes. Delete( ) Method This method is useful to delete the specified file. rename( ) Method This method is used to rename a specified file. IT takes a file object that becomes the destination file or the renamed file, as its parameter. Example illustrates usage of the above three methods, by accepting file names as command line parameters. Example  Open a new file in the editor and enter the following code: 1. import java.io.*; 2. class FileMethods2 { 3. public static void main (String args []) { 4. for (int i=0; i<args.length;i++) 5. File f = new File (“c:\ \ java”, args [i]); 6. File f1 = new File (“c:\ \ java\ \ renamefile”); 7. if (f.exists ( )) { 8. system.out.println (f + “exists”); 9. system.out.println (“Its size is “ + f.length( ) + “ bytes”); 10. f.renameTo (f1); 11. system.out.println (“Renamed file name : “ + f1); 12. system.out.println (“deleting the file “ + f); 13. system.out.println (“= = = = = = = = = = = = = = = = =”); 14. f.delete ( ); 15. } 16. else 17. system.out.println(f + “ does not exist”); 18. } 19. } 20. }

List( ) Method This list( ) method is used to list the contents of the specified directory. The list (FilenameFilter) is used to filter files that match specified patterns and list them from a directory. mkdir( ) Method This methods is used to create a directory and returns a Boolean indicating the success of the creation. The following example depicts the usage of this method. Example  Open a new file in the editor and enter the following code:

Input / Outp 1.ut import java.io.*;

2. class FileMethods4 { 3. public static void main (String args [] ) throws IoException { 4. File f = new File (“c:/java/temp”); 5. if (f.mkdir( )) 6. system.out.println (“created a directory”); 7. else 8. system.out.println (“unable to create a directory”); 9. } 10. }

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

85

Methods in Streams A stream is a path of communication between the source of information and the destination.Streams can be dealt with under three headings – Input Streams, Output Streams and Readers / Writers. All of them are abstract classes. All the methods of these classes throw an IOExeption on error conditions. Discussed below are some methods that are available with Input Streams, Output Streams and Readers/Writers. Methods of InputStream /Reader Methods available with the InputStream/Reader class are read ( ), skip ( ), available ( ), close ( ), mark ( ), and reset( ). The read( ) Method This method waits for the user input and then reads bytes from the input source. There are various forms of the read ( ) method. The read ( ) method without any parameters returns an integer representation of the next available byte of input. The read (byte b[j) method reads the input as bytes into the array b and returns the actual number of bytes successfully read. The read (char buf [], int off, len) reads up to len bytes into the array b, starting at b[off], returning the number of bytes successfully read. The read (char cbuf[], int len) reads from cbuf array of characters from the offset mentioned by off and upto the length mentioned by len. Example illustrates the usage of the read ( ) method. Example  Open a new file in the editor and enter the following code: import java.io.*; class ReadEg { Public static void min (String args []) throws IOExceprion { int i; byte[] c=new byte [10]; System.out.println (“Enter a string of 10 characters”); For (i=0; <10; i++) c[i] = ((byte)System.in.read ( )); System.out.print (“The string entered is: “); for (i=o; i<10;i++) System.out.print ((char) c[i]); } } The skip( ) Method This method skips over n bytes of input and returns the number of bytes skipped.

The available( ) Method This method returns the number of bytes of input currently available for reading. The close( ) Method This method closes the input source. Further attempts to read will result in IOException. The mark( ) Method This method places a mark at the current point in the input stream that remains until a certain number of bytes are read. The reset( ) Method This method returns the input pointer to the previously set mark. Methods of OutputStream / Writer All methods of this class return a void and in case of errors throw an IOException. Some of the methods of this class are writer ( ), flush ( ) and close ( ). The Write( ) Method The write (int b) method helps to write a single byte to an output stream. The write (byte b[j)) assists in writing a complete array of bytes to an output stream. The write (byte b[], int off, int len) assists in writing len bytes from the array b, beginning at b[off].

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


INTERNET & JAVA PROGRAMMING

86

Example uses both the write ( ) and read ( ) methods to read a string from the standard input (monitor) and print it back to the same. Example  Open a new file in the editor and enter the following code: import java.io.*; class WriteEg { public static void main (String args [] ) throws IOException { int i; byte [] c=new byte [10]; System.out.println (“Enter a string of 10 characters”); for (i=0;i<10;i++) { c[i] = (byte) system.in.read ( ); } System.out.println (“The following is the string you have entered :”); System.out.write ( c ); } }

The flush( ) Method This method finalizes the output state to clear any buffers. The close( ) Method This method closes the output stream. Further attempts to write will generate an IOException. Using these file stream and its associated methods a text editor can be easily created.

------------------------------------------------THE END-----------------------------------------

FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CALL ON +91-9999554621


I NTERNET& JAVA

PROGRAMMI NG

Publ i s he dby

I ns t i t ut eofManage me nt& Te c hni c alSt udi e s Addr e s s:E4 1 , Se c t o r 3 , No i da( U. P) www. i mt s i ns t i t ut e . c o m| Co nt a c t :9 1 +9 2 1 0 9 8 9 8 9 8


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.