Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
BT 0074 OOPS with Java Contents Unit 1 Introduction to Java 1 Unit 2 Java Basics 11 Unit 3 Operators and Control Statements 25 Unit 4 Arrays and Strings 48 Unit 5 Inheritance, Package and Interface 81 Unit 6 Exception Handling 109 Unit 7 Streams in Java 119 Unit 8 Applets 131 Unit 9 Event Handling 147 Unit 10 Java Data Base Connectivity 167 Edition: Spring 2009 th BKID – B1002 11 June 2009 Unit 11 RMI, CORBA and Java Beans 178 Unit 12 Java Server Pages and Servlets 191 Unit 13 Networking in Java 202 Unit 14 Java Development Kit 212 Unit 15 Security in Java 226 Acknowledgements, References and Suggested Readings 233 Prof. S. Kannan Director & Dean (In-charge) Directorate of Distance Education Sikkim Manipal University of Health, Medical & Technological Sciences (SMU DDE) Board of Studies Dr. U. B. Pavanaja (Chairman) General Manager – Academics Manipal Universal Learning Pvt. Ltd. Bangalore Prof. Bhushan Patwardhan Chief Academics Manipal Education Bangalore Dr. Harishchandra Hebbar Director Manipal Centre for Info. Sciences, Bangalore Dr. N. V. Subba Reddy HOD-CSE Manipal Institute of Technology, Manipal Dr. Ashok Hegde Vice President MindTree Consulting Ltd., Bangalore Dr. Ramprasad Varadachar Director, Computer Studies Dayanand Sagar College of Engg., Bangalore Nirmal Kumar Nigam HOP – IT Sikkim Manipal University – DDE Manipal Dr. A. Kumaran Research Manager (Multilingual) Microsoft Research Labs India Bangalore Ravindranath P. S. Director (Quality) Yahoo India, Bangalore Dr. Ashok Kallarakkal Vice President IBM India, Bangalore H. Hiriyannaiah Group Manager EDS Mphasis, Bangalore Content Preparation Team Content Writing Mr. Balasubramani R Assistant Professor, Dept. of IT Sikkim Manipal University – DDE Manipal. Instructional Design Mr. Kulwinder Pal Senior Lecturer (Education) Sikkim Manipal University – DDE, Manipal Content Editing Dr. E. R. Naganathan Professor & HOD – IT Sikkim Manipal University – DDE Manipal. Language Editing Ms. Vasantha Raviprakash Lecturer - English M.G.M. College, Udupi Edition: Spring 2009 This book is a distance education module comprising a collection of learning material for our students. All rights reserved. No part of this work may be reproduced in any form by any means without permission in writing from Sikkim Manipal University of Health, Medical and Technological Sciences, Gangtok, Sikkim. Printed and published on behalf of Sikkim Manipal University of Health, Medical and Technological Sciences, Gangtok, Sikkim by Mr.Rajkumar Mascreen, GM, Manipal Universal Learning Pvt. Ltd., Manipal – 576 104. Printed at Manipal Press Limited, Manipal. SUBJECT INTRODUCTION OOPS (Object Oriented Programming Systems) with Java is a four credit subject in BScIT Program. This subject focuses primarily on developing applications in Java using object oriented programming features. Java is a programming language similar to that of C++. Java is well suited for designing software that works in conjunction with the Internet. It is a cross platform language, which means its programs can be designed to run the same way on any operating systems like MS-Windows, Apple Macintosh, UNIX etc. This SLM on “OOPS with Java” is divided into fifteen units, the brief account of them is given below: Unit 1: Introduction to Java This unit gives an overview of various features of Java. You will also learn about Java Byte Code, which is platform independent. Unit 2: Java Basics In this unit, you will learn about various Java keywords. Emphasis is given on various data types in Java and variable declaration. Brief introduction is also given for using classes and declaring methods in Java. You will also learn to write, compile, and run a simple Java program. Unit 3: Operators and Control Statements In this Unit, you will learn about various operators and control flow statements in Java. This unit forms the basis for learning programming in Java. Unit 4: Arrays and Strings This unit explains arrays and strings in Java with emphasis on string constructors, special string operations, character extraction, comparison etc. Special attention is also given to StringBuffer class. string Unit 5: Inheritance, Package and Interface In this Unit, you will learn about the advantages of Inheritance and various types of Inheritance. Also you will learn how to group classes into a package. Brief introduction to interface and abstract classes are also given in this unit. Unit 6: Exception Handling When your program encounters an error, it should not stop working abruptly. This is taken care of by a mechanism called Exception Handling in Java. You will learn how to implement exception handling in Java. Unit 7: Streams in Java In this unit, you will learn about abstract streams and stream classes. Introduction to Random Access Files and Serialization is also discussed in this unit. Unit 8: Applets The power of Java lies in developing Web applications. These Java programs are called applets. This unit gives an overview of life cycle of an applet and various applet methods. Unit 9: Event Handling Event handling is essential to GUI programming. In this unit, you will learn various Event Classes and Adapter Classes. Unit 10: Java Data Base Connectivity (JDBC) This unit explains Database Management concepts in Java through a mechanism called Java Data Base Connectivity (JDBC). You will learn how to connect Java programs to popular back end databases. Unit 11: RMI, CORBA and Java Beans This unit explains various advanced topics in Java such as Remote Method Invocation (RMI), Common Object Request Broker Architecture (CORBA) and Java Beans. Unit 12: Java Server Pages and Servlets Java Server Pages and Servlets are used to write server side programs in Java. This unit discusses various features of JSP and servlets. Unit 13: Networking in Java Networking allows the application to connect to existing network services, provides its own services, and even allow for multiuser, network-aware games over the Internet. This unit explains various Networking features available in Java through java.net package. Unit 14: Java Development Kit This unit explains various tools available in Java Development Kit (JDK) along with various advanced debugging commands. Unit 15: Security in Java In this unit, you will learn how to use Digital Signatures to identify applets. Also you will learn about various JDK security tools and certificates. Objective of studying the subject After studying this subject, you should be able to develop industry standard applications and applets in Java, using its primitive and advanced features. The subject requires knowledge and understanding of skills related to object oriented programming and classes. For various multimedia and other resources on the subject, log on to TeL portal of SMU DDE at www.smude.edu.in. OOPS with Java Unit 1 Unit 1 Introduction to Java Structure 1.1 Introduction Objectives 1.2 History of Java 1.3 Features of Java 1.4 Java Magic: Byte Code 1.5 Summary 1.6 Terminal Questions 1.7 Answers 1.1 Introduction Java is a simple language that can be learned easily, even if you have just started programming. A Java programmer need not know the internal of Java. The syntax of Java is similar to C++. Unlike C++, in which the programmer handles memory manipulation, Java handles the required memory manipulations, and thus prevents errors that arise due to improper memory usage. This unit orients you towards understanding of basic Java features. To further enrich your knowledge about the history and basic features of Java read “Java 2 – Complete Reference”. Objectives After studying this unit, you should be able to: describe the history of Java explain the features of Java explain the Java Magic – Byte Code 1.2 History of Java Although the Java programming language is usually associated with the World Wide Web, its origin predates the web. Java began life as the programming language Oak. Oak was developed by the members of the Green Project, which included Patrick Naughton, Mike Sheridan and James Gosling, a group formed in 1991 to create products for the smart electronics market. The team decided Sikkim Manipal University - DDE Page No. 1 OOPS with Java Unit 1 that the existing programming languages were not well suited for use in consumer electronics. The chief programmer of Sun Microsystems, James Gosling, was given the task of creating the software for controlling consumer electronic devices. The team wanted a fundamentally new way of computing, based on the power of networks, and wanted the same software to run on different kinds of computer, consumer gadgets and other devices. Patenting issues gave a new name to Oak – Java. During that period, Mosaic, the first graphical browser, was released. Nonprogrammers started accessing the World Wide Web and the Web grew dramatically. People with different types of machines and operating systems started accessing the applications available on the web. Members of the Oak team realized that Java would provide the required cross-platform independence that is, independence from the hardware, the network, and the operating system. Very soon, Java became an integral part of the web. Java works just everywhere, from the smallest devices to supercomputer. Java technology components (programs) do not depend on the kind of computer, telephone, television, or operating system they run on. They work on any kind of compatible device that supports the Java platform. Self Assessment Questions: 1. The earlier name of Java was _____. 2. The members of Green Project were _____, _____ and _____. 3. _____ is the first graphical browser. 1.3 Features of Java Java defines data as objects with methods that support the objects. Java is purely object-oriented and provides abstraction, encapsulation, inheritance and polymorphism. Even the most basic program has a class. Any code that you write in Java is inside a class. Java is tuned for Web. Java programs can access data across the Web as easily as they access data from a local system. You can build distributed applications in Java that use resources from any other networked computer. Java is both interpreted and compiled. The code is complied to a bytecode that is binary and platform independent. When the program has to be Sikkim Manipal University - DDE Page No. 2 OOPS with Java Unit 1 executed, the code is fetched into the memory and interpreted on the user’s machine. As an interpreted language, Java has simple syntax. When you compile a piece of code, all errors are listed together. You can execute only when all the errors are rectified. An interpreter, on the other hand, verifies the code and executes it line by line. Only when the execution reaches the statement with error, the error is reported. This makes it easy for a programmer to debug the code. The drawback is that this takes more time than compilation. Compilation is the process of converting the code that you type, into a language that the computer understands - machine language. When you compile a program using a compiler, the compiler checks for syntactic errors in code and list all the errors on the screen. You have to rectify the errors and recompile the program to get the machine language code. The Java compiler compiles the code to a bytecode that is understood by the Java environment. Bytecode is the result of compiling a Java program. You can execute this code on any platform. In other words, due to the bytecode compilation process and interpretation by a browser, Java programs can be executed on a variety of hardware and operating systems. The only requirement is that the system should have a Java-enabled Internet browser. The Java interpreter can execute Java code directly on any machine on which a Java interpreter has been installed. Thanks to bytecode, a Java program can run on any machine that has a Java interpreter. The bytecode supports connection to multiple databases. Java code is portable. Therefore, others can use the programs that you write in Java, even if they have different machines with different operating systems. Java forces you to handle unexpected errors. This ensures that Java programs are robust (reliable), bug free and do not crash. Due to strong type-checking done by Java on the user’s machine, any changes to the program are tagged as error and the program will not execute. Java is, therefore, secure. Java is faster than other interpreter-based language like BASIC since it is compiled and interpreted. Sikkim Manipal University - DDE Page No. 3 OOPS with Java Unit 1 Multithreading is the ability of an application to perform multiple tasks at the same time. You can create multithreading programs using Java. The core of Java is also multithreaded. The following definition of Java by Sun Microsystems lists all the features of Java. ‘Java is a simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded and dynamic language.’ Self Assessment Questions: 4. _____ is the process of converting typed code to machine code. 5. Java code is _____, so that it can easily run on any systems. 6. Java is _____ than other interpreted language. 1.4 Java Magic: Byte Code The key factor that allows Java to solve both the security and the portability problems just described is that the output of a Java compiler is not executable code. Rather, it is bytecode. Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM). That is, in its standard form, the JVM is an interpreter for bytecode. This may come as a bit of surprise. As you know, C++ is compiled to executable code. In fact, most modern languages are designed to be compiled, not interpreted, mostly because of performance concerns. However, the fact that a Java program is executed by the JVM helps to solve the major problems associated with downloading programs over the Internet. Here is why. Translating a Java program into bytecode helps it to run much easier in a wide variety of environments. The reason is straightforward: only the JVM needs to be implemented for each platform. Once the run-time package exists for a given system, any Java program can run on it. Remember, although the details of the JVM will differ from platform to platform, all interpret the same Java bytecode. If a Java program was compiled to native code, then different versions of the same program should exist for each type of CPU connected to the Internet. This is, of course, not a feasible solution. Sikkim Manipal University - DDE Page No. 4 OOPS with Java Unit 1 Thus, the interpretation of bytecode is the easiest way to create truly portable programs. The fact that a Java program is interpreted also helps to make it secure. Because the execution of every Java program is under the control of the JVM, the JVM can contain the program and prevent it from generating side effects outside the system. As you will see, safety is also enhanced by certain restrictions that exist in the Java language. When a program is interpreted, it generally runs substantially slower than it would run if compiled to executable code. However, with Java, the difference between the two is not so great. The use of bytecode enables the Java run-time system to execute programs much faster than you might expect. The Internet helped catapult Java to the forefront of programming, and Java, in turn, has had a profound effect on the Internet. The reason for this is quite simple. Java expands the universe of objects that can move about freely in cyberspace. In a network, two very broad categories of objects are transmitted between the server and your personal computer: passive information and dynamic, active programs. For example, when you read your e-mail, you are viewing passive data. Even when you download a program, the program's code is only a passive data until you execute it. However, a second type of object can be transmitted to your computer: a dynamic, self-executing program. Such a program is an active agent on the client computer, yet it is initiated by the server. For example, a program might be provided by the server to display properly the data that the server is sending. Though desirable and dynamic, the network programs present serious problems in the areas of security and portability. Prior to Java, cyberspace was effectively closed to half the entities that now live there. As you will see, Java addresses those concerns and, by doing so, has opened the door to an exciting new form of program: the applet. The Java Buzzwords No discussion of the genesis of Java is complete without a look at the Java buzzwords. Although the fundamental forces that necessitated the invention of Java are portability and security, other factors also played an important role in molding the final form of the language. The key considerations were summed up by the Java team in the following list of buzzwords: Sikkim Manipal University - DDE Page No. 5 OOPS with Java Unit 1 Simple Secure Portable Object-oriented Robust Multithreaded Architecture-neutral Interpreted High performance Distributed Dynamic Two of these buzzwords have already been discussed: secure and portable. Let's examine what each of them implies. Simple Java was designed to be easy for the professional programmer to learn and use effectively. Assuming that you have some programming experience, you will not find Java hard to master. If you already understand the basic concepts of object-oriented programming, learning Java will be even easier. Best of all, if you are an experienced C++ programmer, moving to Java will require very little effort. Because Java inherits the C/C++ syntax and many of the object-oriented features of C++, most programmers have little trouble learning Java. Also, some of the more confusing concepts from C++ are either left out of Java or implemented in a cleaner, more approachable manner. Beyond its similarities with C/C++, Java has another attribute that makes it easy to learn: it makes an effort not to have surprising features. In Java, there are some clearly defined ways to accomplish a given task. Object-Oriented Although influenced by its predecessors, Java was not designed to be source-code compatible with any other language. This allowed the Java team the freedom to design with a blank slate. One outcome of this was a clean, usable, pragmatic approach to objects. Borrowing liberally from many seminal object-software environments of the last few decades, Java manages to strike a balance between the purists’ "everything is an object" paradigm and the pragmatists’ "stay out of my way" model. The object Sikkim Manipal University - DDE Page No. 6 OOPS with Java Unit 1 model in Java is simple and easy to extend, while simple types, such as integers, are kept as high performance non objects. Robust The multiplatformed environment of the Web places extraordinary demands on a program, because the program must execute reliably in a variety of systems. Thus, the ability to create robust programs was given a high priority in the design of Java. To gain reliability, Java restricts you in a few key areas, to force you to find your mistakes early in program development. At the same time, Java frees you from having to worry about many of the most common causes of programming errors. Because Java is a strictly typed language, it checks your code at compile time. However, it also checks your code at run time. In fact, many hard-to-track-down bugs that often turn up in hard-to-reproduce run-time situations are simply impossible to create in Java. Knowing that what you have written will behave in a predictable way under diverse conditions is a key feature of Java. To better understand how Java is robust, consider two of the main reasons for program failure: memory management mistakes and mishandled exceptional conditions (that is, run-time errors). Memory management can be a difficult, tedious task in traditional programming environments. For example, in C/C++, the programmer must manually allocate and free all dynamic memory. This sometimes leads to problems, because programmers will either forget to free memory that has been previously allocated or, worse, try to free some memory that another part of their code is still using. Java virtually eliminates these problems by managing memory allocation and de-allocation for you. (In fact, de-allocation is completely automatic, because Java provides garbage collection for unused objects.) Exceptional conditions in traditional environments often arise in situations such as division by zero or "File not found," and they must be managed with clumsy and hard-to-read constructs. Java helps in this area by providing object-oriented exception handling. In a well-written Java program, all runtime errors can and should be managed by your program. Multithreaded Java was designed to meet the real-world requirement of creating interactive, networked programs. To accomplish this, Java supports multithreaded programming, which allows you to write programs that do many things simultaneously. The Java run-time system comes with an Sikkim Manipal University - DDE Page No. 7 OOPS with Java Unit 1 elegant yet sophisticated solution for multiprocess synchronization that enables you to construct smoothly running interactive systems. Java's easyto-use approach to multithreading allows you to think about the specific behavior of your program, not the multitasking subsystem. Architecture-Neutral A central issue for the Java designers was that of code longevity and portability. One of the main problems facing programmers is that no guarantee exists that if you write a program today, it will run tomorrow – even on the same machine. Operating system upgrades, processor upgrades, and changes in core system resources can all combine to make a program malfunction. The Java designers made several hard decisions in the Java language and in the Java Virtual Machine as an attempt to alter this situation. Their goal was "write once; run anywhere, any time, forever." To a great extent, this goal was accomplished. Interpreted and High Performance As described earlier, Java enables the creation of cross-platform programs by compiling into an intermediate representation called Java bytecode. This code can be interpreted on any system that provides a Java Virtual Machine. Most previous attempts at cross-platform solutions have been done at the expense of performance. Other interpreted systems, such as BASIC, Tcl, and PERL, suffer from almost insurmountable performance deficits. Java, however, was designed to perform well on very low-power CPUs. As explained earlier, while it is true that Java was engineered for interpretation, the Java bytecode was carefully designed so that it would be easy to translate directly into native machine code for very high performance by using a just-in-time compiler. Java run-time systems that provide this feature lose none of the benefits of the platform-independent code. "Highperformance cross-platform" is no longer an oxymoron. Distributed Java is designed for the distributed environment of the Internet, because it handles TCP/IP protocols. In fact, accessing a resource using a URL is not much different from accessing a file. The original version of Java (Oak) included features for intra-address space messaging. This allowed objects on two different computers to execute procedures remotely. Java has recently revived these interfaces in a package called Remote Method Sikkim Manipal University - DDE Page No. 8 OOPS with Java Unit 1 Invocation (RMI). This feature brings an unparalleled level of abstraction to client/server programming. Dynamic Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run time. This makes it possible to dynamically link code in a safe and expedient manner. This is crucial to the robustness of the applet environment, in which small fragments of bytecode may be dynamically updated on a running system. Self Assessment Questions: 7. ___________ is the ability of an application to perform multiple tasks at a time. 8. Java is tuned for _________. 9. Java is both _______________ and ________________. 1.5 Summary Java is a programming language developed by Sun Microsystems. Java is : o Simple – It is easy to learn Java. o Object-oriented – Everything in Java is in form of classes and objects. o Distributed – Java programs can access data across a network. o Compiled and Interpreted – The Java code you write is compiled to bytecode and interpreted when you execute the program. o Robust – Java programs are less prone to error. o Architecture Neutral and Portable – The bytecode can be executed on a variety of computers running on different operating system. o Secure – Java does not allow a programmer to manipulate the memory of the system. o A high performance programming language – Java programs are faster when compared to programs written in other interpreter-based languages. Sikkim Manipal University - DDE Page No. 9 OOPS with Java Unit 1 o Multithreaded – It allows multiple parts of a program to run simultaneously. o Dynamic – Maintaining different versions of an application is very easy in Java. 1.6 Terminal Questions 1. Give the features of Java. 2. What is Bytecode? 1.7 Answers Self Assessment Questions: 1. Oak 2. Patrick Naughton, Mike Sheridan, James Gosling 3. Mosaic 4. Compilation 5. Portable 6. Secure 7. Multithreading 8. Web 9. Compiled and Interpreted Terminal Questions: 1. Java is a simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multi-threaded and dynamic language. (Refer section 1.3) 2. Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM). (Refer section 1.3) Sikkim Manipal University - DDE Page No. 10 OOPS with Java Unit 2 Unit 2 Java Basics Structure 2.1 Introduction Objectives 2.2 Keywords 2.3 Working of Java 2.4 Including Comments 2.5 Data Types in Java Primitives Data Types Abstract / Derived Data Types 2.6 Variables in Java 2.7 Using Classes in Java 2.8 Declaring Methods in Java 2.9 Code to Display Test Value 2.10 The main Method 2.11 Invoking a Method in Java 2.12 Saving, Compiling and Executing Java Programs 2.13 Summary 2.14 Terminal Questions 2.15 Answers 2.1 Introduction In the last unit, we have discussed various features of Java. In this unit, we will discuss the basic programming structure in Java. Before that we all know that the English language has a vocabulary – a set of words that have certain meaning. It also provides us with rules for using the vocabulary – English grammar. The Java language also provides a vocabulary and a set of rules to use the vocabulary. The vocabulary is represented through a set of keywords and the grammar is the syntax of the language. This unit explains how to write object-oriented program using the Java language syntax. Objectives After studying this unit, you should be able to: list the keywords significant to Java compiler Sikkim Manipal University - DDE Page No. 11 OOPS with Java Unit 2 explain the working of Java describe different data types in Java explain the variables and their naming in Java use classes and coding standards in Java discuss declaring methods in Java use code to display test value discuss the main methods with its rules describe invoking a method in Java save, compile and execute a Java program 2.2 Keywords Keywords are special words that are of significance to the Java compiler. There are 48 reserved keywords currently defined in the Java language (see Table 2.1). These keywords combined with the syntax of the operators and separators, form the definition of the Java language. These keywords cannot be used as names for a variable, class, or method. Table 2.1: Java Reserved Keywords abstract boolean break byte case catch char class const continue default do double else extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while The keywords const and goto are reserved but not used. In addition to the keywords, Java reserves the following: true, false, and null. These are values defined by Java. You may not use these words for the names of variables, classes, and so on. Sikkim Manipal University - DDE Page No. 12 OOPS with Java Unit 2 2.3 Working of Java A compiler converts the Java program into an intermediate language representation called bytecode which is platform independent. A Java file will have the extension .java, similar to a word file having the extension .doc, a Pascal file having the extension .pas and a text file having the extension .txt. Let us assume that there exists a Java file named Hello.java. When this file is complied we get a file called as Hello.class. This class file is run using an interpreter as and when necessary. The Figure 2.1 shows the java program saved as Hello.java. Figure 2.1: A Sample Java Program The steps for compiling and running the program are shown in Figure 2.2. The program is stored in a subdirectory called java. When you run the above program, it prints the message “Hello! How are you? “ Sikkim Manipal University - DDE Page No. 13 OOPS with Java Unit 2 Figure 2.2: Compiling and Executing The concept of “write once, run anywhere” is possible in Java. The Java program can be compiled on any platform having a Java compiler. The resulting bytecode can then be run on Window NT or Solaris or Macintosh or any other machine. The machine should have a Java platform to run Java code. Java platform consists of Java Virtual Machine (JVM) and a package of ready made software components. This package is known as Java Application Programming Interface (Java API). The compiled Java program can run on any hardware platform having Java Virtual Machine (JVM) installed on it. Self Assessment Questions 1. A compiler converts the Java program into an intermediate language representation called ____________. 2. The concept of _________________ is possible in Java. 2.4 Including Comments Comments can be included in a Java program as follows: Type 1 /* Comments go here More comments here */ Sikkim Manipal University - DDE Page No. 14 OOPS with Java Unit 2 Type 2 // This information is ignored by the compiler till the end of the line Type 3 /* Documentation comment */ In the first type comments can spread over multiple lines. In the second type the information written after // is ignored by the compiler. This is used for writing single line comments. The third type of comment is used by a tool called javadoc for automatic generation of documentation. Self Assessment Questions: 3. The third type of comment is used by a tool called ___________ for automatic generation of documentation. 2.5 Data Types in Java There are two kinds of data types in Java: Primitive / Standard data types. Abstract / Derived data types. 2.5.1 Primitives Data Types Primitive data types (also know as standard data types) are the data types that are built into the Java language. The Java compiler holds detailed instructions on each legal operation the data type supports. There are eight primitive data types in Java (see Table 2.2). Table 2.2: Primitive / Standard Data Types Data Type byte Size/Form at (bits) 8 Description Range Byte-length integer -128 to 128 (signed) 0 to 255 (unsigned) short 16 Short integer 15 15 -1 31 31 -1 63 63 -1 -2 to 2 int 32 Integer -2 to 2 long 64 Long integer -2 to 2 float 32 Single precision floating point +/- about 10 Sikkim Manipal University - DDE 39 Page No. 15 OOPS with Java Unit 2 317 double 64 Double precision floating point +/- about 10 char 16 A single character Any single character A boolean value true or false boolean 1 The data types – byte, short, int, long, float and double are numeric data types. The first four of these can hold only whole numbers whereas the last two (float and double) can hold decimal values like 5.05. All these data types can hold negative values. However, the keyword unsigned can be used to restrict the range of values to positive numbers. Amongst others, boolean can hold only the value true or false and char can hold only a single character. 2.5.2 Abstract / Derived Data Types Abstract data types are based on primitive data types and have more functionality than the primitive data types. For example, String is an abstract data type that can store alphabets, digits and other special characters like /, (); :$#. You cannot perform calculations on a variable of the String data type even if the data stored in it has digits. Self Assessment Questions: 4. String is a ___________ data type in Java. 2.6 Variables in Java When you learned algebraic equations in school, you used x and y to represent values in equations. Unlike pi which has a constant value of 3.14, the values of x and y are not constant in equations. Java provides constants and variables to store data in programs. Java allocates memory to each variable and constant you use in your program. As in algebra, the values of variables may change in a program, but the values of constants, as the name suggests, do not change. You must assign unique names to variables and constants. Variable names are used in a program in much the same way as they are in ordinary algebra. Each variable used in a program must be declared. That is to say, the program must contain a statement specifying precisely what kind of information (data type) the variable will contain. This applies to every variable used in the program, regardless of the type. Sikkim Manipal University - DDE Page No. 16 OOPS with Java Unit 2 Naming Variables A program refers to a variable using its name. Certain rules and conventions govern the naming of variables. You must adhere to rules. Conventions help improve the readability of the program, but following them is not mandatory. Rules for Naming Variables in Java A variable name: Must not be a keyword in Java. Must not begin with a digit. Must not contain embedded spaces. Can contain characters from various alphabets, like Japanese, Greek, and Cyrillic. Syntax for Defining Variables All the attributes of a class are defined as data members. The syntax used to declare a class variable is: <data_type> <variable_name>; As the brackets “{ }” are used to mark the beginning and end of a class, a semicolon “;” is used to mark the end of a statement. Self Assessment Questions: 5. Keywords can be used as a variable name. True or False. 2.7 Using Classes in Java The data members and methods of a class are defined inside the class body. In Java, braces { } mark the beginning and end of a class or method. Any program that you write in Java can be written using a simple text editor. We will use Windows Notepad for writing programs. Example: class Employee { } Standard for Coding By following coding standards and conventions, you can write code that is easy to read and understand. Sikkim Manipal University - DDE Page No. 17 OOPS with Java Unit 2 One of the conventions is indentation. Notice that the code written below clearly indicates the data members defined in the class. Example: class Employee { String employeeName; String employeeAddress; } 2.8 Declaring Methods in Java The syntax for declaring a method in Java is as follows: <access_specifier><return_type><method_name> ([argument_list]) { } access_specifier An access specifier defines where a method can be accessed. A public specifier allows the method to be executed from another class. A private provides access to methods for only the current class. return_type The return_type of a method is the data type of the value that is returned by the method. Example: public void displayEmpName(); // returns no value, therefore, the return // type of the method is void. public float calculateAllowance(); // returns a value of float data type // therefore, the return type of the method // is float Self Assessment Questions: 6. A ____________ access specifier allows the method to be executed from another class. Sikkim Manipal University - DDE Page No. 18 OOPS with Java Unit 2 2.9 Code to Display Test Value The System class To communicate with the computer, a program needs to use certain system resources such as the display device and the keyboard. Java makes use of all these resources with the help of a class called System, which contains all the methods that are required to work with these resources. System is one of the most important and useful classes provided by Java. It provides a standard interface to common system resources like the display device and the keyboard. The out Object It is an object encapsulated inside the System class, and represents the standard output device. This object contains the println () method. The println () method The println () method displays the data on the screen. Example: System.out.println (“Hello World”); The above statement will display “Hello World” on the screen. 2.10 The main() Method In a Java application, you may have many classes. Within those classes, you may have many methods. The method that you need to execute first should be the main() method. Syntax for the main() method: public static void main(String args[]) { } The main () method should exist in a class that is declared as public. Rules for the main () method: The primary name of the file in which the code is written, and the name of the class that has the main() method should be exactly the same. If you try to execute a Java application that does not have a main () method, the following error message will be printed: Exception in thread “main” Java.lang.NoSuchMethodError: main Sikkim Manipal University - DDE Page No. 19 OOPS with Java Unit 2 2.11 Invoking a Method in Java Creating an Object of a class The new operator is used to create a class object. Example: Employee emp = new Employee (); Invoking a Method To invoke a method, the method name must be followed by parentheses and a semicolon. One method of a class can invoke another method of the same class using the name of the method. Example: class Employee { String employeeName; String employeeAddress; public Employee() { employeeName=”Bala”; employeeAddress = “Manipal“; } public void display() { System.out.println (“Name: “+employeeName); System.out.println(“Address: “+employeeAddress); } public static void main(String args[]) { Employee emp =new Employee(); emp.display (); } } Self Assessment Questions: 7. _____________ operator is used to create an object. Sikkim Manipal University - DDE Page No. 20 OOPS with Java Unit 2 2.12 Saving, Compiling and Executing a Java Program Saving The programs that you write in Java should be saved in a file, which has the following name format: <class_name>.java Compiling A program is a set of instructions. In order to execute a program, the operating system needs to understand the language. The only language an operating system understands is in terms of 0’s and 1’s i.e. the binary language. Programs written in language such as C and C++ are converted to binary code during the compilation process. However, that binary code can be understood only by the operating system for which the program is compiled. This makes the program or application as operating system dependent. In Java, the program is compiled into bytecode (.class file) that run on the Java Virtual Machine, which can interpret and run the program on any operating system. This makes Java programs platform-independent. At the command prompt, type javac <filename>.java to compile the Java program. Executing When the code is compiled and error-free, the program can be executed using the command: java <class filename> Self Assessment Questions: 8. _____________ is the extension for Java source code files. 9. _____ command is used to compile the Java source code. 10. _____ command is used to execute the Java class file. Sikkim Manipal University - DDE Page No. 21 OOPS with Java Unit 2 2.13 Summary In this unit, you have learnt the following: Creating Classes Using Java The data members and methods of a class are defined inside the class body. In Java, brackets {} mark the beginning and end of a class or method. The class keyword is used to declare a class. Coding Methods of a Class Methods provide functionality to classes. In Java, methods are declared in the class body. Declaring Objects The new operator is used to create a class object. Displaying Data on Screen The System class is one of the most important and useful classes provided by Java. It provides a standard interface to common system resources like the display device and the keyboard. The println() method displays the data on the screen. Compiling a Java Program In Java, the program is compiled into bytecode (.class file) that runs on the Java Virtual Machine, which can interpret and run the program on any operating system. This makes Java programs platform-independent. Executing a Java Program When the code is compiled and error-free, the program can be executed by issuing the following command: java <class filename> 2.14 Terminal Questions 1. The candidate class for the employee referral process has the following attributes and behaviors: Candidate candidateName candidateAddress candidateCourse displayDetails() Create the candidate class with its attribute and methods. Sikkim Manipal University - DDE Page No. 22 OOPS with Java Unit 2 2. What do you mean by the statement : System.out.println(“ “); 3. How do you compile a Java program? 4. How do you execute a Java program? 2.15 Answers Self Assessment Questions: 1. bytecode 2. write once, run anywhere 3. javadoc 4. abstract / derived 5. false 6. public 7. new 8. .java 9. Javac 10. java Terminal Questions: 1. class Candidate { String candidateName; String candidateAddress; String candidateCourse; public Candidate() { candidateName=”Arun”; candidateAddress=”Manipal”; candidateCourse=”BScIT”; } public void displayDetails() { System.out.println(“Name: “+candidateName); Sikkim Manipal University - DDE Page No. 23 OOPS with Java Unit 2 System.out.println(“Address: “+candidateAddress); System.out.println(“Course: “+candidateCourse); } } (Refer section 2.11) 2. System.out.println(“ “); will print a blank line. (Refer section 2.9) 3. Java programs are compiled using the command javac. (Refer section 2.12) 4. Java class files are executed using the command java. (Refer section 2.12) Sikkim Manipal University - DDE Page No. 24 OOPS with Java Unit 3 Unit 3 Operators and Control Statements Structure 3.1 Introduction Objectives 3.2 Operators Arithmetic Operators Increment and Decrement Operators Comparison Operators Logical Operators Operator Precedence 3.3 Control Flow Statements If-else Statement Switch Statement For Loop While Loop Do…While Loop Break Statement Continue Statement 3.4 Summary 3.5 Terminal Questions 3.6 Answers 3.1 Introduction In the last unit, you have learnt the basic program structure in Java. In this unit, we will explore various operators and control statements in Java. There are many constructs in Java to implement conditional execution. For example flow of a program can be controlled using the if construct. The if construct allows selective execution of statements depending on the value of the expressions associated with the if construct. Similarly repetitive tasks can be done using for constructs which would be discussed in detail in this unit. Objectives After studying this unit, you should be able to: explain different operators in Java Sikkim Manipal University - DDE Page No. 25 OOPS with Java Unit 3 discuss various control statements in Java 3.2 Operators Operators play an important role in Java. There are three kinds of operators in Java. They are (i) Arithmetic Operators (ii) Comparison / Relational Operators and (iii) Logical Operators 3.2.1 Arithmetic Operators Addition, Subtraction, Multiplication, Division and Modulus are the various arithmetic operations that can be performed in Java. Table 3.1: List of Arithmetic Operators Operator Meaning Use Meaning + Addition op1+op2 Adds op1 and op2 - Subtraction op1-op2 Subtracts op2 from op1 * Multiplication op1*op2 Multiplies op1 and op2 / Division op1/op2 Divides op1 by op2 % Modulus op1 % op2 Computes the remainder dividing op1 by op2 of The following Java program adds two numbers and prints the result. Sikkim Manipal University - DDE Page No. 26 OOPS with Java Unit 3 Figure 3.1: Java Program to add two numbers and printing the result The compilation and running of the program is shown in figure 3.2 Figure 3.2: Compilation and Running of Java Program 3.2.2 Increment and Decrement Operators The increment operator is ++ and decrement operator is –. This is used to add 1 to the value of a variable or subtract 1 from the value of a variable. These operators are placed either before the variable or after the variable name. The example below shows the use of these operators. Sikkim Manipal University - DDE Page No. 27 OOPS with Java Unit 3 Figure 3.3: Example showing increment operators in Java Figure 3.4: Program Compilation and Running When the operator ++ is placed after the variable name, first the assignment of the value of the variable takes place and then the value of the variable is incremented. This operation is also called post increment. Therefore the value of y1 will remain as 5 and the value of x1 will be 6. When the operator is placed before the variable, first increment of the variable takes place and then the assignment occurs. Hence the value x2 and y2 both will be 6. This operation is also called as pre increment. Similarly – – operator can be used to perform post decrement and pre decrement operations. If there is no assignment and only the value of variable has to be incremented or decremented then placing the operator after or before does not make difference. 3.2.3 Comparison Operators Comparison operators are used to compare two values and give the results. Table 3.2: List of Comparison Operators in Java Operator Meaning Example Remarks == Equal op1 = = op2 Checks if op1 is equal to op2 != Not Equal op1 != op2 Checks if op1 is not equal to op2 < Less than op1 < op2 Checks if op1 is less than op2 Sikkim Manipal University - DDE Page No. 28 OOPS with Java Unit 3 > Greater than op1 > op2 Checks if op1 is greater than op2 <= Less than or equal op1 <= op2 Checks if op1 is less than or equal to op2 >= Greater than or equal op1 >= op2 Checks if op1 is greater than or equal to op2 3.2.4 Logical Operators Logical operators are used to perform Boolean operations on the operands. Table 3.3: List of Logical Operators in Java Operator Meaning Example Remarks && Short-circuit AND op1 && op2 Returns true if both are true. If op1 is false, op2 will not be evaluated and returns false. || Short-circuit OR op1 || op2 Returns true if anyone is true. If op1 is true, op2 will not be evaluated and returns true. ! Logical unary NOT !op Returns true if op is false. & Logical AND Op1 & op2 Returns true if both are true. Always op1 and op2 will be evaluated. | Logical OR Op1 | op2 Returns true if anyone is true. Always op1 and op2 will be evaluated. 3.2.5 Operator Precedence When more than one operator is used in an expression, Java will use operator precedence rule to determine the order in which the operators will be evaluated. For example, consider the following expression: Result=10+5*8-15/5 Sikkim Manipal University - DDE Page No. 29 OOPS with Java Unit 3 In the above expression, multiplication and division operations have higher priority over the addition and subtraction. Hence they are performed first. Now, Result = 10+40-3. Addition and subtraction has the same priority. When the operators are having the same priority, they are evaluated from left to right in the order they appear in the expression. Hence the value of the result will become 47. In general the following priority order is followed when evaluating an expression: Increment and decrement operations. Arithmetic operations. Comparisons. Logical operations. Assignment operations. To change the order in which expressions are evaluated, parentheses are placed around the expressions that are to be evaluated first. When the parentheses are nested together, the expressions in the innermost parentheses are evaluated first. Parentheses also improve the readability of the expressions. When the operator precedence is not clear, parentheses can be used to avoid any confusion. Figure 3.5: Operator Precedence Example Self Assessment Questions: 1. Give the symbol for modulus operator. 2. Give the symbol for logical AND operator. Sikkim Manipal University - DDE Page No. 30 OOPS with Java Unit 3 3.3 Control Flow Statements Following statements are used to control the flow of execution in a program: 1. Decision Making Statements If-else statement Switch – case statement 2. Looping Statements For loop While loop Do-while loop 3. Other statements Break Continue 3.3.1 If-else statement The if statement is Java's conditional branch statement. It can be used to route program execution through two different paths. Here is the general syntax of the if statement: if (condition) statement1; else statement2; Here, each statement may be a single statement or a compound statement enclosed in curly brackets { }(that is, a block). The condition is any expression that returns a boolean value. The else clause is optional. The if statement works like this: If the condition is true, then statement1 is executed. Otherwise, statement2 (if it exists) is executed. In no case will both statements be executed. Figure 3.6: If… else statement example Sikkim Manipal University - DDE Page No. 31 OOPS with Java Unit 3 Most often, the expression used to control the if will involve the relational operators. However, this is not technically necessary. It is possible to control the if using a single boolean variable, as shown in this code fragment: boolean dataAvailable; // ... if (dataAvailable) ProcessData(); else waitForMoreData(); Remember, only one statement can appear directly after the if or the else. If you want to include more statements, you'll need to create a block, as in this fragment: int bytesAvailable; // ... if (bytesAvailable > 0) { ProcessData(); bytesAvailable -= n; } else waitForMoreData(); Here, both statements within the if block will execute if bytesAvailable is greater than zero. Some programmers find it convenient to include the curly braces when using the if, even when there is only one statement in each clause. This makes it easy to add another statement at a later date, and you don't have to worry about forgetting the brackets. In fact, forgetting to define a block when one is needed is a common cause of errors. For example, consider the following code fragment: int bytesAvailable; // ... if (bytesAvailable > 0) { ProcessData(); bytesAvailable -= n; } else Sikkim Manipal University - DDE Page No. 32 OOPS with Java Unit 3 waitForMoreData(); bytesAvailable = n; It seems clear that the statement bytesAvailable = n; was intended to be executed inside the else clause, because of the indentation level. However, as you recall, whitespace is insignificant to Java, and there is no way for the compiler to know what was intended. This code will compile without complaint, but it will behave incorrectly when run. The preceding example is fixed in the code that follows: int bytesAvailable; // ... if (bytesAvailable > 0) { ProcessData(); bytesAvailable -= n; } else { waitForMoreData(); bytesAvailable = n; } The if-else-if Ladder A common programming construct that is based upon a sequence of nested if is the if-else-if ladder. It looks like this: if(condition) statement; else if(condition) statement; else if(condition) statement; . . . else statement; Sikkim Manipal University - DDE Page No. 33 OOPS with Java Unit 3 The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed. The final else acts as a default condition; that is, if all other conditional tests fail, then the last else statement is performed. If there is no final else and all other conditions are false, then no action will take place. Here is a program that uses an if-else-if ladder to determine which season a particular month is in. // Demonstrate if-else-if statements. class IfElse { public static void main(String args[ ]) { int month = 4; // April String season; if(month == 12 || month == 1 || month == 2) season = "Winter"; else if(month == 3 || month == 4 || month == 5) season = "Spring"; else if(month == 6 || month == 7 || month == 8) season = "Summer"; else if(month == 9 || month == 10 || month == 11) season = "Autumn"; else season = "Bogus Month"; System.out.println("April is in the " + season + "."); } } Here is the output produced by the program: April is in the Spring. You might want to experiment with this program before moving on. As you will find, no matter what value you give month, one and only one assignment statement within the ladder will be executed. Sikkim Manipal University - DDE Page No. 34 OOPS with Java Unit 3 3.3.2 Switch Statement The switch statement is Java's multi-way branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression. As such, it often provides a better alternative than a large series of if-else-if statements. Here is the general form of a switch statement: switch (expression) { case value1: // statement sequence break; case value2: // statement sequence break; . . . case valueN: // statement sequence break; default: // default statement sequence } The expression must be of type byte, short, int, or char; each of the values specified in the case statements must be of a type compatible with the expression. Each case value must be a unique literal (that is, it must be a constant, not a variable). Duplicate case values are not allowed. The switch statement works as follows: The value of the expression is compared with each of the literal values in the case statements. If a match is found, the code sequence following that case statement is executed. If none of the constants matches the value of the expression, then the default statement is executed. However, the default statement is optional. If no case matches and no default is present, then no further action is taken. Sikkim Manipal University - DDE Page No. 35 OOPS with Java Unit 3 The break statement is used inside the switch to terminate a statement sequence. When a break statement is encountered, execution branches to the first line of code that follows the entire switch statement. This has the effect of "jumping out" of the switch. Figure 3.7: The switch…case statement example The break statement is optional. If you omit the break, execution will continue on into the next case. It is sometimes desirable to have multiple cases without break statements between them. For example, consider the following program: // In a switch, break statements are optional. class MissingBreak { public static void main(String args[ ]) { for(int i=0; i<12; i++) switch(i) { case 0: case 1: case 2: case 3: case 4: System.out.println("i is less than 5"); break; Sikkim Manipal University - DDE Page No. 36 OOPS with Java Unit 3 case 5: case 6: case 7: case 8: case 9: System.out.println("i is less than 10"); break; default: System.out.println("i is 10 or more"); } } } This program generates the following output: i is less than 5 i is less than 5 i is less than 5 i is less than 5 i is less than 5 i is less than 10 i is less than 10 i is less than 10 i is less than 10 i is less than 10 i is 10 or more i is 10 or more Nested switch Statements You can use a switch as part of the statement sequence of an outer switch. This is called a nested switch. Since a switch statement defines its own block, no conflicts arise between the case constants in the inner switch and those in the outer switch. For example, the following fragment is perfectly valid: Sikkim Manipal University - DDE Page No. 37 OOPS with Java Unit 3 switch(count) { case 1: switch(target) { // nested switch case 0: System.out.println("target is zero"); break; case 1: // no conflicts with outer switch System.out.println("target is one"); break; } break; case 2: // ... Here, the case 1: statement in the inner switch does not conflict with the case 1: statement in the outer switch. The count variable is only compared with the list of cases at the outer level. If count is 1, then target is compared with the inner list cases. In summary, there are three important features of the switch statement to note: The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type of Boolean expression. That is, the switch looks only for a match between the value of the expression and one of its case constants. No two case constants in the same switch can have identical values. Of course, a switch statement enclosed by an outer switch can have case constants in common. A switch statement is usually more efficient than a set of nested ifs. The last point is particularly interesting because it gives insight into how the Java compiler works. When it compiles a switch statement, the Java compiler will inspect each of the case constants and create a "jump table" that it will use for selecting the path of execution depending on the value of the expression. Therefore, if you need to select among a large group of values, a switch statement will run much faster than the equivalent logic Sikkim Manipal University - DDE Page No. 38 OOPS with Java Unit 3 coded using a sequence of if-else. The compiler can do this because it knows that the case constants are all the same type and simply must be compared for equality with the switch expression. The compiler has no such knowledge of a long list of if expressions. 3.3.3 For Loop The usage of for loop is as follows: for (initial statement; termination condition; increment instruction) statement; When multiple statements are to be included in the for loop, the statements are included inside flower braces as below: for (initial statement; termination condition; increment instruction) { statement1; statement2; } The example below prints numbers from 1 to 10. Figure 3.8: For loop example program The result of the above program is shown below: Figure 3.9: Result of the above for loop program Sikkim Manipal University - DDE Page No. 39 OOPS with Java Unit 3 Like all other programming languages, Java allows loops to be nested. That is, one loop may be inside another. For example, here is a program that nests for loops: // Loops may be nested. class Nested { public static void main(String args[ ]) { int i, j; for(i=0; i<10; i++) { for(j=i; j<10; j++) System.out.print("."); System.out.println(); } } } The output produced by this program is shown here: .......... ......... ........ ....... ...... ..... 3.3.4 While Loop The while loop is Java's most fundamental looping statement. It repeats a statement or block while its controlling expression is true. Here is its general form: while (condition) { // body of loop } The condition can be any Boolean expression. The body of the loop will be executed as long as the conditional expression is true. When condition becomes false, control passes to the next line of code immediately following Sikkim Manipal University - DDE Page No. 40 OOPS with Java Unit 3 the loop. The flower brackets are unnecessary if only a single statement is being repeated. Figure 3.10: While loop example 3.3.5 Do…. While Loop As you just saw, if the conditional expression controlling a while loop is initially false, then the body of the loop will not be executed at all. However, sometimes it is desirable to execute the body of a while loop at least once, even if the conditional expression is false to begin with. In other words, there are times when you would like to test the termination expression at the end of the loop rather than at the beginning. Fortunately, Java supplies a loop that does just that: the do-while. The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. Its general form is do { // body of loop } while (condition); Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of Java's loops, condition must be a boolean expression. Sikkim Manipal University - DDE Page No. 41 OOPS with Java Unit 3 Figure 3.11: Do…while loop example The do-while loop is especially useful when you process a menu selection, because you will usually want the body of a menu loop to execute at least once. Consider the following program which implements a very simple help system for Java's selection and iteration statements: // Using a do-while to process a menu selection class Menu { public static void main(String args[]) throws java.io.IOException { char choice; do { System.out.println("Help on:"); System.out.println(" 1. if"); System.out.println(" 2. switch"); System.out.println(" 3. while"); System.out.println(" 4. do-while"); System.out.println(" 5. for\\n"); System.out.println("Choose one:"); choice = (char) System.in.read(); } while( choice < '1' || choice > '5'); System.out.println("\\n"); Sikkim Manipal University - DDE Page No. 42 OOPS with Java Unit 3 switch(choice) { case '1': System.out.println("The if:\\n"); System.out.println("if(condition) statement;"); System.out.println("else statement;"); break; case '2': System.out.println("The switch:\\n"); System.out.println("switch(expression) {"); System.out.println(" case constant:"); System.out.println(" statement sequence"); System.out.println(" break;"); System.out.println(" // ..."); System.out.println("}"); break; case '3': System.out.println("The while:\\n"); System.out.println("while(condition) statement;"); break; case '4': System.out.println("The do-while:\\n"); System.out.println("do {"); System.out.println(" statement;"); System.out.println("} while (condition);"); break; case '5': System.out.println("The for:\\n"); System.out.print("for(init; condition; iteration)"); System.out.println(" statement;"); break; } } } Sikkim Manipal University - DDE Page No. 43 OOPS with Java Unit 3 Here is a sample run produced by this program: Help on: 1. if 2. switch 3. while 4. do-while 5. for Choose one: The do-while: do { statement; } while (condition); In the program, the do-while loop is used to verify that the user has entered a valid choice. If not, then the user is re-prompted. As the menu must be displayed at least once, the do-while is the perfect loop to accomplish this. A few other points about this example: Notice that the characters are read from the keyboard by calling System.in.read( ). This is one of Java's console input functions. Although Java's console I/O methods won't be discussed in detail, just know that System.in.read( ) is used here to obtain the user's choice. It reads characters from standard input (returned as integers, which is why the return value was cast to char). By default, standard input is line buffered, so you must press ENTER before any characters that you type will be sent to your program. Java's console input is quite limited and awkward to work with. Further, most real-world Java programs and applets will be graphical and window-based. For these reasons, not much use of console input has been made in this book. However, it is useful in this context. One other point; because System.in.read( ) is being used, the program must specify the throws java.io.IOException clause. This line is necessary to handle input errors. 3.3.6 Break Statement By using break, you can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop. Sikkim Manipal University - DDE Page No. 44 OOPS with Java Unit 3 When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop. Here is a simple example: // Using break to exit a loop class BreakLoop { public static void main(String args[ ]) { for(int i=0; i<100; i++) { if(i == 10) break; // terminate loop if i is 10 System.out.println("i: " + i); } System.out.println("Loop complete."); } } This program generates the following output: i: 0 i: 1 i: 2 i: 3 i: 4 i: 5 i: 6 i: 7 i: 8 i: 9 Loop complete. As you can see, although the for loop is designed to run from 0 to 99, the break statement causes it to terminate early, when i equal 10. 3.3.7 Continue Statement Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the loop, but stop processing the remainder of the code in its body for this particular iteration. The continue statement performs such an action. In while and do-while loops, a continue statement causes control to be transferred directly to the conditional expression that controls the loop. In a for loop, control goes first to the iteration portion of the for statement and then to the conditional expression. For all three loops, any intermediate code is bypassed. Sikkim Manipal University - DDE Page No. 45 OOPS with Java Unit 3 Here is an example program that uses continue to cause two numbers to be printed on each line: // Demonstrate continue. class Continue { public static void main (String args[ ]) { for (int i=0; i<10; i++) { System.out.print (i + " "); if (i%2 == 0) continue; System.out.println (""); } } } This code uses the % operator to check if i is even. If it is, the loop continues without printing a newline. Here is the output from this program: 01 23 45 67 89 As with the break statement, continue may specify a label to describe which enclosing loops to continue. Self Assessment Questions: 3. If-else is a looping statement. True or False. 4. Do…While is a decision making statement. True or False. 3.4 Summary This unit has given a brief overview of various operators and conditional statements in Java. Let us summarize the concepts: Implementing Conditional Execution You can control the flow of a program using the if construct. The if construct allows selective execution of statements depending on the value of the expressions associated with the if construct. Performing Repetitive Tasks Using Loop Construct You can perform repetitive tasks by making use of the for construct. Sikkim Manipal University - DDE Page No. 46 OOPS with Java Unit 3 3.5 Terminal Questions 1. 2. 3. 4. 5. 6. What are the different types of operators used in Java? What do you understand by operator precedence? What are the different types of control statements? Write Java program to print the address of the study center. Write Java program to convert the Rupees to Dollars. Write a Java program to compare whether your height is equal to your friends height. 7. Write a Java program to find the sum of 1+3+5+…. for 10 terms in the series. 3.6 Answers Self Assessment Questions: 1 % 2 & 3 False 4 False Terminal Questions: 1. Arithmetic, Comparison and Logical Operators. (Refer Section 3.2.1 to 3.2.4) 2. When more than one operator is used in an expression, Java will use operator precedence rule to determine the order in which the operators will be evaluated. (Refer Section 3.2) 3. If…else, Switch…Case, For, While, Do…While, Break, and Continue. (Refer Section 3.3.1 to 3.3.7) (Terminal Questions 4 to 7 are programming exercises. For this, you should go through this unit thoroughly.) Sikkim Manipal University - DDE Page No. 47 OOPS with Java Unit 4 Unit 4 Arrays and Strings Structure 4.1 Introduction Objectives 4.2 String Handling 4.3 Special String Operations 4.4 Character Extraction 4.5 String Comparison 4.6 Searching Strings 4.7 String Modification 4.8 StringBuffer 4.9 Summary 4.10 Terminal Questions 4.11 Answers 4.1 Introduction In the last unit, we have discussed operators and control flow statements. In this unit, we will introduce the concept of arrays and strings. The sorting of data can done using arrays, which represents a number of variables that occupy contiguous spaces in the memory. Each element in the array is distinguished by its index. All the elements in an array must be of the same data type. Objectives After studying this unit, you should be able to: discuss array representation in Java explain various string operations in Java 4.2 String Handling An array represents a number of variables which occupy contiguous spaces in the memory. Each element in the array is distinguished by its index. All elements in an array must be of the same data type. For example, you cannot have one element with int data type and another belonging to the boolean data type in the same array. An array is a collection of elements of the same type that are referenced by a common name. Each element of an Sikkim Manipal University - DDE Page No. 48 OOPS with Java Unit 4 array can be referred to by an array name and a subscript or index. To create and use an array in Java, you need to first declare the array and then initialize it. The syntax for creating an array is: data- type [ ] variablename; Example: int [ ] numbers; The above statement will declare a variable that can hold an array of int type variables. After declaring the variable for the array, the array needs to be allocated in memory. This can be done using the new operator in the following way: numbers = new int [10]; This statement assigns ten contiguous memory locations of the type int to the variable numbers. The array can store ten elements. Iteration can be used to access all the elements of the array, one by one. As is the case in most other programming languages, in Java a string is a sequence of characters. But, unlike many other languages that implement strings as character arrays, Java implements strings as objects of type String. Implementing strings as built-in objects allows Java to provide a full complement of features that make string handling convenient. For example, Java has methods to compare two strings, search for a substring, concatenate two strings, and change the case of letters within a string. Also, String objects can be constructed in a number of ways, making it easy to obtain a string when needed. When you create a String object, you are creating a string that cannot be changed. That is, once a String object has been created, you cannot change the characters that comprise that string. At first, this may seem to be a serious restriction. However, such is not the case. You can still perform all types of string operations. The difference is that each time you need an altered version of an existing string, a new String object is created that contains the modifications. The original string is left unchanged. This approach is used because fixed, immutable strings can be implemented more efficiently than changeable ones. For those cases in which a modifiable string is desired, there is a companion class to String called Sikkim Manipal University - DDE Page No. 49 OOPS with Java Unit 4 StringBuffer, whose objects contain strings that can be modified after they are created. Both the String and StringBuffer classes are defined in java.lang package. Thus, they are available to all programs automatically. Both are declared final, which means that neither of these classes may be sub-classed. This allows certain optimizations that increase performance to take place on common string operations. When we say that the strings within objects of type String are unchangeable it means that the contents of the String instance cannot be changed after it has been created. However, a variable declared as a String reference can be changed to point at some other String object at any time. The String class supports several constructors. To create an empty String, you call the default constructor. For example, String s = new String(); will create an instance of String with no characters in it. Frequently, you may want to create strings that have initial values. The String class provides a variety of constructors to handle this. To create a String initialized by an array of characters, use the constructor shown here: String(char chars[ ]); Here is an example: char chars[ ] = { 'a', 'b', 'c' }; String s = new String(chars); This constructor initializes s with the string "abc". You can specify a sub-range of a character array as an initializer using the following constructor: String(char chars[ ], int startIndex, int numChars); Here, startIndex specifies the index at which the sub-range begins, and numChars specifies the number of characters to use. Here is an example: char chars[ ] = { 'a', 'b', 'c', 'd', 'e', 'f' }; String s = new String(chars, 2, 3); Sikkim Manipal University - DDE Page No. 50 OOPS with Java Unit 4 This initializes s with the string “cde”. Please remember that the array index starts with 0. You can construct a String object that contains the same character sequence as another String object using this constructor: String(String strObj); Here, strObj is a String object. Consider this example: // Construct one String from another. class MakeString { public static void main(String args[ ]) { char c[ ] = {'J', 'a', 'v', 'a'}; String s1 = new String(c); String s2 = new String(s1); System.out.println(s1); System.out.println(s2); } } The output from this program is as follows: Java Java As you can see, s1 and s2 contain the same string. Even though Java's char type uses 16 bits to represent the Unicode character set, the typical format for strings on the Internet uses arrays of 8-bit bytes constructed from the ASCII character set. Because 8-bit ASCII strings are common, the String class provides constructors that initialize a string when given a byte array. Their forms are shown here: String(byte asciiChars[ ]); String(byte asciiChars[ ], int startIndex, int numChars); Sikkim Manipal University - DDE Page No. 51 OOPS with Java Unit 4 Here, asciiChars specifies the array of bytes. The second form allows you to specify a sub-range. In each of these constructors, the byte-to-character conversion is done by using the default character encoding of the platform. The following program illustrates these constructors: // Construct string from subset of char array. class SubStringCons { public static void main(String args[ ]) { byte ascii[ ] = {65, 66, 67, 68, 69, 70 }; String s1 = new String(ascii); System.out.println(s1); String s2 = new String(ascii, 2, 3); System.out.println(s2); } } This program generates the following output: ABCDEF CDE Extended versions of the byte-to-string constructors are also defined in which you can specify the character encoding that determines how bytes are converted to characters. However, most of the time, you will require to use the default encoding provided by the platform. The length of a string is the number of characters that it contains. To obtain this value, call the length( ) method, as shown here: int length( ); The following fragment prints "3", since there are three characters in the string s: char chars[ ] = { 'a', 'b', 'c' }; String s = new String(chars); System.out.println(s.length()); Sikkim Manipal University - DDE Page No. 52 OOPS with Java Unit 4 4.3 Special String Operations Because strings are a common and important part of programming, Java has added special support for several string operations within the syntax of the language. These operations include the automatic creation of new String instances from string literals, concatenation of multiple String objects by use of the + operator, and the conversion of other data types to a string representation. There are explicit methods available to perform all of these functions, but Java does them automatically as a convenience for the programmer and to add clarity. String Literals The earlier examples showed how to explicitly create a String instance from an array of characters by using the new operator. However, there is an easier way to do this using a string literal. For each string literal in your program, Java automatically constructs a String object. Thus, you can use a string literal to initialize a String object. For example, the following code fragment creates two equivalent strings: char chars[ ] = { 'a', 'b', 'c' }; String s1 = new String(chars); String s2 = "abc"; // use string literal Because a String object is created for every string literal, you can use a string literal any place you can use a String object. For example, you can call methods directly on a quoted string as if it were an object reference, as the following statement shows. It calls the length( ) method on the string "abc". As expected, it prints "3". System.out.println("abc".length()); String Concatenation In general, Java does not allow operators to be applied to String objects. The one exception to this rule is the + operator, which concatenates two strings, producing a String object as the result. This allows you to chain together a series of + operations. For example, the following fragment concatenates three strings: String age = "9"; String s = "He is " + age + " years old."; System.out.println(s); Sikkim Manipal University - DDE Page No. 53 OOPS with Java Unit 4 This displays the string "He is 9 years old." One practical use of string concatenation is found when you are creating very long strings. Instead of letting long strings wrap around within your source code, you can break them into smaller pieces, using the + to concatenate them. Here is an example: // Using concatenation to prevent long lines. class ConCat { public static void main(String args[ ]) { String longStr = "This could have been " + "a very long line that would have " + "wrapped around. But string concatenation " + "prevents this."; System.out.println(longStr); } } String Concatenation with Other Data Types You can concatenate strings with other types of data. For example, consider this slightly different version of the earlier example: int age = 9; String s = "He is” + age + “years old."; System.out.println(s); In this case, age is an int rather than another String, but the output produced is the same as before. This is because the int value in age is automatically converted into its string representation within a String object. This string is then concatenated as before. The compiler will convert an operand to its string equivalent whenever the other operand of the + is an instance of String. Sikkim Manipal University - DDE Page No. 54 OOPS with Java Unit 4 Be careful when you mix other types of operations with string concatenation expressions. You might get surprising results. Consider the following: String s = "four: " + 2 + 2; System.out.println(s); This fragment displays four: 22 rather than the four: 4 that you probably expected. Here's why. Operator precedence causes the concatenation of "four" with the string equivalent of 2 to take place first. This result is then concatenated with the string equivalent of 2 a second time. To complete the integer addition first, you must use parentheses, like this: String s = "four: " + (2 + 2); Now s contains the string "four: 4". String Conversion and toString( ) When Java converts data into its string representation during concatenation, it does so by calling one of the overloaded versions of the string conversion method valueOf( ) defined by String. valueOf( ) is overloaded for all the simple types and for type Object. For the simple types, valueOf( ) returns a string that contains the human-readable equivalent of the value with which it is called. For objects, valueOf( ) calls the toString( ) method on the object. We will look more closely at valueOf( ) later in this chapter. Here, let's examine the toString( ) method, because it is the means by which you can determine the string representation for objects of classes that you create. Every class implements toString( ), because it is defined by Object. However, the default implementation of toString( ) is seldom sufficient. For most important classes that you create, you may want to override toString( ) and provide your own string representations. Fortunately, this is easy to do. The toString( ) method has this general form: String toString( ) To implement toString( ), simply return a String object that contains the human-readable string that appropriately describes an object of your class. By overriding toString( ) for classes that you create, you allow the resulting strings to be fully integrated into Java's programming environment. For example, they can be used in print( ) and println( ) statements and in Sikkim Manipal University - DDE Page No. 55 OOPS with Java concatenation expressions. The following overriding toString( ) for the Box class: Unit 4 program demonstrates this by // Override toString() for Box class. class Box { double width; double height; double depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } public String toString() { return "Dimensions are " + width + " by " + depth + " by " + height + "."; } } class toStringDemo { public static void main(String args[ ]) { Box b = new Box(10, 12, 14); String s = "Box b: " + b; // concatenate Box object System.out.println(b); // convert Box to string System.out.println(s); } } Sikkim Manipal University - DDE Page No. 56 OOPS with Java Unit 4 The output of this program is shown here: Dimensions are 10 by 14 by 12. Box b: Dimensions are 10 by 14 by 12. As you can see, Box's toString( ) method is automatically invoked when a Box object is used in a concatenation expression or in a call to println( ). Self Assessment Questions 1. _____ represents a number of variables which occupy contiguous spaces in the memory. 2. Each element in the array is distinguished by its _____. 3. In Java, a _____ is a sequence of characters. 4.4 Character Extraction The String class provides a number of ways in which characters can be extracted from a String object. Each is examined here. Although the characters that comprise a string within a String object cannot be indexed as if they were a character array, many of the String methods employ an index (or offset) into the string for their operation. Like arrays, the string indexes begin at zero. charAt( ) To extract a single character from a String, you can refer directly to an individual character via the charAt( ) method. It has this general form: char charAt(int where); Here, where is the index of the character that you want to obtain. The value of where must be nonnegative and specify a location within the string. charAt( ) returns the character at the specified location. For example, char ch; ch = "abc".charAt(1); assigns the value "b" to ch. getChars( ) If you need to extract more than one character at a time, you can use the getChars( ) method. It has this general form: void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart) Sikkim Manipal University - DDE Page No. 57 OOPS with Java Unit 4 Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an index that is one past the end of the desired substring. Thus, the substring contains the characters from sourceStart through sourceEnd–1. The array that will receive the characters is specified by target. The index within target at which the substring will be copied is passed in targetStart. Care must be taken to assure that the target array is large enough to hold the number of characters in the specified substring. The following program demonstrates getChars( ): class getCharsDemo { public static void main(String args[ ]) { String s = "This is a demo of the getChars method."; int start = 10; int end = 14; char buf[ ] = new char[end - start]; s.getChars(start, end, buf, 0); System.out.println(buf); } } Here is the output of this program: demo getBytes( ) There is an alternative to getChars( ) that stores the characters in an array of bytes. This method is called getBytes( ), and it uses the default character-to-byte conversions provided by the platform. Here is its simplest form: byte[ ] getBytes( ); Other forms of getBytes( ) are also available. getBytes( ) is most useful when you are exporting a String value into an environment that does not support 16-bit Unicode characters. For example, most Internet protocols and text file formats use 8-bit ASCII for all text interchange. toCharArray( ) If you want to convert all the characters in a String object into a character array, the easiest way is to call toCharArray( ). It returns an array of characters for the entire string. Sikkim Manipal University - DDE Page No. 58 OOPS with Java Unit 4 It has this general form: char[ ] toCharArray( ); This function is provided as a convenience, since it is possible to use getChars( ) to achieve the same result. 4.5 String Comparison The String class includes several methods that compare strings or substrings within strings. Each is examined here. equals( ) and equalsIgnoreCase( ) To compare two strings for equality, use equals( ). It has this general form: boolean equals(Object str); Here, str is the String object being compared with the invoking String object. It returns true if the strings contain the same characters in the same order, and false otherwise. The comparison is case-sensitive. To perform a comparison that ignores case differences, call equalsIgnoreCase( ). When it compares two strings, it considers A-Z to be the same as a-z. It has this general form: boolean equalsIgnoreCase(String str); Here, str is the String object being compared with the invoking String object. It, too, returns true if the strings contain the same characters in the same order, and false otherwise. Here is an example that demonstrates equals( ) and equalsIgnoreCase( ): // Demonstrate equals() and equalsIgnoreCase(). class equalsDemo { public static void main(String args[ ]) { String s1 = "Hello"; String s2 = "Hello"; String s3 = "Good-bye"; String s4 = "HELLO"; System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2)); System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3)); Sikkim Manipal University - DDE Page No. 59 OOPS with Java Unit 4 System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4)); System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " + s1.equalsIgnoreCase(s4)); } } The output from the program is shown here: Hello equals Hello -> true Hello equals Good-bye -> false Hello equals HELLO -> false Hello equalsIgnoreCase HELLO -> true regionMatches( ) The regionMatches( ) method compares a specific region inside a string with another specific region in another string. There is an overloaded form that allows you to ignore case in such comparisons. Here are the general forms for these two methods: boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numChars); boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int numChars); For both versions, startIndex specifies the index at which the region begins within the invoking String object. The String being compared is specified by str2. The index at which the comparison will start within str2 is specified by str2StartIndex. The length of the substring being compared is passed in numChars. In the second version, if ignoreCase is true, the case of the characters is ignored. Otherwise, case is significant. startsWith( ) and endsWith( ) String defines two routines that are, more or less, specialized forms of regionMatches( ). The startsWith( ) method determines whether a given String begins with a specified string. Conversely, endsWith( ) determines whether the String in question ends with a specified string. They have the following general forms: boolean startsWith(String str); boolean endsWith(String str); Sikkim Manipal University - DDE Page No. 60 OOPS with Java Unit 4 Here, str is the String being tested. If the string matches, true is returned. Otherwise, false is returned. For example, "Foobar".endsWith("bar"); "Foobar".startsWith("Foo"); are both true. A second form of startsWith( ), shown here, lets you specify the starting point: boolean startsWith(String str, int startIndex); Here, startIndex specifies the index into the invoking string at which point the search will begin. For example, "Foobar".startsWith("bar", 3); returns true. equals( ) Versus == It is important to understand that the equals( ) method and the == operator perform two different operations. As just explained, the equals( ) method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance. The following program shows how two different String objects can contain the same characters, but references to these objects will not compare as equal: // equals() vs == class EqualsNotEqualTo { public static void main(String args[ ]) { String s1 = "Hello"; String s2 = new String(s1); System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2)); System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2)); } } The variable s1 refers to the String instance created by "Hello". The object referred to by s2 is created with s1 as an initializer. Thus, the contents of the two String objects are identical, but they are distinct objects. This means that s1 and s2 do not refer to the same objects and are, therefore, not ==, as is shown here by the output of the preceding example: Sikkim Manipal University - DDE Page No. 61 OOPS with Java Unit 4 Hello equals Hello -> true Hello == Hello -> false compareTo( ) Often, it is not enough to simply know whether two strings are identical. For sorting applications, you need to know which is less than, equal to, or greater than the next. A string is less than another if it comes before the other in dictionary order. A string is greater than another if it comes after the other in dictionary order. The String method compareTo( ) serves this purpose. It has this general form: int compareTo(String str); Here, str is the String being compared with the invoking String. The result of the comparison is returned and is interpreted as shown here: Value Meaning Less than zero The invoking string is less than str. Greater than zero The invoking string is greater than str. Zero The two strings are equal. Here is a sample program that sorts an array of strings. The program uses compareTo() to determine sort ordering for a bubble sort: // A bubble sort for strings. class SortString { static String arr[] = { “Now”, “is”, “the”, “time”, “for”, “all”, “good”, “men”, “to”, “come”, “to”, “the”, “aid”, “of”, “their”, “country” }; public static void main(String args[]) { for(int j=0; j<arr.length; j++) { if(arr[i].compareTo(arr[j])<0) { String t = arr[j]; arr[j] = arr[i]; Sikkim Manipal University - DDE Page No. 62 OOPS with Java Unit 4 arr[i] = t; } } System.out.println(arr[j]); } } } The output of this program is the list of words: Now aid all come country for good is men of the the their time to to As you can see from the output of this example, compareTo() takes into account uppercase and lowercase letters. The word “Now” comes out Sikkim Manipal University - DDE Page No. 63 OOPS with Java Unit 4 before all the others because it begins with an uppercase letter, which means it has a lower value in the ASCII character set. If you want to ignore case differences when comparing two strings, use compareToIgnoreCase(), shown here: int compareToIgnoreCase(String str) This method returns the same results as compareTo(), except that case differences are ignored. Self Assessment Questions 4. To extract a single character from a String, you can use _____ method. 5. To extract more than one character at a time, you can use _____ method. 6. To compare two strings for equality, use _____ method. 4.6 Searching Strings The String class provides two methods that allow you to search a string for a specified character or substring: • indexOf( ) Searches for the first occurrence of a character or substring. • lastIndexOf( ) Searches for the last occurrence of a character or substring. These two methods are overloaded in several different ways. In all cases, the methods return the index at which the character or substring was found, or –1 on failure. To search for the first occurrence of a character, use int indexOf(int ch); To search for the last occurrence of a character, use int lastIndexOf(int ch); Here, ch is the character being sought. To search for the first or last occurrence of a substring, use int indexOf(String str); int lastIndexOf(String str); Here, str specifies the substring. Sikkim Manipal University - DDE Page No. 64 OOPS with Java Unit 4 You can specify a starting point for the search using these forms: int indexOf(int ch, int startIndex); int lastIndexOf(int ch, int startIndex); int indexOf(String str, int startIndex); int lastIndexOf(String str, int startIndex); Here, startIndex specifies the index at which point the search begins. For indexOf( ), the search runs from startIndex to the end of the string. For lastIndexOf( ), the search runs from startIndex to zero. The following example shows how to use the various index methods to search inside of Strings: // Demonstrate indexOf() and lastIndexOf(). class indexOfDemo { public static void main(String args[]) { String s = "Now is the time for all good men " + "to come to the aid of their country."; System.out.println(s); System.out.println("indexOf(t) = " + s.indexOf('t')); System.out.println("lastIndexOf(t) = " + s.lastIndexOf('t')); System.out.println("indexOf(the) = " + s.indexOf("the")); System.out.println("lastIndexOf(the) = " + s.lastIndexOf("the")); System.out.println("indexOf(t, 10) = " + s.indexOf('t', 10)); System.out.println("lastIndexOf(t, 60) = " + s.lastIndexOf('t', 60)); System.out.println("indexOf(the, 10) = " + s.indexOf("the", 10)); System.out.println("lastIndexOf(the, 60) = " + s.lastIndexOf("the", 60)); } } Sikkim Manipal University - DDE Page No. 65 OOPS with Java Unit 4 Here is the output of this program: Now is the time for all good men to come to the aid of their country. indexOf(t) = 7 lastIndexOf(t) = 65 indexOf(the) = 7 lastIndexOf(the) = 55 indexOf(t, 10) = 11 lastIndexOf(t, 60) = 55 indexOf(the, 10) = 44 lastIndexOf(the, 60) = 55 4.7 String Modification Because String objects are immutable, whenever you want to modify a String, you must either copy it into a StringBuffer or use one of the following String methods, which will construct a new copy of the string with your modifications complete. substring( ) You can extract a substring using substring( ). It has two forms. The first is String substring(int startIndex); Here, startIndex specifies the index at which the substring will begin. This form returns a copy of the substring that begins at startIndex and runs to the end of the invoking string. The second form of substring( ) allows you to specify both the beginning and ending index of the substring: String substring(int startIndex, int endIndex); Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. The string returned contains all the characters from the beginning index, up to, but not including, the ending index. The following program uses substring( ) to replace all instances of one substring with another within a string: // Substring replacement. class StringReplace { public static void main(String args[ ]) { String org = "This is a test. This is, too."; Sikkim Manipal University - DDE Page No. 66 OOPS with Java Unit 4 String search = "is"; String sub = "was"; String result = ""; int i; do { // replace all matching substrings System.out.println(org); i = org.indexOf(search); if(i != -1) { result = org.substring(0, i); result = result + sub; result = result + org.substring(i + search.length()); org = result; } } while(i != -1); } } The output from this program is shown here: This is a test. This is, too. Thwas is a test. This is, too. Thwas was a test. This is, too. Thwas was a test. Thwas is, too. Thwas was a test. Thwas was, too. concat( ) You can concatenate two strings using concat( ), shown here: String concat(String str); This method creates a new object that contains the invoking string with the contents of str appended to the end. concat( ) performs the same function as +. For example, String s1 = "one"; String s2 = s1.concat("two"); puts the string "onetwo" into s2. It generates the same result as the following sequence: String s1 = "one"; String s2 = s1 + "two"; Sikkim Manipal University - DDE Page No. 67 OOPS with Java Unit 4 replace( ) The replace( ) method replaces all occurrences of one character in the invoking string with another character. It has the following general form: String replace(char original, char replacement); Here, original specifies the character to be replaced by the character specified by replacement. The resulting string is returned. For example, String s = "Hello".replace('l', 'w'); puts the string "Hewwo" into s. trim( ) The trim( ) method returns a copy of the invoking string from which any leading and trailing whitespace has been removed. It has this general form: String trim( ); Here is an example: String s = " Hello World ".trim(); This puts the string "Hello World" into s. The trim( ) method is quite useful when you process user commands. For example, the following program prompts the user for the name of a state and then displays that state's capital. It uses trim( ) to remove any leading or trailing whitespace that may have inadvertently been entered by the user. // Using trim() to process commands. import java.io.*; class UseTrim { public static void main(String args[ ]) throws IOException { // create a BufferedReader using System.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter 'stop' to quit."); System.out.println("Enter State: "); do { Sikkim Manipal University - DDE Page No. 68 OOPS with Java Unit 4 str = br.readLine(); str = str.trim(); // remove whitespace if(str.equals("Illinois")) System.out.println("Capital is Springfield."); else if(str.equals("Missouri")) System.out.println("Capital is Jefferson City."); else if(str.equals("California")) System.out.println("Capital is Sacramento."); else if(str.equals("Washington")) System.out.println("Capital is Olympia."); // ... } while(!str.equals("stop")); } } Data Conversion Using valueOf( ) The valueOf( ) method converts data from its internal format into a humanreadable form. It is a static method that is overloaded within String for all of Java's built-in types, so that each type can be converted properly into a string. valueOf( ) is also overloaded for type Object, so an object of any class type you create can also be used as an argument. (Recall that Object is a superclass for all classes.) Here are a few of its forms: static String valueOf(double num); static String valueOf(long num); static String valueOf(Object ob); static String valueOf(char chars[ ]); As we discussed earlier, valueOf( ) is called when a string representation of some other type of data is needed – for example, during concatenation operations. You can call this method directly with any data type and get a reasonable String representation. All of the simple types are converted to their common String representation. Any object that you pass to valueOf( ) will return the result of a call to the object's toString( ) method. In fact, you could just call toString( ) directly and get the same result. For most arrays, valueOf( ) returns a rather cryptic string, which indicates that it is an array of some type. For arrays of char, however, a String object is created that Sikkim Manipal University - DDE Page No. 69 OOPS with Java Unit 4 contains the characters in the char array. There is a special version of valueOf( ) that allows you to specify a subset of a char array. It has this general form: static String valueOf(char chars[ ], int startIndex, int numChars); Here, chars is the array that holds the characters, startIndex is the index into the array of characters at which the desired substring begins, and numChars specifies the length of the substring. Changing the Case of Characters within a String The method toLowerCase( ) converts all the characters in a string from uppercase to lowercase. The toUpperCase( ) method converts all the characters in a string from lowercase to uppercase. Non-alphabetical characters, such as digits, are unaffected. Here are the general forms of these methods: String toLowerCase( ); String toUpperCase( ); Both methods return a String object that contains the uppercase or lowercase equivalent to the invoking String. Here is an example that uses toLowerCase( ) and toUpperCase( ): // Demonstrate toUpperCase() and toLowerCase(). class ChangeCase { public static void main(String args[ ]) { String s = "This is a test."; System.out.println("Original: " + s); String upper = s.toUpperCase(); String lower = s.toLowerCase(); System.out.println("Uppercase: " + upper); System.out.println("Lowercase: " + lower); } } Sikkim Manipal University - DDE Page No. 70 OOPS with Java Unit 4 The output produced by the program is shown here: Original: This is a test. Uppercase: THIS IS A TEST. Lowercase: this is a test. Self Assessment Questions 7. _____ method searches for the first occurrence of a character or substring. 8. _____ method searches for the last occurrence of a character or substring. 9. You can extract a substring using _____ method. 4.8 StringBuffer StringBuffer is a peer class of String that provides much of the functionality of strings. As you know, String represents fixed-length, immutable character sequences. In contrast, StringBuffer represents growable and writeable character sequences. StringBuffer may have characters and substrings inserted in the middle or appended to the end. StringBuffer will automatically grow to make room for such additions and often has more characters pre-allocated than are actually needed, to allow room for growth. Java uses both classes heavily, but many programmers deal only with String and let Java manipulate StringBuffers behind the scenes by using the overloaded + operator. StringBuffer defines these three constructors: StringBuffer( ); StringBuffer(int size); StringBuffer(String str); The default constructor (the one with no parameters) reserves room for 16 characters without reallocation. The second version accepts an integer argument that explicitly sets the size of the buffer. The third version accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation. StringBuffer allocates room for 16 additional characters when no specific buffer length is requested, because reallocation is a costly process in terms of time. Also, frequent reallocations can fragment memory. By allocating Sikkim Manipal University - DDE Page No. 71 OOPS with Java Unit 4 room for a few extra characters, StringBuffer reduces the number of reallocations that take place. length( ) and capacity( ) The current length of a StringBuffer can be found via the length( ) method, while the total allocated capacity can be found through the capacity( ) method. They have the following general forms: int length( ); int capacity( ); The following program demonstrates the use of length() and capacity(). // StringBuffer length vs. capacity. class StringBufferDemo { public static void main(String args[ ]) { StringBuffer sb = new StringBuffer("Hello"); System.out.println("buffer = " + sb); System.out.println("length = " + sb.length()); System.out.println("capacity = " + sb.capacity()); } } Here is the output of this program, which shows how StringBuffer reserves extra space for additional manipulations: buffer = Hello length = 5 capacity = 21 Since sb is initialized with the string "Hello" when it is created, its length is 5. Its capacity is 21 because room for 16 additional characters is automatically added. ensureCapacity( ) If you want to pre-allocate room for a certain number of characters after a StringBuffer has been constructed, you can use ensureCapacity( ) to set the size of the buffer. This is useful if you know in advance that you will be appending a large number of small strings to a StringBuffer. ensureCapacity( ) has a general form: Sikkim Manipal University - DDE Page No. 72 OOPS with Java Unit 4 void ensureCapacity(int capacity); Here, capacity specifies the size of the buffer. setLength( ) To set the length of the buffer within a StringBuffer object, use setLength(). Its general form is shown here: void setLength(int len); Here, len specifies the length of the buffer. This value must be nonnegative. When you increase the size of the buffer, null characters are added to the end of the existing buffer. If you call setLength( ) with a value less than the current value returned by length( ), then the characters stored beyond the new length will be lost. The setCharAtDemo sample program in the following section uses setLength( ) to shorten a StringBuffer. charAt( ) and setCharAt( ) The value of a single character can be obtained from a StringBuffer via the charAt( ) method. You can set the value of a character within a StringBuffer using setCharAt( ). Their general forms are shown here: char charAt(int where); void setCharAt(int where, char ch); For charAt( ), „where’ specifies the index of the character being obtained. For setCharAt(), „where’ specifies the index of the character being set, and ch specifies the new value of that character. For both methods, „where’ must be non-negative and must not specify a location beyond the end of the buffer. The following example demonstrates charAt( ) and setCharAt( ): // Demonstrate charAt() and setCharAt(). class setCharAtDemo { public static void main(String args[ ]) { StringBuffer sb = new StringBuffer("Hello"); System.out.println("buffer before = " + sb); System.out.println("charAt(1) before = " + sb.charAt(1)); sb.setCharAt(1, 'i'); Sikkim Manipal University - DDE Page No. 73 OOPS with Java Unit 4 sb.setLength(2); System.out.println("buffer after = " + sb); System.out.println("charAt(1) after = " + sb.charAt(1)); } } Here is the output generated by this program: buffer before = Hello charAt(1) before = e buffer after = Hi charAt(1) after = i getChars( ) To copy a substring of a StringBuffer into an array, use the getChars( ) method. It has this general form: void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart); Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an index that is one past the end of the desired substring. This means that the substring contains the characters from sourceStart through sourceEnd–1. The array that will receive the characters is specified by target. The index within target at which the substring will be copied is passed in targetStart. Care must be taken to assure that the target array is large enough to hold the number of characters in the specified substring. append( ) The append( ) method concatenates the string representation of any other type of data to the end of the invoking StringBuffer object. It has overloaded versions for all the built-in types and for Object. Here are a few of its forms: StringBuffer append(String str); StringBuffer append(int num); StringBuffer append(Object obj); String.valueOf( ) is called for each parameter to obtain its string representation. The result is appended to the current StringBuffer object. The buffer itself is returned by each version of append( ). This allows subsequent calls to be chained together, as shown in the following example: Sikkim Manipal University - DDE Page No. 74 OOPS with Java Unit 4 // Demonstrate append(). class appendDemo { public static void main(String args[ ]) { String s; int a = 42; StringBuffer sb = new StringBuffer(40); s = sb.append("a = ").append(a).append("!").toString(); System.out.println(s); } } The output of this example is shown here: a = 42! The append( ) method is most often called when the + operator is used on String objects. Java automatically changes modifications to a String instance into similar operations on a StringBuffer instance. Thus, a concatenation invokes append( ) on a StringBuffer object. After the concatenation has been performed, the compiler inserts a call to toString( ) to turn the modifiable StringBuffer back into a constant String. All of this may seem unreasonably complicated. Why not just have one string class and have it behave more or less like StringBuffer? The answer is performance. There are many optimizations that the Java run time can make knowing that String objects are immutable. Thankfully, Java hides most of the complexity of conversion between Strings and StringBuffers. Actually, many programmers will never feel the need to use StringBuffer directly and will be able to express most operations in terms of the + operator on String variables. insert( ) The insert( ) method inserts one string into another. It is overloaded to accept values of all the simple types, plus Strings and Objects. Like append( ), it calls String.valueOf( ) to obtain the string representation of the value it is called with. This string is then inserted into the invoking StringBuffer object. These are a few of its forms: StringBuffer insert(int index, String str); StringBuffer insert(int index, char ch); StringBuffer insert(int index, Object obj); Sikkim Manipal University - DDE Page No. 75 OOPS with Java Unit 4 Here, index specifies the index at which point the string will be inserted into the invoking StringBuffer object. The following sample program inserts "like" between "I" and "Java": // Demonstrate insert(). class insertDemo { public static void main(String args[ ]) { StringBuffer sb = new StringBuffer("I Java!"); sb.insert(2, "like "); System.out.println(sb); } } The output of this example is shown here: I like Java! reverse( ) You can reverse the characters within a StringBuffer object using reverse(), as shown here: StringBuffer reverse( ); This method returns the reversed object on which it was called. The following program demonstrates reverse( ): // Using reverse() to reverse a StringBuffer. class ReverseDemo { public static void main(String args[ ]) { StringBuffer s = new StringBuffer("abcdef"); System.out.println(s); s.reverse(); System.out.println(s); } } Here is the output produced by the program: abcdef fedcba Sikkim Manipal University - DDE Page No. 76 OOPS with Java Unit 4 delete( ) and deleteCharAt( ) Java 2 adds to StringBuffer the ability to delete characters using the methods delete( ) and deleteCharAt( ). These methods are shown here: StringBuffer delete(int startIndex, int endIndex); StringBuffer deleteCharAt(int loc); The delete( ) method deletes a sequence of characters from the invoking object. Here, startIndex specifies the index of the first character to remove, and endIndex specifies an index one past the last character to remove. Thus, the substring deleted runs from startIndex to endIndex–1. The resulting StringBuffer object is returned. The deleteCharAt( ) method deletes the character at the index specified by loc. It returns the resulting StringBuffer object. Here is a program that demonstrates the delete( ) and deleteCharAt( ) methods: // Demonstrate delete() and deleteCharAt() class deleteDemo { public static void main(String args[ ]) { StringBuffer sb = new StringBuffer("This is a test."); sb.delete(4, 7); System.out.println("After delete: " + sb); sb.deleteCharAt(0); System.out.println("After deleteCharAt: " + sb); } } The following output is produced: After delete: This a test. After deleteCharAt: his a test. replace( ) Another new method added to StringBuffer by Java 2 is replace( ). It replaces one set of characters with another set inside a StringBuffer object. Its signature is shown here: StringBuffer replace(int startIndex, int endIndex, String str); Sikkim Manipal University - DDE Page No. 77 OOPS with Java Unit 4 The substring being replaced is specified by the indexes startIndex and endIndex. Thus, the substring at startIndex through endIndex–1 is replaced. The replacement string is passed in str. The resulting StringBuffer object is returned. The following program demonstrates replace( ): // Demonstrate replace() class replaceDemo { public static void main(String args[ ]) { StringBuffer sb = new StringBuffer("This is a test."); sb.replace(5, 7, "was"); System.out.println("After replace: " + sb); } } Here is the output: After replace: This was a test. substring( ) Java 2 also adds the substring( ) method, which returns a portion of a StringBuffer. It has the following two forms: String substring(int startIndex); String substring(int startIndex, int endIndex); The first form returns the substring that starts at startIndex and runs to the end of the invoking StringBuffer object. The second form returns the substring that starts at startIndex and runs through endIndex–1. These methods work just like those defined for String that were described earlier. Self Assessment Questions 10. To set the length of the buffer within a StringBuffer object, use _____ method. 11. The _____ method concatenates the string representation of any other type of data to the end of the invoking StringBuffer object. 12. You can reverse the characters within a StringBuffer object using _____ method. Sikkim Manipal University - DDE Page No. 78 OOPS with Java Unit 4 4.9 Summary In this unit, we have discussed the following: Storing Data in Arrays An array represents a number of variables that occupy contiguous spaces in the memory. Each element in the array is distinguished by its index. All the elements in an array must be of the same data type. Manipulating Strings in Java a string is a sequence of characters. Java implements strings as objects of type String. Implementing strings as built-in objects allows Java to provide a full complement of features that make string handling convenient. 4.10 Terminal Questions 1. What do you mean by an array? Explain with an example? 2. List out with examples various character extraction functions available in Java. 3. List out various String comparison functions in Java. 4. What are the functions available in Java to modify a String? Explain with examples. 5. List out the functions provided by StringBuffer class in Java. 4.11 Answers Self Assessment Questions 1. array 2. index 3. String 4. charAt() 5. getChars() 6. equals() 7. indexOf() 8. lastIndexOf() 9. substring() 10. setLength() 11. append() 12. reverse() Sikkim Manipal University - DDE Page No. 79 OOPS with Java Unit 4 Terminal Questions 1. An array represents a number of variables which occupy contiguous spaces in the memory. (Refer section 4.2) 2. charAt(), getChars(), getBytes(). (Refer section 4.4) 3. equals(), equalsIgnoreCase(), regionMatches(). (Refer section 4.5) 4. concat(), replace(), trim(). (Refer section 4.7) 5. length(), capacity(), setLength(), charAt(), etc. (Refer section 4.8) Sikkim Manipal University - DDE Page No. 80 OOPS with Java Unit 5 Unit 5 Inheritance, Package and Interface Structure 5.1 Introduction Objectives 5.2 Inheritance Types of Relationships What is Inheritance? Why Generalize? Implementing Inheritance in Java Access Specifiers The Abstract Class 5.3 Packages Defining a Package Understanding CLASSPATH 5.4 Interface Defining an Interface Some Uses of Interfaces Interfaces versus Abstract Classes 5.5 Summary 5.6 Terminal Questions 5.7 Answers 5.1 Introduction In the last unit, we have discussed arrays and strings in Java. In this unit, we will explain the concepts of Inheritance, Packages and Interfaces. Inheritance can create a general class that defines traits common to a set of related items. This class can then be inherited by other, more specific classes, each adding those things that are unique to it. In the terminology of Java, a class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a superclass. Java provides a mechanism for partitioning the class name space into more manageable chunks. This mechanism is the package. The package is both a naming and a visibility control mechanism. You can define classes inside a package that are not accessible by code outside that package. You can also define class members that are only Sikkim Manipal University - DDE Page No. 81 OOPS with Java Unit 5 exposed to other members of the same package. Using the keyword interface, you can fully abstract a class' interface from its implementation. That is, using interface, you can specify what a class must do, but not how it does it. Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body. Once defined then any number of classes can implement an interface. Objectives After studying this unit, you should be able to: explain the various types inheritance and its implementation define packages and understand CLASSPATH define and give the uses of interfaces 5.2 Inheritance Inheritance is one of the cornerstones of object-oriented programming, because it allows the creation of hierarchical classifications. Using inheritance, you can create a general class that defines traits common to a set of related items. This class can then be inherited by other, more specific classes, each adding those things that are unique to it. In the terminology of Java, a class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance variables and methods defined by the superclass and add its own, unique elements. 5.2.1 Types of Relationships Relationships are classified as follows: A Kind-Of relationship. A Is-A relationship. A Part-Of-relationship. A Has-A relationship. Consider for a moment the similarities and differences among the following objects/classes: Automobile, Ford, Porsche, Car and Engine. We can make the following observations: A truck is a kind of an automobile. A car is a (different) kind of an automobile. An engine is a part of an automobile. Sikkim Manipal University - DDE Page No. 82 OOPS with Java Unit 5 An automobile has an engine. The ford is a car. A-Kind-Of Relationship Taking the example of a human being and an elephant, both are ‘kind-of’ mammals. As human beings and elephants are ‘kind-of’ mammals, they share the attributes and behaviors of mammals. Human being and elephants are subset of the mammals class. The following figure depicts the relationship between the Mammals and Human Being classes: Figure 5.1: Example for A-Kind-Of relationship Is-A Relationship Let’s take an instance of the human being class – peter, who ‘is –a’ human being and, therefore, a mammal. The following figure depicts the ‘is –a’ relationship. Figure 5.2: Example for Is-A relationship Has-A Relationship/Part-Of Relationship A human being has a heart. This represents has-a relationship. Heart is a part of the human being. This represents part-of relationship. The following figure depicts the relationship between a human being and a heart. Sikkim Manipal University - DDE Page No. 83 OOPS with Java Unit 5 Has-A Human Being Heart Part-Of Figure 5.3: Example for Has-A/Part-Of Relationship 5.2.2 What is Inheritance? The philosophy behind inheritance is to portray things as they exist in the real world. For instance, a child inherits properties from both the parents. Inheritance means that a class derives a set of attributes and related behaviors from another class. Inheritance helps you to: Reduce redundancy in code. Code redundancy means writing the same code in different places, leading to unnecessary replication of code. Inheritance helps you to reuse code. Maintain code easily, as the code resides at one place (superclass). Any changes made to the superclass automatically change the behavior automatically. Extend the functionality of an existing class by adding more methods to the subclass. 5.2.3 Why Generalize? The most important reason for generalization is to make programs extensible. Consider a simple example from the programming world. Assume that you have a program that displays a string, after accepting it from the user. Now, suppose your requirement has changed and you want to display an integer. Assume that you have Data as a superclass, which has a method to display its value. You also have Character and Float as subclasses of the Data class. To be able to display an integer, all you need to do is to create a class called Integer, which is a subclass of Data. Sikkim Manipal University - DDE Page No. 84 OOPS with Java Unit 5 Adding a new subclass will not affect the existing classes. There is no need to write different methods to display each of these subclasses. Since the superclass has this method, the subclasses inherit the same from it. Generalization helps in abstraction. A superclass has the attributes and methods, which are the bare essentials for that particular superclass, and are acquired by all its subclasses. 5.2.4 Implementing Inheritance in Java The extends keyword is used to derive a class from a superclass, or in other words, extend the functionality of a superclass. Syntax public class <subclass_name> extends <superclass_name> Example public class Confirmed extends Ticket { } Rules for Overriding Methods The method name and the order of arguments should be identical to that of the superclass method. The return type of both the methods must be the same. The overriding method cannot be less accessible than the method it overrides. For example, if the method to override is declared as public in the superclass, you cannot override it with the private keyword in the subclass. An overriding method cannot raise more exceptions than those raised by the superclass. Example // Create a superclass. class A { int i, j; void showij() { System.out.println("i and j: " + i + " " + j); } } Sikkim Manipal University - DDE Page No. 85 OOPS with Java Unit 5 // Create a subclass by extending class A. class B extends A { int k; void showk() { System.out.println("k: " + k); } void sum() { System.out.println("i+j+k: " + (i+j+k)); } } class SimpleInheritance { public static void main(String args[]) { A superOb = new A(); B subOb = new B(); // The superclass may be used by itself. superOb.i = 10; superOb.j = 20; System.out.println("Contents of superOb: "); superOb.showij(); System.out.println(); /* The subclass has access to all public members of its superclass. */ subOb.i = 7; subOb.j = 8; subOb.k = 9; System.out.println("Contents of subOb: "); subOb.showij(); subOb.showk(); System.out.println(); System.out.println("Sum of i, j and k in subOb:"); subOb.sum(); } } Sikkim Manipal University - DDE Page No. 86 OOPS with Java Unit 5 The output from this program is shown here: Contents of superOb: i and j: 10 20 Contents of subOb: i and j: 7 8 k: 9 Sum of i, j and k in subOb: i+j+k: 24 As you can see, the subclass B includes all of the members of its superclass, A. This is why subOb can access i and j and call showij ( ). Also, inside sum ( ), i and j can be referred to directly, as if they were part of B. Even though A is a superclass for B, it is also a completely independent, stand-alone class. Being a superclass for a subclass does not mean that the superclass cannot be used by itself. Further, a subclass can be a superclass for another subclass. The general form of a class declaration that inherits a superclass is shown here: class subclass-name extends superclass-name { // body of class } You can only specify one superclass for any subclass that you create. Java does not support the inheritance of multiple superclasses into a single subclass. (This differs from C++, in which you can inherit multiple base classes.) You can, as stated, create a hierarchy of inheritance in which a subclass becomes a superclass of another subclass. However, no class can be a superclass of itself. 5.2.5 Access Specifiers An access specifier determines which features of a class (the class itself, the data members, and the methods) may be used by other classes. Java supports three access specifiers. public. private. protected. Sikkim Manipal University - DDE Page No. 87 OOPS with Java Unit 5 The public Access Specifiers All classes except the inner class (class within classes) can have the public access specifier. You can use a public class, a data member, or a method from any object in any Java program. Example: public class publicclass { public int publicvaraible; public void publicmethod () { } } The private Access Specifier Only objects of the same class can access a private variable or method. You can declare only variables, methods, and inner classes as private. Example: private int privatevariable; The protected Access Specifier The variables, methods, and inner classes that are declared protected are accessible to the subclasses of the class in which they are declared. Example: protected int protectedvariable; Default Access If you do not specify any of the above access specifiers, the scope is friendly. A class, variable, or method that has friendly access is accessible to all the classes of a package. Consider the following set of classes. Class Y and Z inherit from class X. Class Z belongs to a package different than that of classes X and Y. Sikkim Manipal University - DDE Page No. 88 OOPS with Java Unit 5 X Y Figure 5.4: Example showing the default access A method accessMe() has been declared in class X. The following table shows you the accessibility of the method accessMe() from classes Y and Z Table 5.1: Table showing the accessibility Access Specifier Class Y Class Z accessMe () is declared as protected Accessible, as Y is a subclass Accessible, as Z is a subclass (event if it is in another package) accessMe () is declared without an access specifier (friendly) Accessible, as it is in the same package Not accessible, as it is not in the same package You can access a non-private variable or method using an object of the class as shown below: Someclass classobject = new someclass (); Classobject.publicvariable; Classobject.protectedmethod(); Sikkim Manipal University - DDE Page No. 89 OOPS with Java Unit 5 Although a subclass includes all of the members of its superclass, it cannot access those members of the superclass that have been declared as private. For example, consider the following simple class hierarchy: /* In a class hierarchy, private members remain private to their class. This program contains an error and will not compile. */ // Create a superclass. class A { int i; // public by default private int j; // private to A void setij(int x, int y) { i = x; j = y; } } // A's j is not accessible here. class B extends A { int total; void sum() { total = i + j; // ERROR, j is not accessible here } } class Access { public static void main(String args[]) { B subOb = new B(); subOb.setij(10, 12); subOb.sum(); System.out.println("Total is " + subOb.total); } } This program will not compile because the reference to j inside the sum( ) method of B causes an access violation. Since j is declared as private, it is only accessible by other members of its own class. Subclasses have no access to it. Note: A class member that has been declared as private will remain private to its class. It is not accessible by any code outside its class, including subclasses. Sikkim Manipal University - DDE Page No. 90 OOPS with Java Unit 5 A Superclass Variable can reference a Subclass Object A reference variable of a superclass can be assigned a reference to any subclass derived from that superclass. You will find this aspect of inheritance quite useful in a variety of situations. For example, consider the following: class RefDemo { public static void main(String args[]) { BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37); Box plainbox = new Box(); double vol; vol = weightbox.volume(); System.out.println("Volume of weightbox is " + vol); System.out.println("Weight of weightbox is " + weightbox.weight); System.out.println(); // assign BoxWeight reference to Box reference plainbox = weightbox; vol = plainbox.volume(); // OK, volume() defined in Box System.out.println("Volume of plainbox is " + vol); /* The following statement is invalid because plainbox does not define a weight member. */ // System.out.println("Weight of plainbox is " + plainbox.weight); } } Here, weightbox is a reference to BoxWeight objects, and plainbox is a reference to Box objects. Since BoxWeight is a subclass of Box, it is permissible to assign plainbox a reference to the weightbox object. It is important to understand that it is the type of the reference variable – not the type of the object that it refers to – that determines what members can be accessed. That is, when a reference to a subclass object is assigned to a Sikkim Manipal University - DDE Page No. 91 OOPS with Java Unit 5 superclass reference variable, you will have access only to those parts of the object defined by the superclass. This is why plainbox can't access weight even when it refers to a BoxWeight object. If you think about it, this makes sense, because the superclass has no knowledge of what a subclass adds to it. This is why the last line of code in the preceding fragment is commented out. It is not possible for a Box reference to access the weight field, because it does not define one. Although the preceding may seem a bit esoteric, it has some important practical applications – two of which are discussed later in this chapter. Using super In the preceding examples, classes derived from Box were not implemented as efficiently or as robustly as they could have been. For example, the constructor for BoxWeight explicitly initializes the width, height, and depth fields of Box( ). Not only does this duplicate code found in its superclass, which is inefficient, but it implies that a subclass must be granted access to these members. However, there will be times when you will want to create a superclass that keeps the details of its implementation to itself (that is, that keeps its data members private). In this case, there would be no way for a subclass to directly access or initialize these variables on its own. Since encapsulation is a primary attribute of OOP, it is not surprising that Java provides a solution to this problem. Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword super. super has two general forms. The first calls the superclass' constructor. The second is used to access a member of the superclass that has been hidden by a member of a subclass. Each use is examined here. Using super to Call Superclass Constructors A subclass can call a constructor method defined by its superclass by use of the following form of super: super(parameter-list); Here, parameter-list specifies any parameters needed by the constructor in the superclass. super( ) must always be the first statement executed inside a subclass' constructor. To see how super( ) is used, consider this improved version of the BoxWeight( ) class: // BoxWeight now uses super to initialize its Box attributes. Sikkim Manipal University - DDE Page No. 92 OOPS with Java Unit 5 class BoxWeight extends Box { double weight; // weight of box // initialize width, height, and depth using super() BoxWeight(double w, double h, double d, double m) { super(w, h, d); // call superclass constructor weight = m; } } Here, BoxWeight( ) calls super( ) with the parameters w, h, and d. This causes the Box( ) constructor to be called, which initializes width, height, and depth using these values. BoxWeight no longer initializes these values itself. It only needs to initialize the value unique to it: weight. This leaves Box free to make these values private if desired. In the preceding example, super( ) was called with three arguments. Since constructors can be overloaded, super( ) can be called using any form defined by the superclass. The constructor executed will be the one that matches the arguments. For example, here is a complete implementation of BoxWeight that provides constructors for the various ways that a box can be constructed. In each case, super( ) is called using the appropriate arguments. Notice that width, height, and depth have been made private within Box. // A complete implementation of BoxWeight. class Box { private double width; private double height; private double depth; // construct clone of an object Box(Box ob) { // pass object to constructor width = ob.width; height = ob.height; depth = ob.depth; } Sikkim Manipal University - DDE Page No. 93 OOPS with Java Unit 5 // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } // constructor used when cube is created Box(double len) { width = height = depth = len; } // compute and return volume double volume() { return width * height * depth; } } // BoxWeight now fully implements all constructors. class BoxWeight extends Box { double weight; // weight of box // construct clone of an object BoxWeight(BoxWeight ob) { // pass object to constructor super(ob); weight = ob.weight; } // constructor when all parameters are specified Sikkim Manipal University - DDE Page No. 94 OOPS with Java Unit 5 BoxWeight(double w, double h, double d, double m) { super(w, h, d); // call superclass constructor weight = m; } // default constructor BoxWeight() { super(); weight = -1; } // constructor used when cube is created BoxWeight(double len, double m) { super(len); weight = m; } } class DemoSuper { public static void main(String args[]) { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); BoxWeight mybox3 = new BoxWeight(); // default BoxWeight mycube = new BoxWeight(3, 2); BoxWeight myclone = new BoxWeight(mybox1); double vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); System.out.println("Weight of mybox1 is " + mybox1.weight); System.out.println(); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); System.out.println("Weight of mybox2 is " + mybox2.weight); Sikkim Manipal University - DDE Page No. 95 OOPS with Java Unit 5 System.out.println(); vol = mybox3.volume(); System.out.println("Volume of mybox3 is " + vol); System.out.println("Weight of mybox3 is " + mybox3.weight); System.out.println(); vol = myclone.volume(); System.out.println("Volume of myclone is " + vol); System.out.println("Weight of myclone is " + myclone.weight); System.out.println(); vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); System.out.println("Weight of mycube is " + mycube.weight); System.out.println(); } } This program generates the following output: Volume of mybox1 is 3000.0 Weight of mybox1 is 34.3 Volume of mybox2 is 24.0 Weight of mybox2 is 0.076 Volume of mybox3 is -1.0 Weight of mybox3 is -1.0 Volume of myclone is 3000.0 Weight of myclone is 34.3 Volume of mycube is 27.0 Weight of mycube is 2.0 Pay special attention to this constructor in BoxWeight( ): // construct clone of an object BoxWeight(BoxWeight ob) { // pass object to constructor super(ob); Sikkim Manipal University - DDE Page No. 96 OOPS with Java Unit 5 weight = ob.weight; } Notice that super( ) is called with an object of type BoxWeight – not of type Box. This still invokes the constructor Box(Box ob). As mentioned earlier, a superclass variable can be used to reference any object derived from that class. Thus, we are able to pass a BoxWeight object to the Box constructor. Of course, Box only has knowledge of its own members. Let's review the key concepts behind super( ). When a subclass calls super( ), it is calling the constructor of its immediate superclass. Thus, super( ) always refers to the superclass immediately above the calling class. This is true even in a multi-leveled hierarchy. Also, super( ) must always be the first statement executed inside a subclass constructor. A Second Use of super The second form of super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used. This usage has the following general form: super.member Here, member can be either a method or an instance variable. This second form of super is most applicable to situations in which member names of a subclass hide members by the same name in the superclass. Consider this simple class hierarchy: // Using super to overcome name hiding. class A { int i; } // Create a subclass by extending class A. class B extends A { int i; // this i hides the i in A B(int a, int b) { super.i = a; // i in A i = b; // i in B Sikkim Manipal University - DDE Page No. 97 OOPS with Java Unit 5 } void show() { System.out.println("i in superclass: " + super.i); System.out.println("i in subclass: " + i); } } class UseSuper { public static void main(String args[]) { B subOb = new B(1, 2); subOb.show(); } } This program displays the following: i in superclass: 1 i in subclass: 2 Although the instance variable i in B hides the i in A, super allows access to the i defined in the superclass. As you will see, super can also be used to call methods that are hidden by a subclass. 5.2.6 The abstract class An abstract class defines common properties and behaviors of other classes. An abstract class is used as a base class to derive specific classes of the same kind. It defines properties common to the classes derived from it. The abstract keyword is used to declare such a class. The classes declared using the abstract keyword cannot be instantiated. Syntax: abstract class <class_name> { } You can also declare abstract methods. Abstract methods have public scope. The code below declares an abstract method for the class shape. abstract class Shape { public abstract float calculateArea (); Sikkim Manipal University - DDE Page No. 98 OOPS with Java Unit 5 } The abstract method calculateArea(), given above, is inherited by the subclasses of the Shape class. The subclasses Rectangle, Circle and Hexagon implement this method in different ways. public class Circle extends Shape { float radius; public float calculateArea () { return radius*22/7; } } In the above example, the calculateArea () method has been overridden in the circle class. If the method is not overridden, the class will inherit the abstract method from the parent class. Any class that has an abstract method is abstract. Hence, you would not be able to create an object of the circle class. Therefore, it is necessary to override the calculateArea() method in the circle class. The final Keyword A class called password authenticates user login. You do not want anybody to change the functionality of the class by extending it. To prevent inheritance, use the final modifier. Example: final class password { } You will also find final classes in JDK package. For example, the java.lang.String class has been declared final. This is done for security reasons. It ensures that any method that refers to the String class gets the actual String class and not a modified one. Sikkim Manipal University - DDE Page No. 99 OOPS with Java Unit 5 Self Assessment Questions 1. ________ is one of the features of object oriented programming that allows the creation of hierarchical classifications. 2. A class that is inherited is called a ________. 3. The class that does the inheriting is called a ________. 4. Engine has a __________ relationship with automobile. 5. ________, ________ and ________ are the three types of access specifiers in Java. 5.3 Packages In the preceding section, the name of each example class was taken from the same name space. This means that a unique name has to be used for each class to avoid name collisions. After a while, without some way to manage the name space, you could run out of convenient, descriptive names for individual classes. You also need some way to be assured that the name you choose for a class will be reasonably unique and not collide with class names chosen by other programmers. (Imagine a small group of programmers fighting over who gets to use the name "Foobar" as a class name. Or, imagine the entire Internet community arguing over ‘who first named a class Espresso.’) Thankfully, Java provides a mechanism for partitioning the class name space into more manageable chunks. This mechanism is the package. The package is both a naming and a visibility control mechanism. You can define classes inside a package that are not accessible by code outside that package. You can also define class members that are only exposed to other members of the same package. This allows your classes to have intimate knowledge of each other, but not expose that knowledge to the rest of the world. 5.3.1 Defining a Package To create a package is quite easy: simply include a package command as the first statement in a Java source file. Any classes declared within that file will belong to the specified package. The package statement defines a name space in which classes are stored. If you omit the package statement, the class names are put into the default package, which has no name. (This is why you haven't had to worry about packages before now.) While the default package is fine for short, sample programs, it is inadequate for real Sikkim Manipal University - DDE Page No. 100 OOPS with Java Unit 5 applications. Most of the time, you will define a package for your code. This is the general form of the package statement: package pkg; Here, pkg is the name of the package. For example, the following statement creates a package called MyPackage. package MyPackage; Java uses file system directories to store packages. For example, the .class files for any classes you declare to be part of MyPackage must be stored in a directory called MyPackage. Remember that case is significant, and the directory name must match the package name exactly. More than one file can include the same package statement. The package statement simply specifies to which package the classes defined in a file belong. It does not exclude other classes in other files from being part of that same package. Most real-world packages are spread across many files. You can create a hierarchy of packages. To do so, simply separate each package name from the one above it by use of a period. The general form of a multi-leveled package statement is shown here: package pkg1 [.pkg2 [.pkg3]]; A package hierarchy must be reflected in the file system of your Java development system. For example, a package declared as package java.awt.image; needs to be stored in java/awt/image, java\\awt\\image, or java:awt:image on your UNIX, Windows, or Macintosh file system, respectively. Be sure to choose your package names carefully. You cannot rename a package without renaming the directory in which the classes are stored. 5.3.2 Understanding CLASSPATH Before an example that uses a package is presented, a brief discussion of the CLASSPATH environmental variable is required. While packages solve many problems from an access control and name-space-collision perspective, they cause some curious difficulties when you compile and run programs. This is because the specific location that the Java compiler will consider as the root of any package hierarchy is controlled by CLASSPATH. Until now, you have been storing all of your classes in the same, unnamed default package. Doing so allowed you to simply compile the source code and run the Java interpreter on the result by naming the class on the Sikkim Manipal University - DDE Page No. 101 OOPS with Java Unit 5 command line. This worked because the default current working directory (.) is usually in the CLASSPATH environmental variable defined for the Java run-time system, by default. However, things are not so easy when packages are involved. Assume that you create a class called PackTest in a package called test. Since your directory structure must match your packages, you create a directory called test and put PackTest.java inside that directory. You then make test the current directory and compile PackTest.java. This results in PackTest.class being stored in the test directory, as it should be. When you try to run PackTest, though, the Java interpreter reports an error message similar to "can't find class PackTest." This is because the class is now stored in a package called test. You can no longer refer to it simply as PackTest. You must refer to the class by enumerating its package hierarchy, separating the packages with dots. This class must now be called test.PackTest. However, if you try to use test.PackTest, you will still receive an error message similar to "can't find class test/PackTest." The reason you still receive an error message is hidden in your CLASSPATH variable. Remember, CLASSPATH sets the top of the class hierarchy. The problem is that there's no test directory in the current working directory, because you are in the test directory, itself. You have two choices at this point: change directories up one level and try java test.PackTest, or add the top of your development class hierarchy to the CLASSPATH environmental variable. Table 5.2: Table showing the Class Member Access Sikkim Manipal University - DDE Page No. 102 OOPS with Java Unit 5 Self Assessment Questions 6. ___________ is the mechanism in Java through which class name space is partitioned into more manageable chunks. 7. ___________ keyword is used to define a package. 8. In Java, multi-leveled packages can be created. True / False. 9. The specific location that the Java compiler will consider as the root of any package hierarchy is controlled by ___________. 10. ________ symbol denotes the current working directory. 5.4 Interface Using the keyword interface, you can fully abstract a class' interface from its implementation. That is, using interface, you can specify what a class must do, but not how it does it. Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body. In practice, this means that you can define interfaces which don't make assumptions about how they are implemented. Once it is defined, any number of classes can implement an interface. Also, one class can implement any number of interfaces. To implement an interface, a class must create the complete set of methods defined by the interface. However, each class is free to determine the details of its own implementation. By providing the interface keyword, Java allows you to fully utilize the "one interface, multiple methods" aspect of polymorphism. Interfaces are designed to support dynamic method resolution at run time. Normally, in order for a method to be called from one class to another, both classes need to be present at compile time so the Java compiler can check to ensure that the method signatures are compatible. This requirement by itself makes for a static and non-extensible classing environment. Inevitably in a system like this, functionality gets pushed up higher and higher in the class hierarchy so that the mechanisms will be available to more and more subclasses. Interfaces are designed to avoid this problem. They disconnect the definition of a method or set of methods from the inheritance hierarchy. Since interfaces are in a different hierarchy from classes, it is possible for classes that are unrelated in terms of the class hierarchy to implement the same interface. This is where the real power of interfaces is realized. Sikkim Manipal University - DDE Page No. 103 OOPS with Java Unit 5 Interfaces add most of the functionality that is required for many applications which would normally resort to using multiple inheritances in a language such as C++. 5.4.1 Defining an Interface An interface is defined much like a class. This is the general form of an interface: access interface name { return-type method-name1 (parameter-list); return-type method-name2(parameter-list); type final-varname1 = value; type final-varname2 = value; // ... return-type method-nameN (parameter-list); type final-varnameN = value; } Here, access is either public or not used. When no access specifier is included, then default access results, and the interface is only available to other members of the package in which it is declared. When it is declared as public, the interface can be used by any other code. name is the name of the interface, and can be any valid identifier. Notice that the methods which are declared have no bodies. They end with a semicolon after the parameter list. They are, essentially, abstract methods; there can be no default implementation of any method specified within an interface. Each class that includes an interface must implement all of the methods. Variables can be declared inside of interface declarations. They are implicitly final and static, meaning they cannot be changed by the implementing class. They must also be initialized with a constant value. All methods and variables are implicitly public if the interface, itself, is declared as public. Here is an example of an interface definition. It declares a simple interface which contains one method called callback ( ) that takes a single integer parameter. interface Callback { void callback (int param); } Sikkim Manipal University - DDE Page No. 104 OOPS with Java Unit 5 5.4.2 Some uses of interfaces Interfaces are a way of saying, “You need to plug some code in here for this thing to fully work “. The interfaces specify the exact signatures of the methods that must be provided. Use the interface type as a parameter for a method. Inside the method you can invoke any of the methods promised by the interface parameter. When you actually call the method, you will have to provide an object that has all the methods promised by the interface. It might help to think of this as a bit like passing in a subclass as an argument and having the correct overriding methods called. Interfaces can be used to mix in generally useful constants. So, for example, if an interface defines a set of constants, and then multiple classes use those constants, the values of those constants could be globally changed without having to modify multiple classes. That is interfaces separate design from implementation. 5.4.3 Interfaces versus Abstract Classes While an interface is used to specify the form that something must have, it does not actually provide the implementation for it. In this sense, an interface is a little like an abstract class that must be extended in exactly the manner that its abstract methods specify. An abstract class is an incomplete class that requires further specialization. An interface is just a specification or prescription for behavior. An interface does not have any overtones of specialization that are present with inheritance. A class can implement several interfaces at once, whereas a class can extend only one parent class. Interfaces can be used to support callbacks (inheritance does not help with this). This is a significant coding idiom. It essentially provides a pointer to a function, but in a type-safe way. Sikkim Manipal University - DDE Page No. 105 OOPS with Java Unit 5 Self Assessment Questions 11. __________ is the mechanism through which you can specify what a class must do, but not how it does it. 12. Variables declared inside the interface declarations are implicitly __________ and __________. 5.5 Summary In this unit, we have discussed the following: Identifying Relationships Relationships are of the following types: A Kind-Of relationship. A Is-A relationship. A Part-Of relationship. A Has-A relationship. Implementing Inheritance in Java The extends keyword is used to derive a class from a superclass, or in other words, extends the functionality of a superclass. Identifying and Applying Constraints An access specifier determines which features of a class (the class itself, the data members, and the methods) may be used by other classes. Java supports three access specifiers (also known as access modifiers). public. private. protected. Using final and abstract classes The abstract keyword The abstract keyword is used to declare classes that define common properties and behavior of other classes. An abstract is used as a base class to derive specific classes of the same kind. The final keyword A class can be declared as final if you do not want the class to be subclassed. Sikkim Manipal University - DDE Page No. 106 OOPS with Java Unit 5 5.6 Terminal Questions 1. What are the different types of relationships? 2. How do you implement inheritance in Java? 3. What are the rules for overriding a method in Java? 4. What are the uses of interfaces? 5. What are the differences between an interface and an abstract class? 5.7 Answers Self Assessment Questions 1. inheritance 2. superclass 3. subclass 4. part-of 5. public, private, protected 6. package 7. package 8. true 9. CLASSPATH 10. . (dot) 11. Interface 12. final, static Terminal Questions 1. A-Kind-Of, Is-A, Part-Of, Has-A. (Refer section 5.2.1) 2. public class <subclass_name> extends <superclass_name> { } (Refer section 5.2.4) 3. Rules for Overriding Methods The method name and the order of arguments should be identical to that of the superclass method. The return type of both the methods must be the same. Sikkim Manipal University - DDE Page No. 107 OOPS with Java Unit 5 The overriding method cannot be less accessible than the method it overrides. For example, if the method to override is declared as public in the superclass, you cannot override it with the private keyword in the subclass. An overriding method cannot raise more exceptions than those raised by the superclass. (Refer section 5.2.4) 4. Uses of Interfaces Interfaces can be used to mix in generally useful constants. If an interface defines a set of constants, and then multiple classes use those constants, the values of those constants could be globally changed without having to modify multiple classes. That is interfaces separate design from implementation. (Refer section 5.4.2) 5. Interface vs Abstract Class An abstract class is an incomplete class that requires further specialization. An interface is just a specification or prescription for behavior. An interface does not have any overtones of specialization that are present with inheritance. (Refer section 5.4.3) Sikkim Manipal University - DDE Page No. 108 OOPS with Java Unit 6 Unit 6 Exception Handling Structure 6.1 Introduction Objectives 6.2 Definition of an Exception 6.3 Exception Classes 6.4 Common Exceptions 6.5 Exception Handling Techniques 6.6 Summary 6.7 Terminal Questions 6.8 Answers 6.1 Introduction In the last unit, we have seen the implementation of inheritance, packages and interfaces in Java. In this unit, we will discuss about exception handling. Though it is the dream of every programmer to write error-free programs, normally it is not so. This is because the programmer does not anticipate all possible situations that might occur while running the program. The errors might be due to situations that might occur while running the program. The errors might be due to a programming mistake, bad input data, corrupt files or problems in physical devices. It is necessary to take care about these situations. The possible remedies could be Notify the user of an error. Save the work environment. Exiting from the program without adversely affecting the other programs in execution. This unit aims at providing information about handling situations occurring due to error or faulty conditions. This unit explains the mechanisms available in Java to handle such situations. The error or exception handling mechanisms in Java enables programmers to write more robust and secure codes. Java enforces the programmers to specify the exceptions that might occur while executing a method. Sikkim Manipal University - DDE Page No. 109 OOPS with Java Unit 6 Objectives After studying this unit, you should be able to: define Exception in Java list various Exception Classes describe some common exceptions in Java explain various exception handling techniques 6.2 Definition of an Exception The term exception denotes an exceptional event. It can be defined as an abnormal event that occurs during program execution and disrupts the normal flow of instruction. Error-handling becomes a necessity when you develop applications that need to take care of unexpected situations. The unexpected situations that may occur during program execution are: Running out of memory. Resource allocation errors. Inability to find a file. Problems in network connectivity. If an above-mentioned situation is encountered, a program may stop working. You cannot afford to have an application stop working or crashing, if the requested file is not present on the disk. Traditionally, programmers use return values of methods to detect the errors that has occurred at runtime. A variable errno was used for a numeric representation of the error. When multiple errors has occurred in a method, errno would have only one value-that of the last error that occurred in the method. Java handles exceptions in the object-oriented way. You can use a hierarchy of exception classes to manage runtime errors. Self Assessment Questions 1. The term exception denotes a/an ________. 2. Java handles exceptions in the ______________ way. 6.3 Exception Classes Sikkim Manipal University - DDE Page No. 110 OOPS with Java Unit 6 The class at the top of the exception classes hierarchy is Throwable class. Two classes are derived from the Throwable class - Error and Exception. The Exception class is used for the exceptional conditions that has to be trapped in a program. The Error class defines a condition that does not occur under normal circumstances. In other words, the Error class is used for catastrophic failures such as VirtualMachineError. These classes are available in the java.lang package. Self Assessment Questions 3. The class at the top of the exception classes hierarchy is _________. 4. ________ and __________ classes are derived from Throwable class. 5. Exception classes are available in ___________ package. 6.4 Common Exceptions Java has several predefined exceptions. The most common exceptions that you may encounter are described below. Arithmetic Exception This exception is thrown when an exceptional arithmetic condition has occurred. For example, a division by zero generates such an exception. NullPointer Exception This exception is thrown when an application attempts to use null where an object is required. An object that has not been allocated memory holds a null value. The situations in which an exception is thrown include: Using an object without allocating memory for it. Calling the methods of a null object. Accessing or modifying the attributes of a null object. ArrayIndexOutOfBounds Exception This exception is thrown when an attempt is made to access an array element beyond the index of the array. For example, if you try to access the eleventh element of an array that has only ten elements, the exception will be thrown. Self Assessment Questions 6. __________ exception will be thrown when you divide by zero. Sikkim Manipal University - DDE Page No. 111 OOPS with Java Unit 6 7. __________ exception will be thrown if you try to access the array element beyond its index value. 6.5 Exception Handling Techniques When an unexpected error occurs in a method, Java creates an object of the appropriate exception class. After creating the exception objects, Java passes it to the program, by an action called throwing an exception. The exception object contains information about the type of error and the state of the program when the exception occurred. You need to handle the exception using exception-handler and process the exception. You can implement exception-handling in your program by using following keywords: try catch finally The try Block You need to guard the statements that may throw an exception in the try block. The following skeletal code illustrates the use of the try block. try { // statement that may cause an exception } The try block governs the statements that are enclosed within it and defines the scope of the exception handlers associated with it. In other words, if an exception occurs within try block, the appropriate exception-handler that is associated with the try block handles the exception. A try block must have at least one catch block that follow it immediately. Nested try Statements The try statement can be nested. That is, a try statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement's catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or until the entire Sikkim Manipal University - DDE Page No. 112 OOPS with Java Unit 6 nested try statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception. Here is an example that uses nested try. Example: // An example of nested try statements. class NestTry { public static void main(String args[ ]) { try { int a = args.length; /* If no command-line args are present, the following statement will generate a divide-by-zero exception. */ int b = 42 / a; System.out.println("a = " + a); try { // nested try block /* If one command-line arg is used, then a divide-by-zero exception will be generated by the following code. */ if(a==1) a = a/(a-a); // division by zero /* If two command-line args are used, then generate an out-of-bounds exception. */ if(a==2) { int c[ ] = { 1 }; c[42] = 99; // generate an out-of-bounds exception } } catch(ArrayIndexOutOfBoundsException e) { } } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } Sikkim Manipal University - DDE Page No. 113 OOPS with Java Unit 6 } } As you can see, this program nests one try block within another. The program works as follows: When you execute the program with no command-line arguments, a divide-by zero exception is generated by the outer try block. Execution of the program by one command-line argument generates a divide-by-zero exception from within the nested try block. Since the inner block does not catch this exception, it is passed on to the outer try block, where it is handled. If you execute the program with two commandline arguments, an array boundary exception is generated from within the inner try block. Here are sample runs that illustrate each case: C:\\>java NestTry Divide by 0: java.lang.ArithmeticException: / by zero C:\\>java NestTry One a=1 Divide by 0: java.lang.ArithmeticException: / by zero C:\\>java NestTry One Two a=2 Array index out-of-bounds: java.lang.ArrayIndexOutOfBoundsException: 42 Nesting of try statements can occur in less obvious ways when method calls are involved. For example, you can enclose a call to a method within a try block. Inside that method is another try statement. In this case, the try within the method is still nested inside the outer try block, which calls the method. Here is the previous program recoded so that the nested try block is moved inside the method nesttry( ): /* Try statements can be implicitly nested via calls to methods. */ class MethNestTry { static void nesttry(int a) { try { // nested try block Sikkim Manipal University - DDE Page No. 114 OOPS with Java Unit 6 /* If one command-line arg is used, then a divide-by-zero exception will be generated by the following code. */ if(a==1) a = a/(a-a); // division by zero /* If two command-line args are used, then generate an out-of-bounds exception. */ if(a==2) { int c[ ] = { 1 }; c[42] = 99; // generate an out-of-bounds exception } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index out-of-bounds: " + e); } } public static void main(String args[ ]) { try { int a = args.length; /* If no command-line args are present, the following statement will generate a divide-by-zero exception. */ int b = 42 / a; System.out.println("a = " + a); nesttry(a); } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } } } The output of this program is identical to that of the preceding example. The catch Block Sikkim Manipal University - DDE Page No. 115 OOPS with Java Unit 6 You associate an exception-handler with the try block by providing one or more catch handlers immediately after try block. The following skeletal code illustrates the use of the catch block. try { //statements that may cause an exception } catch () { // error handling code } The catch statement takes an object of an exception class as a parameter. If an exception is thrown, the statements in the catch block are executed. The scope of the catch block is restricted to the statements in the preceding try block only. The finally Block When an exception is raised, the rest of the statements in the try block are ignored. Sometimes, it is necessary to process certain statements irrespective of whether an exception is raised or not. The finally block is used for this purpose. try { openFile(); writeFile(); //may cause an exception } catch (…) { //process the exception } In the above example, the file has to be closed irrespective of whether an exception is raised or not. You can place the code to close the file in both the try and catch blocks. To avoid duplication of code, you can place the code in the finally block. The code in the finally block is executed regardless of whether an exception is thrown or not. The finally block follows the catch Sikkim Manipal University - DDE Page No. 116 OOPS with Java Unit 6 blocks. You have only one finally block for an exception-handler. However, it is not mandatory to have a finally block. finally { closeFile (); } 6.6 Summary The term exception denotes an exceptional event. It can be defined as an abnormal event that occurs during program execution and disrupts the normal flow of instructions. The Exception class is used for the exceptional conditions that have to be trapped in a program. Java has several predefined exceptions. The most common exceptions that you may encounter are: Arithmetic Exception NullPointer Exception ArrayIndexOutOfBounds Exception The following keywords are used for exception-handlings: try catch finally If an exception occurs within the try block, the appropriate exception-handler that it associated with the try block handles the exception. You associate an exception-handler with the try block by providing one or more catch handlers immediately after the try block. Sometimes, it is necessary to process certain statements, no matter whether an exception is raised or not. The finally block is used for this purpose. 6.7 Terminal Questions 1. What is the difference between errors and exceptions? 2. What are the different types of Exception? 3. What are the different Exception handling techniques? Sikkim Manipal University - DDE Page No. 117 OOPS with Java Unit 6 6.8 Answers Self Assessment Questions 1. An exceptional event. 2. Object oriented. 3. Throwable. 4. Error and Exception. 5. java.lang 6. Arithmetic Exception. 7. ArrayIndexOutOfBounds. Terminal Questions 1. The term exception denotes an exceptional event. It can be defined as an abnormal event that occurs during program execution and disrupts the normal flow of instruction. (Refer section 6.2) 2. Arithmetic, NullPointer, ArrayIndexOutOfBounds. (Refer section 6.4) 3. try, catch, finally. (Refer section 6.5) Sikkim Manipal University - DDE Page No. 118 OOPS with Java Unit 7 Unit 7 Streams in Java Structure 7.1 Introduction Objectives 7.2 Streams Basics 7.3 The Abstract Streams 7.4 Stream Classes 7.5 Readers and Writers 7.6 Random Access Files 7.7 Serialization 7.8 Summary 7.9 Terminal Questions 7.10 Answers 7.1 Introduction In the last unit, we have discussed handling exceptions in Java. In this unit, we will discuss about various streams in Java. All programs accept input from the user, process it and produce an output. Therefore, all programming languages support input and output operations. Java provides support for input and output through the classes of the java.io package. Objectives After studying this unit, you will be able to: discuss streams basics explain abstract streams discuss various stream classes explain various Readers and Writers discuss Random Access Files explain the concept of Serialization 7.2 Streams Basics Java handles all input and output in the form of streams. A stream is a sequence of bytes traveling from a source to a destination over a communication path. If a program writes into a steam, it is the stream’s source. Similarly, if it is reading from a stream, it is the stream’s destination. Sikkim Manipal University - DDE Page No. 119 OOPS with Java Unit 7 Streams are powerful because they abstract the details of input/output (I/O) operations. The two basic streams used are the input and the output streams. Each stream has a particular functionality. You can only read from an input stream and conversely, you can only write to an output stream. Some streams are classified as mode streams because they read from or write to a specific place like a disk file or memory. Some streams are classified as filters. Filters are used to read data from one stream and write it to another stream. The two major classes for byte streams are InputStream and OutputStream. These abstract classes are sub-classed to provide a variety of I/O capabilities. The InputStream class lays the foundation for the input class hierarchy, whereas the OutputStream class lays the foundation for the output class hierarchy. The diagrams given below represent the hierarchy of the two streams. Figure 7.1: InputStream Class Hierarchy Sikkim Manipal University - DDE Page No. 120 OOPS with Java Unit 7 Figure 7.2: OutputStream Class Hierarchy JDK 1.1 introduces the Reader and the Writer classes for Unicode I/O. These classes support internationalization. The hierarchy of these classes is given below. Figure 7.3: Reader Class Hierarchy Sikkim Manipal University - DDE Page No. 121 OOPS with Java Unit 7 Figure 7.4: Writer Class Hierarchy Self Assessment Questions 1. Java handles all input and output in the form of ______________. 2. The two basic streams used are the _____ and the _____ streams. 3. _____ are used to read data from one stream and write it to another stream. 7.3 The Abstract Streams The methods available in InputStream class are shown in Table 7.1. Table 7.1: Methods of the InputStream Class Method Explanation int read () Reads a byte of data from the input stream. int read (byte [] b) Reads bytes of data from the input stream and stores them in the array. int read (byte [] b, int off, int len) Reads the number of bytes specified by the third argument from the input stream and stores it in the array. The second argument specifies the position from where the bytes have to be read. int available () Returns the number of bytes available for reading from the input stream. void close () Close an input stream and releases all the resources associated with it. Sikkim Manipal University - DDE Page No. 122 OOPS with Java Unit 7 Markable Streams Markable streams provide the capability of placing “bookmarks” on the stream and resetting it. This stream can then be read from the marked position. If a stream is marked, it must have some memory associated with it to keep track of the data between the mark and the current position of the stream. Table 7.2 shows the various markable stream methods and table 7.3 shows various methods available in OutputStream class. Table 7.2: Markable Stream Methods Method Explanation boolean markSupported () Returns true if the stream supports a bookmark. void mark (int readlimit ) Marks a position on the stream and identifies the number of bytes that can be read before the mark becomes invalid. void reset () Repositions the stream to its last marked position. long skip (long n) Skips a specific number of bytes in the stream. Table 7.3: Methods of the OutputStream Class Method Explanation void write (int n) Writes the specified byte of data to the output stream. void write (byte [] b ) Writes an array of bytes to the output stream. void write (byte [] b, int off, int len ) Writes a segment of an array to the output streams. void flush () Force writes whenever the data accumulates in the output stream. void close () Cause the output stream to close. Any data present on it is stored before the stream is de-allocated from the memory. Self Assessment Questions 4. __________ provide the capability of placing “bookmarks” on the stream and resetting it. 5. ______ method writes the specified byte of data to the output stream. Sikkim Manipal University - DDE Page No. 123 OOPS with Java Unit 7 7.3 Stream Classes Stream Classes are classified as FileInputStream, FileOutputStream, BufferedInputStream, BufferedOutputStream, DataInputStream, and DataOutputStream classes. The FileInputStream and FileOutputStream Classes These streams are classified as mode streams as they read and write data from disk files. The classes associated with these streams have constructors that allow you to specify the path of the file to which they are connected. The FileInputStream class allows you to read input from a file in the form of a stream. The FileOutputStream class allows you to write output to a file stream. Example: FileInputStream inputfile = new FileInputStream (“Employee.dat”); FileOutputStream outputfile = new FileOutputStream (“binus.dat”); The BufferedInputStream and BufferedOutputStream Classes The BufferedInputStream class creates and maintains a buffer for an input stream. This class is used to increase the efficiency of input operations. This is done by reading data from the stream one byte at a time. The BufferedOutputStream class creates and maintains a buffer for the output stream. Both the classes represent filter streams. The DataInputStream and DataOutputStream Classes The DataInputStream and DataOutputStream classes are the filter streams that allow the reading and writing of Java primitive data types. The DataInputStream class provides the capability to read primitive data types from an input stream. It implements the methods presents in the DataInput interface. Table 7.4: Methods of the DataInputStream class Method Explanation boolean readBoolean () Reads one byte and returns true if that byte is nonzero, false if it is zero. byte readByte () Reads a byte as an 8-bit signed value. char readChar () Reads a Unicode character. int readInt () Reads an integer value. Sikkim Manipal University - DDE Page No. 124 OOPS with Java Unit 7 The DataOutputStream class provides methods that are complementary to the methods of DataInputStream classes. It keeps track of the number of bytes written to the output stream. Table 7.5: Methods of the DataOutputStream Class Method Explanation void writeChar (int v ) Writes a character to the output stream. void writeLong (long v) Writes a long integer to the output stream. void writeInt (int v ) Writes an integer to the output stream. 7.3.4 The ByteArrayInputStream and ByteArrayOutputStream Classes These classes allow you to read and write an array of bytes. Table 7.6: Methods of ByteArrayInputStream Classes Method Explanation ByteArrayInputStream (byte [] b) Creates an input stream of the array of byes int size () Returns the total number of bytes written to the stream. Self Assessment Questions 6. _______ and ______ streams are classified as mode streams as they read and write data from disk files. 7. The _______ and ______ classes are the filter streams that allow the reading and writing of Java primitive data types. 7.4 Readers and Writers The subclasses of the input and output streams read and write data in the form of bytes. The Reader and Writer classes are abstract classes that support the reading and writing of Unicode character streams. Unicode is used to represents data such that each character is represented by 16 bits. Byte streams work on eight bits of data. These 16-bit version streams are called Reader and Writer. The most important subclasses of the Reader and Writer classes are InputStreamReader and OutputStreamWriter. These classes are used as interfaces between byte streams and character readers and writers. Sikkim Manipal University - DDE Page No. 125 OOPS with Java Unit 7 The Reader class supports InputStream class methods like read(), skip(), mark(), markSupported(), reset() and close(). The writer class supports methods of the OutputStream class like write(), flush() and close(). Reading from the Keyboard The InputStreamReader and OutputStreamReader classes are used to convert data between the byte and Unicode character streams. The InputStreamReader class converts an InputStream subclass object into Unicode character stream. The OutputStreamWriter class converts a Unicode character output stream into a byte output stream. Buffered character I/O is supported by the BufferedReader and BufferedWriter classes. The readLine() method of the BufferedReader class is used for reading lines of text from the console, the file, or other input streams. Figure 7.5: Example showing Reading from the keyboard In the above code, the InputStreamReader constructor takes an object of the InputStream class System.in as its parameter and constructs an InputStreamReader object called inputReader. Passing the InputStreamReader object as a parameter to the constructor of BufferedReader creates a BufferedReader object. The readLine() method of Sikkim Manipal University - DDE Page No. 126 OOPS with Java Unit 7 BufferedReader reads the line from the console. This line is then displayed as a message in the screen. You have to press Enter to terminate the program. Self Assessment Questions 8. The _____ and _____ classes are abstract classes that support the reading and writing of Unicode character streams. 9. Unicode is used to represent data such that each character is represented by _____. 10. The most important subclasses of the Reader and Writer classes are _____ and _____. 7.5 Random Access Files The term random access means that data can be read from or written to random locations within a file. In all the above mentioned streams, data is read and written as a continuous stream of information. Java provides the RandomAccessFile class to perform I/O operations at specified locations within a file. The RandomAccessFile class implements the DataInput and DataOutput interfaces for performing I/O using the primitive data types. The RandomAccessFile class also supports permissions like read and write, and allows files to be accessed in read-only and read-write modes. Creating a Random Access File There are two ways to create a random access file - using the pathname as a string or using an object of the File class. RandomAccessFile (String pathname, String mode); RandomAccessFile (File name, String mode); Example: randomFile = new RandomAccessFile (“iotets.txt”,”rw”); or File file1 = new File (“iotest.txt”); RandomAccessFile (file1, “rw”); Sikkim Manipal University - DDE randomFile = new RandomAccessFile Page No. 127 OOPS with Java Unit 7 The second argument is the mode argument that determines whether you have read-only or read/write (rw) access to the file. The RandomAccessFile class has several methods that allow random access to the content within the file. Table 7.7: Methods of RandomAccessFile Class Method Explanation void seek (long pos ) Sets the file pointer to a particular location inside the file. long getFilePointer () Return the current location of the file pointer. long length () Returns the length of the file, in bytes. 7.6 Serialization When you create a file using a text editor, it allows you to store the text to a file. The text stored in the file is the data encapsulated within the file object. This object is permanently available once you store it on the disk. The capability of an object to exist beyond the execution of the program that created is known as persistence. In the above example, the file object continues to exist even after the text editor stops executing. To make the file object persistent, you have to carry out an important step: saving the file. Saving the file object is called serialization. Serialization is the key to implement persistence. It provides the capability for you to write an object to a stream and read the object at a later stage. JDK 1.2 provides the Serializable interface in the java.io package to support object serialization. The process of reading an object and writing it to a file stream is very simple. The readObject() method of the ObjectInputStream class is used to read objects from the stream. The Objects that are read should be cast to the appropriate class names. Similarly, the writeObject() method of the ObjectOutputStream class writes objects to a stream. Self Assessment Questions 11. Java provides the _____ class to perform I/O operations at specified locations within a file. Sikkim Manipal University - DDE Page No. 128 OOPS with Java Unit 7 12. The RandomAccessFile class implements the _____and _____ interfaces. 13. The capability of an object to exist beyond the execution of the program that created is known as _____. 14. _____ is the key to implement persistence. 7.7 Summary The classes of the java.io package provide support for input and output operations in Java programs. A stream is a sequence of bytes traveling from a source to a destination over a communication path. InputStream and OutputStream are superclasses used for reading from and writing to byte streams. The Reader and Writer classes support I/O for Unicode character. The RandomAccessFile class supports random access operations in files. 7.8 Terminal Questions 1. What are the uses of a stream class? 2. What is the syntax of FileInputStream and FileOutputStream ? 3. What are the different DataOutputStream? methods under DataInputStream and 4. What are the uses of random access file over sequential access file? 7.9 Answers Self Assessment Questions 1. Streams. 2. Input, Output. 3. Filters. 4. Markable Streams. 5. void write(int n). 6. FileInputStream, FileOutputStream. 7. DataInputStream, DataOutputStream. 8. Reader, Writer. 9. 16 bits. Sikkim Manipal University - DDE Page No. 129 OOPS with Java 10. 11. 12. 13. 14. Unit 7 InputStreamReader, OutputStreamWriter. RandomAccessFile. DataInput, DataOutput. Persistence. Serialization. Terminal Questions 1. Streams are powerful because they abstract the details of input/output (I/O) operations. (Refer Section 7.1) 2. FileInputStream inputfile = new FileInputStream (“Employee.dat”); FileOutputStream outputfile = new FileOutputStream (“binus.dat”); (Refer Section 7.3) 3. Methods of the DataInputStream class Method Explanation boolean readBoolean () Reads one byte and returns true if that byte is nonzero, false if it is zero. byte readByte () Reads a byte as an 8-bit signed value. char readChar () Reads a Unicode character. int readInt () Reads an integer value. Methods of the DataOutputStream Class Method Explanation void writeChar (int v ) Writes a character to the output stream. void writeLong (long v) Writes a long integer to the output stream. void writeInt (int v ) Writes an integer to the output stream. (Refer section 7.3) 4. The term random access means that data can be read from or written to random locations within a file. (Refer Section 7.5) Sikkim Manipal University - DDE Page No. 130 OOPS with Java Unit 8 Unit 8 Applets Structure 8.1 Introduction Objectives 8.2 What are Applets? 8.3 The Applet Class 8.4 The Applet and HTML 8.5 Life Cycle of an Applet 8.6 The Graphics Class 8.7 Painting the Applet 8.8 User Interfaces for Applet 8.9 Adding Components to user interface 8.10 AWT (Abstract Windowing Toolkit) Controls 8.11 Summary 8.12 Terminal Questions 8.13 Answers 8.1 Introduction In the last unit, we have discussed various stream classes in Java. In this unit, we will discuss Java applets. Internet as of today has become an inseparable part of life used widely for accessing libraries, getting information on latest happenings, transferring information, sending email and communicating with others. Java programs written to run on World Wide Web (WWW) are called as applets. Since applets are run on different machines, security becomes a critical issue. Another probable disadvantage of applets would be the slight flickering that would be inevitable in animations but there is light at the end of the tunnel since a separate buffer can be used for the images which can then be superimpose on to the window or canvas. Objectives After studying this unit, you should be able to: explain applet and applet classes explain the Life Cycle of an applet discuss the Graphics class Sikkim Manipal University - DDE Page No. 131 OOPS with Java Unit 8 paint the applet create user interfaces for applets add components to user interfaces create AWT (Abstract Windowing Toolkit) controls 8.2 What are Applets? An applet is a Java program that can be embedded in a web page. Java applications are run by using a Java interpreter. Applets are run on any browser that supports Java. Applets can also be tested using the appletviewer tool included in the Java Development Kit. In order to run an applet it must be included in a web page, using HTML tags. When a user browses a web server and it runs applets on the user’s system. Applets have certain restrictions put on them. They can not read or write files on the user’s system. They can not load or run any programs stored on the user’s system. All applets are subclasses of the Applet class in the java.applet package. Applets do not have main() method. All applets must be declared public. An applet displays information on the screen by using the paint method. This method is available in java.awt.Component class. This method takes an instance of the class Graphics as parameter. The browser creates an instance of Graphics class and passes to the method paint(). Graphics class provides a method drawString to display text. It also requires a position to be specified as arguments. 8.3 The Applet Class The java.applet package is the smallest package in the Java API. The Applet class is the only class in the package. An applet is automatically loaded and executed when you open a web page that contains it. The Applet class has over 20 methods that are used to display images, play audio files, and respond when you interact with it. The applet runs in a web page that is loaded in a web browser. The environment of the applet is known as the context of the applet. You can retrieve the context using the getAppletContext() method. The life cycle of an applet is implemented using init(), start(), stop(), and destroy() methods. Sikkim Manipal University - DDE Page No. 132 OOPS with Java Unit 8 Use javac to compile applets and appletviewer to execute them. You can view applets in any browser that is Java-enabled. Self Assessment Questions 1. Java programs written to run on World Wide Web (WWW) are called _______. 2. Applets can be tested using the _______ tool included in the Java Development Kit. 8.4 The Applet and HTML The Applet tag is used to embed an applet in an HTML document. The Applet tag takes zero or more parameters. The Applet Tag The Applet tag is written in the body tag of an HTML document. Syntax: <APPLET CODE = “name of the class file that extends java.applet.Applet” CODEBASE = “path of the class file” HEIGHT = “maximum height of the applet, in pixels” WIDTH = “maximum width of the applet, in pixels” VSPACE = “vertical space between the applet and the rest of the HTML” HSPACE = “horizontal space between the applet and the rest of the HTML” ALIGN = “alignment of the applet with respect to the rest of the web page” ALT = “alternate text to be displayed if the browser does not support applets” > <PARAM NAME=“parameter_name” value=“value_of_parameter”> …….. </APPLET> The most commonly used attributes of the Applet tag are CODE, HEIGHT, WIDTH, CODEBASE and ALT. You can send parameters to the applet using the PARAM tag. The PARAM tag must be written between <APPLET> and </APPLET> Sikkim Manipal University - DDE Page No. 133 OOPS with Java Unit 8 Example: <applet Code = “clock. class” Height = 200 Width = 200 > </applet> 8.5 Life Cycle of an Applet You can describe the life cycle of an applet through four methods. These methods are: The init() method. The start() method. The stop() method. The destroy() method. The init() method The init() method is called the first time an applet is loaded into the memory of a computer. You can initialize variables, and add components like buttons and check boxes to the applet in the init() method. The start() method The start() method is called immediately after the init() method and every time the applet receives focus as a result of scrolling in the active window. You can use this method when you want to restart a process, such as thread animation. The stop() method The stop() method is called every time the applet loses the focus. You can use this method to reset variables and stop the threads that are running. The destroy() method The destroy() method is called by the browser when the user moves to another page. You can use this method to perform clean-up operations like closing a file. Sikkim Manipal University - DDE Page No. 134 OOPS with Java Unit 8 Figure 8.1: Diagram depicting the life cycle of an applet. It is not mandatory to use any or all the methods of the applet. These methods are called automatically by the Java environment, and hence, must be declared public. None of the methods accept parameters. Example: public void init() { } All but the most trivial applets override a set of methods that provides the basic mechanism by which the browser or appletviewer interfaces to the applet and controls its execution. Four of these methods—init(), start(), stop(), and destroy() – are defined by Applet. Another, paint() method, is defined by the AWT Component class. Default implementations for all of these methods are provided. Applets do not need to override those methods that they do not use. However, only very simple applets will not need to define all of them. These five methods can be assembled into the skeleton shown here: // An Applet skeleton. import java.awt.*; import java.applet.*; /* <applet code="AppletSkel" width=300 height=100> Sikkim Manipal University - DDE Page No. 135 OOPS with Java Unit 8 </applet> */ public class AppletSkel extends Applet { // Called first. public void init() { // initialization } /* Called second, after init(). Also called whenever the applet is restarted. */ public void start() { // start or resume execution } // Called when the applet is stopped. public void stop() { // suspends execution } /* Called when applet is terminated. This is the last method executed. */ public void destroy() { // perform shutdown activities Self Assessment Questions 3. The Applet tag is written in the _____ tag of an HTML document. 4. Parameters can be sent to the applet using _____ tag. 8.6 The Graphics Class The Graphics class is an abstract class that represents the display area of the applet. It is a part of the java.awt package. It is used for drawing on the applet’s display. The Graphics class provides methods to draw a number of graphical figure including Text Lines Sikkim Manipal University - DDE Page No. 136 OOPS with Java Unit 8 Circle and ellipse. Rectangle and polygons. Images. A few of the methods are given below. public abstract void drawString (String text, int x, int y) public abstract void drawLine (int x1, int y1, int x2, int y2) public abstract void drawRect (int x1, int y1, int width, int height) public abstract void fillRect (int x, int y1, int width, int height) public abstract void clearRect (int x, int y1, int width, int height) public abstract void draw3DRect (int x1, int y1, int width, int height, boolean raised) public abstract void drawRoundRect (int x1, int y1, int width, int height, int arcWidth, int arcHeight ) public abstract void fillRoundRect (int x1, int y1, int width, int height, int arcWidth, int arcHeight ) public abstract void drawOval (int x1, int y1, int width, int height) public abstract void fillOval (int x, int y1, int width, int height) You cannot create an object of the Graphics class since it is abstract. You can use the method getGraphics() to obtain an object of the class. 8.7 Painting the Applet When you scroll an applet, the screen has to be refreshed to show the new content. Windows handles this by marking the area (rectangle) that has to be refreshed. The area is then painted to display the result of scrolling. This is handled by the update() and paint() methods. The update() method The update() method takes a Graphics class object as a parameter. When the applet area needs to be redrawn, the Windows system starts the painting process. The update() method is called to clear the screen and calls the paint() method. The screen is then refreshed by the system. The paint() method The paint() method draws the graphics of the applet in the drawing area. The method is automatically called the first time the applet is displayed on Sikkim Manipal University - DDE Page No. 137 OOPS with Java Unit 8 the screen and every time the applet receives the focus. The paint() method can be triggered by invoking the repaint() method. The paint() method of the applet takes an object of the Graphics class as a parameter. Example: Figure 8.1: Coding (Step 1) Figure 8.2: Compiling and Executing (Step 2) Figure 8.3: Output (Step 3) Sikkim Manipal University - DDE Page No. 138 OOPS with Java Unit 8 The repaint() method You can call the repaint() method when you want the applet area to be redrawn. The repaint() method calls the update() method to signal that the applet has to be updated. The default action of the update () method is to clear the applet area and call the paint() method. You can override the update() method if you do not want the applet area to be cleared. The following program uses the paint() and repaint() methods to check when the init(), start(), and stop() methods of an applet are called. As a general rule, an applet writes to its window only when its update( ) or paint( ) method is called by the AWT. This raises an interesting question: How can the applet itself cause its window to be updated when its information changes? For example, if an applet is displaying a moving banner, what mechanism does the applet use to update the window each time this banner scrolls? Remember, one of the fundamental architectural constraints imposed on an applet is that it must quickly return control to the AWT run-time system. It cannot create a loop inside paint( ) that repeatedly scrolls the banner, for example. This would prevent control from passing back to the AWT. Given this constraint, it may seem that output to your applet's window will be difficult at best. Fortunately, this is not the case. Whenever your applet needs to update the information displayed in its window, it simply calls repaint( ). The repaint( ) method is defined by the AWT. It causes the AWT run-time system to execute a call to your applet's update( ) method, which, in its default implementation, calls paint( ). Thus, for another part of your applet to output to its window, simply store the output and then call repaint( ). The AWT will then execute a call to paint( ), which can display the stored information. For example, if part of your applet needs to output a string, it can store this string in a String variable and then call repaint( ). Inside paint( ), you will output the string using drawString( ). The repaint( ) method has four forms. Let's look at each one, in turn. The simplest version of repaint( ) is shown here: void repaint( ); This version causes the entire window to be repainted. The following version specifies a region that will be repainted: void repaint(int left, int top, int width, int height); Sikkim Manipal University - DDE Page No. 139 OOPS with Java Unit 8 import java.awt.*; import java.applet.*; /* <applet code="Test" height=300 width=300> </applet> */ public class Test extends Applet { int initcounter=0; int startcounter=0; int stopcounter=0; int destroycounter=0; public void init() { initcounter++; repaint (); } public void start() { startcounter++; repaint (); } public void stop() { stopcounter++; repaint (); } public void destroy() { destroycounter++; repaint (); } public void paint (Graphics g) { g.drawString ("init has been invoked " + String.valueOf(initcounter) +"times",20,20); g.drawString ("start has been invoked " + String.valueOf(startcounter) +"times",20,35); Sikkim Manipal University - DDE Page No. 140 OOPS with Java Unit 8 g.drawString ("stop has been invoked " + String.valueOf(stopcounter) +"times",20,50); g.drawString ("destroy has been invoked " + String.valueOf(destroycounter) +"times",20,65); } } Self Assessment Questions 5. The Graphics class is a part of _____ package. 6. The _____ method draws the graphics of the applet in the drawing area. 8.8 User Interfaces for Applet The Abstract Windowing Toolkit, also called as AWT is a set of classes, enabling the user to create a user friendly, Graphical User Interface (GUI). It will also facilitate receiving user input from the mouse and keyboard. The AWT classes are part of the java.awt package. The user interface consists of the following three: Components – Anything that can be put on the user interface. This includes buttons, check boxes, pop-up menus, text fields, etc. Containers – This is a component that can contain other components. Layout Manager – These define how the components will be arranged in a container. The statement import java.awt.*; imports all the components, containers and layout managers necessary for designing the user interface. The AWT supplies the following components. Labels (java.awt.Label) Buttons (java.awt.Button) Checkboxes (java.awt.Checkbox) Single- line text field (java.awt.TextField) Larger text display and editing areas (java.awt.TextArea) Pop-up lists of choices (java.awt.Choice) Lists (java.awt.List) Sliders and scrollbars (java.awt.Scrollbar ) Drawing areas (java.awt.Canvas) Menus (java.awt.Menu, java.awt.MenuItem, java.awt.CheckboxMenuItem ) Containers (java.awt.Panel, java.awt.Window and its subclasses) Sikkim Manipal University - DDE Page No. 141 OOPS with Java Unit 8 8.9 Adding Components to user interface Because all applets are containers, components can be added directly to the applet windows. The following steps add a component: Create the component by creating an object of that class. Call the Container’s adds method to add the component. Labels Labels display non editable text. To create a label use one of the following: label() – Creates an empty label. label(String) – Creates a label with the given string. label(String, int ) – Creates a label with the given string and right, left or center alignment. Buttons Clickable buttons can be created from the Button class. You can create a button by using either of the following: Button() – Creates a button without any label. Use setLabel(String) to display a text on the button. Button(String) – Creates a button with the given string as the label. Checkboxes They are labeled or unlabeled boxes that can be either checked off or empty. They are used for selecting some option. Use one of the following to create them. Checkbox() – Creates a checkbox without any label. Checkbox(String) – Creates a labeled checkbox. When many checkboxes are there any number of them can be checked or unchecked. Checkboxes can be organized into groups so that only one of them can be checked at a time. The following statements a checkbox group: CheckboxGroup mygroup = new CheckboxGroup(); To create a checkbox, belonging to this group, use the following statement. Checkbox c1 = new Checkbox (―Manipal‖, mygroup, true); Sikkim Manipal University - DDE Page No. 142 OOPS with Java Unit 8 Figure 8.4: Program that creates label, checkbox and buttons. TextFields TextField is an editable component. Text field can be created by using one of the following: TextField() – Creates an empty text field. TextField(String) – Creates a text field with the specified string. TextField(String, int ) – Creates a text field with the specified String and specified width. The TextField class has several useful methods: The getText() method returns the text in the field. The setText(String) method fills the field with the string. The setEditable(boolean) methods decides whether the filed should be editable or not depending upon the Boolean value. The isEditable() method returns a Boolean value indicating whether the field is editable or not. Text Areas These are editable text fields having more than one line of input. Use one of the following to create a text area. TextArea() – Creates an empty text area. TextArea(rows, character) – Creates a text area of rows specified and width to accommodate the character specified. TextArea(String) TextArea(String, rows, character) Sikkim Manipal University - DDE Page No. 143 OOPS with Java Unit 8 The methods available in case of Text field can also be used here. In addition to that the following methods could be used: The insert(String, charindex) method inserts the indicated string at the position indicated by the second argument. The replace(string, startpos, endpos) method replaces the text between the given integer positions with the indicated string. Figure 8.5: Example showing the use of TextField and TextArea. 8.10 AWT Controls Following AWT (Abstract Windowing Toolkit) controls are available in Java. Table 8.1: Various AWT Controls GUI Category Control AWT Class Name Basic Controls Button Combo box List Menu Slider Toolbar Text Field Button ComboBox List Menu, MenuBar, MenuItem Slider Toolbar TextField, PasswordField, TextArea Uneditable Display Label Tooltip Progress bar Label ToolTip ProgressBar Sikkim Manipal University - DDE Page No. 144 OOPS with Java Unit 8 Editable Display Table Text Tree Color chooser File chooser Table TextPane, TextArea Tree ColorChooser FileChooser Space-Saving Containers Scroll pane Split pane Tabbed pane ScrollPane, ScrollBar SplitPane TabbedPane Top-Level Containers Frame Applet Dialog Frame Applet Dialog Self Assessment Questions 7. AWT stands for _____. 8. _____ defines how the components will be arranged in a container. 8.11 Summary The Applet class is the only class of the java.applet package. An applet runs in a Webpage. An applet can be executed using the appletviewer or a Java-enabled browser. The Applet tag is used to embed an applet in a Web page. The init() method is called the first time the applet is loaded into the memory of a computer. The start() method is called immediately after the init() method and every time the applet receives focus as a result of scrolling in the active window. The stop() method is called every time the user moves on to another web page. The destroy() method is called just before the browser is shut down. You can use the method getGraphics() to obtain an object of the Graphics class. The update() method clears the screen and calls the paint() method. The paint() method draws the graphics of the applet in the drawing area. Sikkim Manipal University - DDE Page No. 145 OOPS with Java Unit 8 The repaint() method calls the update() method to signal that the applet’s redrawn in the drawing area. 8.12 Terminal Questions 1. What are the restrictions on an applet? 2. What is the life cycle of an applet class? 3. What is AWT? 4. What are the components available in AWT? 8.13 Answers Self Assessment Questions 1. applets. 2. appletviewer. 3. body 4. PARAM 5. java.awt 6. paint() 7. Abstract Windowing Toolkit 8. Layout Manager Terminal Questions 1. Since applets are run on different machines, security becomes a critical issue. Another probable disadvantage of applets would be the slight flickering that would be inevitable in animations. (Refer Section 8.1) 2. The life cycle of an applet can be described through four methods viz. init(), start(), stop() and destroy(). (Refer Section 8.5) 3. AWT (Abstract Windowing Toolkit) is a set of classes, enabling the user to create a user friendly, Graphical User Interface. (Refer Section 8.8) 4. Label, Button, Checkbox, TextField, Choice, List etc. are various components available in AWT. (Refer Section 8.8) Sikkim Manipal University - DDE Page No. 146 OOPS with Java Unit 9 Unit 9 Event Handling Structure 9.1 Introduction Objectives 9.2 Components of an Event 9.3 Event Classes 9.4 Event Listener 9.5 Event-Handling 9.6 Adapter Classes 9.7 Inner Classes 9.8 Anonymous Classes 9.9 Summary 9.10 Terminal Questions 9.11 Answers 9.1 Introduction In the last unit, we have discussed Java applets. In this unit, we shall discuss event handling in Java. Event-handling is essential to GUI programming. In event handling, the program waits for the user to perform some action. The user controls the sequence of operations that the application executes through a GUI. This approach is also called eventdriven programming. Figure 9.1: Flow of Event Sikkim Manipal University - DDE Page No. 147 OOPS with Java Unit 9 Objectives: After studying this unit, you should be able to: explain components of an event describe various event classes explain event listener handle events describe adapter classes and inner classes explain anonymous classes 9.2 Components of an Event An event comprises of three components: Event Object – When the user interacts with the application by pressing a key or clicking a mouse button, an event is generated. The operating system traps this event and the data associated with it, for example, the time at which the event occurred, the event type (like a keypress or a mouseclick). This data is then passed on to the application to which the event belongs. In Java, events are represented by objects that describe the events themselves. Java has a number of classes that describe and handle different categories of event. Event Source – An event source is an object that generates an event. For example, if you click on a button, an ActionEvent object is generated. The object of the ActionEvent class contains information about the event. Event-handler – An event-handler is a method that understands the event and processes it. The event-handler method takes an event object as a parameter. 9.3 Event Classes The EventObject class is at the top of the event class hierarchy. It belongs to the java.util package. Most other event classes are present in the java.awt.event package. The hierarchy of the event classes is shown below. The java.util.EventObject and the java.awt.AWTEvent classes do not belong to the java.awt.event package. The hierarchy of the JDK 1.2 event classes is given below. Sikkim Manipal University - DDE Page No. 148 OOPS with Java Unit 9 Figure 9.2: Hierarchy of the JDK 1.2 event classes The getSource() method of the EventObject class returns the object that initiated the event. The getID() method returns the event ID that represents the nature of the event. For example, if a mouse event occurs, you can find out whether the event was a click, a drag, a move, a press, or a release from the event object. Let us see when various events are generated: An ActionEvent object is generated when a component is activated. An AdjustmentEvent object is generated when scrollbars and other adjustable elements are used. A ContainerEvent object is generated when components are added to or removed from a container. A FocusEvent object is generated when a component receives focus for input. An ItemEvent object is generated when an item from a list, a choice, or a check box is selected. A KeyEvent object is generated when a key on the keyboard is pressed. A MouseEvent object is generated when the mouse is used. A PaintEvent object is generated when a component is painted. A TextEvent object is generated when the text of a text component is modified. Sikkim Manipal University - DDE Page No. 149 OOPS with Java Unit 9 9.4 Event Listener An object delegates the task of handling an event to the event listener. When an event occurs, an event object of the appropriate type (as given above) is created. This object is passed to the listener. A listener must implement the interface that has the method for event-handling. A component can have multiple listeners. A listener can be removed using the removeActionListener() method. Figure 9.3: Example showing ActionListener implementation Self Assessment Questions 1. When the user interacts with the application by pressing a key or clicking a mouse button, an _____ is generated. 2. The _____ class is at the top of the event class hierarchy. 9.5 Event-Handling When an event occurs, it is sent to the component from where the event originated. The component registers a listener, which contains eventhandler. Event-handler receives and process events. Sikkim Manipal University - DDE Page No. 150 OOPS with Java Unit 9 Figure 9.4: Event handling in Java Every event has a corresponding listener interface that specifies the methods that are required to handle the event. Event objects report to the registered listeners. To enable a component to handle events, you must register an appropriate listener for the component. Figure 9.5: Example showing Frame class ButtonListener implements ActionListener { public void actionPerformed (ActionEvent evt) { Button source = (Button)evt.getSource(); Source.setLable (“Button clicked’’); { } Sikkim Manipal University - DDE Page No. 151 OOPS with Java Unit 9 How does the above application work? The execution begins with the main() method. An object of the MYFrame class is created in the main() method. The constructor of the MYFrame class is called. The super() method calls the constructor of the base class (Frame) and sets the title of the window. A button object is created and placed at the center of the window. A listener object is created. The addActionListener() method registers the listener object for the button. The application waits for the user to interact with it. When the user clicks on the button: The ActionEvent event is generated. An ActionEvent object is created and is delegated to the registered listener object for processing. The listener object contains the actionPerformed() method, which processes the ActionEvent. In the actionPerformed() method, the reference to the event source is retrieved using the getSource() method. Finally, the label of the button is changed using the setLabel() method. The ActionEvent Class An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu item is selected. The ActionEvent class defines four integer constants that can be used to identify any modifiers associated with an action event: ALT_MASK, CTRL_MASK, META_MASK, and SHIFT_MASK. In addition, there is an integer constant, ACTION_PERFORMED, which can be used to identify action events. ActionEvent has these two constructors: ActionEvent(Object src, int type, String cmd) ActionEvent(Object src, int type, String cmd, int modifiers) Here, src is a reference to the object that generated this event. The type of the event is specified by type, and its command string is cmd. The argument Sikkim Manipal University - DDE Page No. 152 OOPS with Java Unit 9 modifiers indicates which modifier keys (ALT, CTRL, META, and/or SHIFT) were pressed when the event was generated. You can obtain the command name for the invoking ActionEvent object by using the getActionCommand( ) method, shown here: String getActionCommand( ) For example, when a button is pressed, an action event is generated that has a command name equal to the label on that button. The getModifiers( ) method returns a value that indicates which modifier keys (ALT, CTRL, META, and/or SHIFT) were pressed when the event was generated. Its form is shown here: int getModifiers( ) The AdjustmentEvent Class An AdjustmentEvent is generated by a scroll bar. There are five types of adjustment events. The AdjustmentEvent class defines integer constants that can be used to identify them. The constants and their meanings are shown here: BLOCK_DECREMENT: The user clicked inside the scroll bar to decrease its value. BLOCK_INCREMENT: The user clicked inside the scroll bar to increase its value. TRACK: The slider was dragged. UNIT_DECREMENT: The button at the end of the scroll bar was clicked to decrease its value. UNIT_INCREMENT: The button at the end of the scroll bar was clicked to increase its value. In addition, there is an integer constant, ADJUSTMENT_VALUE_ CHANGED, that indicates that a change has occurred. AdjustmentEvent has this constructor: AdjustmentEvent(Adjustable src, int id, int type, int data) Sikkim Manipal University - DDE Page No. 153 OOPS with Java Unit 9 Here, src is a reference to the object that generated this event. The id equals ADJUSTMENT_VALUE_CHANGED. The type of the event is specified by type, and its associated data is data. The getAdjustable( ) method returns the object that generated the event. Its form is shown here: Adjustable getAdjustable( ) The type of the adjustment event may be obtained by the getAdjustmentType( ) method. It returns one of the constants defined by AdjustmentEvent. The general form is shown here: int getAdjustmentType( ) The amount of the adjustment can be obtained from the getValue( ) method, shown here: int getValue( ) For example, when a scroll bar is manipulated, this method returns the value represented by that change. The ComponentEvent Class A ComponentEvent is generated when the size, position, or visibility of a component is changed. There are four types of component events. The ComponentEvent class defines integer constants that can be used to identify them. The constants and their meanings are shown here: COMPONENT_HIDDEN: The component was hidden. COMPONENT_MOVED: The component was moved. COMPONENT_RESIZED: The component was resized. COMPONENT_SHOWN: The component became visible. ComponentEvent has this constructor: ComponentEvent(Component src, int type) Here, src is a reference to the object that generated this event. The type of the event is specified by type. ComponentEvent is the superclass either directly or indirectly of ContainerEvent, Sikkim Manipal University - DDE Page No. 154 OOPS with Java Unit 9 FocusEvent, KeyEvent, MouseEvent, and WindowEvent. The getComponent( ) method returns the component that generated the event. It is shown here: Component getComponent( ) The ContainerEvent Class A ContainerEvent is generated when a component is added to or removed from a container. There are two types of container events. The ContainerEvent class defines int constants that can be used to identify them: COMPONENT_ADDED and COMPONENT_REMOVED. They indicate that a component has been added to or removed from the container. ContainerEvent is a subclass of ComponentEvent and has this constructor: ContainerEvent(Component src, int type, Component comp) Here, src is a reference to the container that generated this event. The type of the event is specified by type, and the component that has been added to or removed from the container is comp. You can obtain a reference to the container that generated this event by using the getContainer( ) method, shown here: Container getContainer( ) The getChild( ) method returns a reference to the component that was added to or removed from the container. Its general form is shown here: Component getChild( ) The FocusEvent Class A FocusEvent is generated when a component gains or loses input focus. These events are identified by the integer constants FOCUS_GAINED and FOCUS_LOST. FocusEvent is constructors: a subclass of ComponentEvent and has these FocusEvent(Component src, int type) FocusEvent(Component src, int type, boolean temporaryFlag) Sikkim Manipal University - DDE Page No. 155 OOPS with Java Unit 9 Here, src is a reference to the component that generated this event. The type of the event is specified by type. The argument temporaryFlag is set to true if the focus event is temporary. Otherwise, it is set to false. (A temporary focus event occurs as a result of another user interface operation. For example, assume that the focus is in a text field. If the user moves the mouse to adjust a scroll bar, the focus is temporarily lost.) The isTemporary( ) method indicates if this focus change is temporary. Its form is shown here: boolean isTemporary( ) The method returns true if the change is temporary. Otherwise, it returns false. The InputEvent Class The abstract class InputEvent is a subclass of ComponentEvent and is the superclass for component input events. Its subclasses are KeyEvent and MouseEvent. The InputEvent class defines the following eight integer constants that can be used to obtain information about any modifiers associated with this event: ALT_MASK BUTTON1_MASK META_MASK ALT_GRAPH_MASK BUTTON2_MASK SHIFT_MASK BUTTON3_MASK CTRL_MASK The isAltDown( ), isAltGraphDown( ), isControlDown( ), isMetaDown( ), and isShiftDown( ) methods test if these modifiers were pressed at the time this event was generated. The forms of these methods are shown here: boolean isAltDown( ) boolean isAltGraphDown( ) Sikkim Manipal University - DDE Page No. 156 OOPS with Java Unit 9 boolean isControlDown( ) boolean isMetaDown( ) boolean isShiftDown( ) The getModifiers( ) method returns a value that contains all the modifier flags for this event. Its signature is shown here: int getModifiers( ) The ItemEvent Class An ItemEvent is generated when a check box or a list item is clicked or when a checkable menu item is selected or deselected. (Check boxes and list boxes are described later in this book.) There are two types of item events, which are identified by the following integer constants: DESELECTED The user deselected an item. SELECTED The user selected an item. In addition, ItemEvent defines one integer ITEM_STATE_CHANGED that signifies a change of state. constant, ItemEvent has this constructor: ItemEvent(ItemSelectable src, int type, Object entry, int state) Here, src is a reference to the component that generated this event. For example, this might be a list or choice element. The type of the event is specified by type. The specific item that generated the item event is passed in entry. The current state of that item is in state. The getItem( ) method can be used to obtain a reference to the item that generated an event. Its signature is shown here: Object getItem( ) The getItemSelectable( ) method can be used to obtain a reference to the ItemSelectable object that generated an event. Its general form is shown here: Sikkim Manipal University - DDE Page No. 157 OOPS with Java Unit 9 ItemSelectable getItemSelectable( ) Lists and choices are examples of user interface elements that implement the ItemSelectable interface. The getStateChange( ) method returns the state change (i.e., SELECTED or DESELECTED) for the event. It is shown here: int getStateChange( ) The KeyEvent Class A KeyEvent is generated when keyboard input occurs. There are three types of key events, which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED. The first two events are generated when any key is pressed or released. The last event occurs only when a character is generated. Remember, not all key presses result in characters. For example, pressing the SHIFT key does not generate a character. There are many other integer constants that are defined by KeyEvent. For example, VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the numbers and letters. Here are some others: VK_ENTER VK_ESCAPE VK_CANCEL VK_UP VK_DOWN VK_LEFT VK_RIGHT VK_PAGE_DOWN VK_PAGE_UP VK_SHIFT VK_ALT VK_CONTROL Sikkim Manipal University - DDE Page No. 158 OOPS with Java Unit 9 The VK constants specify virtual key codes and are independent of any modifiers, such as control, shift, or alt. KeyEvent is a subclass of InputEvent and has these two constructors: KeyEvent(Component src, int type, long when, int modifiers, int code) KeyEvent(Component src, int type, long when, int modifiers, int code, char ch) Here, src is a reference to the component that generated the event. The type of the event is specified by type. The system time at which the key was pressed is passed in when. The modifiers argument indicates which modifiers were pressed when this key event occurred. The virtual key code, such as VK_UP, VK_A, and so forth, is passed in code. The character equivalent (if one exists) is passed in ch. If no valid character exists, then ch contains CHAR_UNDEFINED. For KEY_TYPED events, code will contain VK_UNDEFINED. The KeyEvent class defines several methods, but the most commonly used ones are getKeyChar( ), which returns the character that was entered, and getKeyCode( ), which returns the key code. Their general forms are shown here: char getKeyChar( ) int getKeyCode( ) If no valid character is available, then getKeyChar() returns CHAR_UNDEFINED. When a KEY_TYPED event occurs, getKeyCode( ) returns VK_UNDEFINED. The MouseEvent Class There are seven types of mouse events. The MouseEvent class defines the following integer constants that can be used to identify them: MOUSE_CLICKED: The user clicked the mouse. MOUSE_DRAGGED: The user dragged the mouse. MOUSE_ENTERED: The mouse entered a component. MOUSE_EXITED: The mouse exited from a component. MOUSE_MOVED: The mouse moved. Sikkim Manipal University - DDE Page No. 159 OOPS with Java Unit 9 MOUSE_PRESSED: The mouse was pressed. MOUSE_RELEASED: The mouse was released. MouseEvent is a subclass of InputEvent and has this constructor: MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggersPopup) Here, src is a reference to the component that generated the event. The type of the event is specified by type. The system time at which the mouse event occurred is passed in when. The modifiers argument indicates which modifiers were pressed when a mouse event occurred. The coordinates of the mouse are passed in x and y. The click count is passed in clicks. The triggersPopup flag indicates if this event causes a pop-up menu to appear on this platform. The most commonly used methods in this class are getX( ) and getY( ). These return the X and Y coordinates of the mouse when the event occurred. Their forms are shown here: int getX( ) int getY( ) Alternatively, you can use the getPoint( ) method to obtain the coordinates of the mouse. It is shown here: Point getPoint( ) It returns a Point object that contains the X, Y coordinates in its integer members: x and y. The translatePoint( ) method changes the location of the event. Its form is shown here: void translatePoint(int x, int y) The getClickCount( ) method obtains the number of mouse clicks for this event. Its signature is shown here: int getClickCount( ) The isPopupTrigger( ) method tests if this event causes a pop-up menu to appear on this platform. Its form is shown here: Sikkim Manipal University - DDE Page No. 160 OOPS with Java Unit 9 boolean isPopupTrigger( ) The TextEvent Class Instances of this class describe text events. These are generated by text fields and text areas when characters are entered by a user or program. TextEvent defines the integer constant TEXT_VALUE_CHANGED. The one constructor for this class is shown here: TextEvent(Object src, int type) Here, src is a reference to the object that generated this event. The type of the event is specified by type. The TextEvent object does not include the characters currently in the text component that generated the event. Instead, your program must use other methods associated with the text component to retrieve that information. This operation differs from other event objects discussed in this section. For this reason, no methods are discussed here for the TextEvent class. Think of a text event notification as a signal to a listener that it should retrieve information from a specific text component. The WindowEvent Class There are seven types of window events. The WindowEvent class defines integer constants that can be used to identify them. The constants and their meanings are shown here: WINDOW_ACTIVATED: The window was activated. WINDOW_CLOSED: The window has been closed. WINDOW_CLOSING: The user requested that the window be closed. WINDOW_DEACTIVATED: The window was deactivated. WINDOW_DEICONIFIED: The window was deiconified. WINDOW_ICONIFIED: The window was iconified. WINDOW_OPENED: The window was opened. WindowEvent is a subclass of ComponentEvent and has this constructor: WindowEvent(Window src, int type) Sikkim Manipal University - DDE Page No. 161 OOPS with Java Unit 9 Here, src is a reference to the object that generated this event. The type of the event is type. The most commonly used method in this class is getWindow( ). It returns the Window object that generated the event. Its general form is shown here: Window getWindow( ) Self Assessment Questions 3. When the user clicks on the button, the _____ event is generated. 4. An _____ event is generated by a scroll bar. 9.6 Adapter Classes The Java programming language provides adapter classes that implement the corresponding listener interfaces containing more than one method. The methods in these classes are empty. The listener class that you define can extend the Adapter class and override the methods that you need. The Adapter class is used for the WindowListener interface in the WindowAdapter class. You can rewrite the previous code in the following manner. Figure 9.6: Example showing alternate code for Frame Sikkim Manipal University - DDE Page No. 162 OOPS with Java Unit 9 The following is a list of Adapter classes and listener interfaces: Table 9.1: List of Adapter classes and listener interfaces Event Category Window Interface Name WindowListener Adapter Name Method WindowAdapter void windowClosing (WindowEvent e) void windowOpening (WindowEvent e) void windowActivated (WindowEvent e) void windowDeactivated (WindowEvent e) void windowClosed (WindowEvent e) void windowIconified (WindowEvent e) void windowDeiconified (WindowEvent e) Action ActionListenr void actionPerformed (ActionEvent e ) Item ItemListener void itemStateChanged (ItemEvent e) Mouse Motion MouseMotion Listener MouseMotion Adapter Mouse Button MouseListener MouseAdapter void mousePressed (MouseEvent e) void mouseDragged (MouseEvent e) void mouseMoved (MouseEvent e) void mouseReleased (MouseEvent e) void mouseEntered (MouseEvent e) void mouseExited (MouseEvent e) void mouseClicked (MouseEvent e) Key KeyListener KeyAdapter void keyPressed (KeyEvent e) void keyReleased (KeyEvent e) void keyTyped (KeyEvent e) Focus FocusListener void focusGained (FocusEvent e) void focusLost (FocusEvent e) Component ComponentListener Component Adapter void componentMoved (ComponentEvent e) void componentResized (ComponentEvent e) void componentHidden (ComponentEvent e) void componentShown (ComponentEvent e) Sikkim Manipal University - DDE Page No. 163 OOPS with Java Unit 9 9.7 Inner Classes Inner classes are classes that are declared within other classes. They are also known as nested classes and provide additional clarity to programs. The scope of an inner class is limited to the class that encloses it. The objects of the inner class can access the members of the outer class. The outer class can access the members of the inner class through an object of the inner class. Syntax: <modifiers> class <classname> { <modifiers> class <innerclassname> { } // other attributes and methods } 9.8 Anonymous Classes Sometimes, the classes that you declare in a method do not need a name since you do not need them anywhere else in the program. You can create nameless classes for this purpose. Classes that are not named are called anonymous classes. Example: public void methodOne () { OKButton.addActionListener (new ActionListener () { public void actionPerformed (ActionEvent action) { //process event } } ); Sikkim Manipal University - DDE Page No. 164 OOPS with Java Unit 9 In the above code, the class declaration is the argument of the addActionListener() method. You cannot instantiate an object of the anonymous class elsewhere in the code. An anonymous class cannot have a constructor as the class does not have a name. An anonymous class can be a subclass of another class. It can implement an interface. Self Assessment Questions 5. An _____ event is generated when an item from a list, a choice, or a check box is selected. 9.9 Summary The components of an event are: Event Object Event Source Event Handler To handle window-related events, you need to register the listener object that implements the WindowListener interface. Inner classes, also called nested classes, are classes that are declared within other classes. The classes that are not named within a program are called anonymous classes. An anonymous class cannot have a constructor as the class has no name. 9.10 Terminal Questions 1. What are the different components of an event? 2. What are the uses of an adapter class? 3. What are Inner Classes? Sikkim Manipal University - DDE Page No. 165 OOPS with Java Unit 9 9.11 Answers Self Assessment Questions 1. event 2. EventObject 3. ActiionEvent 4. AdjustmentEvent 5. ItemEvent. Terminal Questions 1. Event Object, Event Source and Event Handler. (Refer Section 9.2) 2. The listener class that you define can extend the Adapter class and override the methods that you need. (Refer Section 9.6) 3. Inner classes are classes that are declared within other classes. They are also known as nested classes and provide additional clarity to programs. (Refer Section 9.5) Sikkim Manipal University - DDE Page No. 166 OOPS with Java Unit 10 Unit 10 Java Data Base Connectivity (JDBC) Structure 10.1 Introduction Objectives 10.2 Java Data Base Connectivity 10.3 Database Management 10.4 Mechanism for connecting to a back end database 10.5 Loading the ODBC driver 10.6 Summary 10.7 Terminal Questions 10.8 Answers 10.1 Introduction In the last unit, we have discussed various event handling mechanisms in Java. In this unit, we shall discuss the database handling mechanisms in Java using Java Data Base Connectivity Application Program Interface (JDBC API). Objectives After studying this unit, you should be able to: describe JDBC concepts manage databases in Java explain the mechanism for connecting to a back end database load the ODBC driver 10.2 Java Data Base Connectivity (JDBC) The JDBC API (Java Data Base Connectivity Application Program Interface) can access any kind of tabular data, especially data stored in a Relational Database. It works on top of ODBC (Open Data Base Connectivity) which was the driver for database connectivity since age old days but since ODBC was implemented in C so people from the VB background had some problems in understanding the implementation intricacies. Since JDBC works on top of ODBC we have something called as a JDBC-ODBC bridge to access the database. JDBC helps you to write Sikkim Manipal University - DDE Page No. 167 OOPS with Java Unit 10 Java applications that manage mainly three programming activities listed below namely: a) connecting to a data source, like a database, b) sending queries and updating statements to the database and c) retrieving and processing the results received from the database in answer to your query 10.3 Database Management A database is a collection of related information and a Data Base Management System (DBMS) is the software that provides you with a mechanism to manipulate data in the database. There are lots of DBMS/RDBMS products available to you, for example, MS-Access, MSSQL Server, Oracle, Sybase and Ingres. The list is never-ending. Each of these RDBMS stores the data in their own format. MS-Access stores the data in .MDB file format whereas MS-SQL Server stores the data in a .DAT file format. Will the database alone be of any use to your client? The answer is NO! It will be a good idea for you to develop a customized application for the client with options to retrieve, add, and modify data at the touch of a key. To accomplish this, you should have a mechanism of making the application understand and work with the file format of the database i.e. .MDB or .DAT files. Self Assessment Questions 1. JAVA API stands for ____________. 2. Give some examples for DBMS products. 10.4 Mechanism for connecting to a back end database (ODBC) ODBC is the abbreviation for Open Database Connectivity, a standard database access method developed by Microsoft Corporation. The goal of ODBC is to make it possible to access any data from any application, regardless of which database management system (DBMS) is handling the data. ODBC manages this by inserting a middle layer, called a driver, between an application and the DBMS. The purpose of this layer is to translate the queries of the application into commands that the DBMS understands. For this to work, both the application and the DBMS must be ODBC-compliant i.e. the application must be capable of issuing ODBC commands and the DBMS must be capable of responding to them. Sikkim Manipal University - DDE Page No. 168 OOPS with Java Unit 10 JDBC JDBC provides a database-programming interface for Java programs. Since the ODBC is written in ‘C’ language, a Java program cannot directly communicate with an ODBC driver. JavaSoft created the JDBC-ODBC bridge driver that translates the JDBC API to the ODBC API. It is used with ODBC drivers. JDBC Driver Manager The JDBC driver manager is the backbone of the JDBC architecture. The function of the JDBC driver manager is to connect a Java application to the appropriate driver. JDBC-ODBC Bridge The JDBC-ODBC bridge allows you to use the ODBC driver as JDBC drivers. JDBC Application Architecture Figure 10.1: JDBC Application Architecture Connection to a Database The java.sql package contains classes that help in connecting to a database, sending SQL statements to the database, and processing query results. Sikkim Manipal University - DDE Page No. 169 OOPS with Java Unit 10 The Connection Objects The Connection object represents a connection with a database. You may have several Connection objects in an application that connects to one or more databases. Loading the JDBC-ODBC Bridge and Establishing Connection To establish a connection with a database, you need to register the ODBCJDBC Driver by calling the forName() method from the Class class and then calling the getConnection() method from the DriverManager class. The getConnection() method of the DriverManager class attempts to locate the driver that can connect to the database represented by the JDBC URL passed to the getConnection() method. The JDBC URL The JDBC URL is a string that provides a way of identifying a database. A JDBC URL is divided into three parts: <protocol>:<subprotocol>:<subname> <protocol> in a JDBC URL is always jdbc. <subprotocol> is the name of the database connectivity mechanism. If the mechanism of retrieving the data is ODBC-JDBC bridge, the subprotocol must be odbc. <subname> is used to identify the database. Example: JDBC URL String url = “jdbc:odbc:MyDataSource”; Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver“); Connection con = DriverManager.getConnection(url); Using the Statement Object You can use the statement object to send simple queries to the database as shown in the sample QueryApp program. Sikkim Manipal University - DDE Page No. 170 OOPS with Java Unit 10 Figure 10.2: Usage of Statement Object In the above QueryApp example: The JDBC-ODBC bridge driver is loaded. The Connection object is initialized using the getConnection() method. The Statement object is created using the createStatement() method. Finally, a simple query is executed using executeQuery() method of the Statement object. The Statement object allows you to execute simple queries. It has the following three methods that can be used for the purpose of querying: The executeQuery() method executes a simple query and returns a single ResultSet object. The executeUpdate() method executes an SQL INSERT, UPDATE or DELETE statement. The execute() method executes an SQL statement that may return multiple results. The ResultSet Object The ResultSet object provides you with methods to access data from the table. Executing a statement usually generates a ResultSet object. It maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next() method moves the cursor to the next row. You can access data from the ResultSet rows by calling the Sikkim Manipal University - DDE Page No. 171 OOPS with Java Unit 10 getXXX() method where XXX is the data type. The following code queries the database and process the ResultSet. Figure 10.3: The ResultSet Object Using the PreparedStatement Object You have to develop an application that queries the database according to the search criteria specified by a user. For example, the user supplies the publisher ID and wants to see the details of that publisher. select * from publishers where pub_id=? To make it possible, you need to prepare a query statement at runtime with an appropriate value in the where clause. The PreparedStatement object allows you to execute parameterized queries. The PreparedStatement object is created using the prepareStatement() method of the Connection object. stat=con.prepareStatement (“select * from publishers where pub_id=?”); The prepareStatement(), method of the Connection object takes an SQL statement as a parameter. The SQL statement can contain placeholders that can be replaced by INPUT parameters at runtime. The ‘?’ symbols is a placeholder that can be replaced by the INPUT parameters at runtime. Sikkim Manipal University - DDE Page No. 172 OOPS with Java Unit 10 Passing INPUT Parameters: Before executing a PreparedStatement object, you must set the value of each ‘?’ parameter. This is done by calling an appropriate setXXX() method, where XXX is the data type of the parameter. stat.setString(1, pid.getText()); ResultSet result=stat.executeQuery(); The following code makes use of the PreparedStatement object : import java.sql.*; import java.awt.*; import java.awt.event.*; public class PreparedQueryApp ActionListener { TextField pid; TextField pname; Button query; extends Frame implements static ResultSet result; static Connection con; static PreparedStatement stat; public PreparedQueryApp() { super (“The Query Application”); setLayout (new GridLayout (5,1)); pid=new TextField (20); pname=new TextField (50); query=new Button (“Query”); add(new Label (“Publisher ID:”)); add(pid); add(new Label (“Publisher Name”)); add(pname); add(query); query.addActionListener (this); pack (); setVisible (true); } Sikkim Manipal University - DDE Page No. 173 OOPS with Java Unit 10 public static void main (String a[]) { PreparedQueryApp obj =new PreparedQueryApp (); try { Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); Con=DriverManager.getConnection (“jdbc:odbc:MyDataSource”,”sa”,” “); stat=con.prepareStatement (“select * from publishers where pub_id =?”); } catch(Exception e){ } obj.showRecord (result ); public void actionPerformed (ActionEvent event) { if(event.getSource()==query) { try { stat.setString (1,pid.getText() ); result = stat.executeQuery(); result.next (); } catch(Exception e){} showRecord (result); } } public void showRecord (ResultSet result) { try { pid.setText (result.getString(1)); pname.setText (result.getString(2)); } catch (Exception e){} Sikkim Manipal University - DDE Page No. 174 OOPS with Java Unit 10 } } In the above example: The PreparedStatement object is created using the prepareStatement() method. The parameters of the PreparedStatement object are initialized when the user clicks on the Query button. The query is then executed using the executeQuery() method and the result is displayed in the corresponding controls. Self Assessment Questions 3. <protocol> in a JDBC URL is always _____. 4. <subprotocol> in JDBC URL must be _____. 5. _____ is used to identify the database in the JDBC URL. 10.5 Loading the ODBC driver Click on the ODBC Data Source icon in the Control Panel. Click on Add. Select the SQL Server option from the list and click on Finish. Select a name for the data source and click on the Next button. Select with SQL Server authentication using login ID and Password entered by the user. Select the database that you want to use and click on Next. Click on Finish. Click on Test Data Source to check for proper connectivity and click on OK. Self Assessment Questions 6. A _____ is a collection of related information and a _____ is the software that provides you with a mechanism to manipulate data in the database. 7. MS-Access stores the data in ______ file format whereas MS-SQL Server stores the data in a _____ file format. Sikkim Manipal University - DDE Page No. 175 OOPS with Java Unit 10 10.6 Summary JDBC JDBC provides a database-programming interface for Java programs. A Java program can send queries to a database using the JDBC driver. The java.sql Package The java.sql package contains classes that help in connecting to a database, send SQL statements to the database, and process the query results. The Connection Object The Connection object represents a connection with a database. It can be initialized using the getConnection() method of the DriverManager class. The PreparedStatement Object The PreparedStatement object allows you to execute parameterized queries. It can be initialized using the prepareStatement() method of the Connection object. The setString() Method The setString() method PreparedStatement Object. sets the query parameters of the The executeQuery() Method The executeQuery() method executes the query statement present in the PreparedStatement object and returns the number of rows affected by the query. 10.7 Terminal Questions 1. What is JDBC? 2. Draw and explain the JDBC Application Architecture? 3. How will you load the ODBC driver? 10.8 Answers Self Assessment Questions 1. Java Data Base Connectivity Application Program Interface. 2. MS-Access, SQL Server, MySQL, Oracle, Sybase etc. 3. jdbc Sikkim Manipal University - DDE Page No. 176 OOPS with Java 4. 5. 6. 7. Unit 10 odbc <subname> Database, Database Management System (DBMS). .MDB, .DAT Terminal Questions 1. JDBC stands for Java Data Base Connectivity. It works on top of ODBC (Open Data Base Connectivity). (Refer Section 10.2) 2. (Refer section 10.4.4) 3. Click on the ODBC Data Source icon in the Control Panel and follow the instructions. (Refer Section 10.5) Sikkim Manipal University - DDE Page No. 177 OOPS with Java Unit 11 Unit 11 RMI, CORBA and Java Beans Structure 11.1 Introduction Objectives 11.2 Remote Method Invocation (RMI) RMI Terminology 11.3 Common Object Request Broker Architecture (CORBA) What is Java IDL? Example: The Hello Client-Server 11.4 Java Beans The BeanBox Running the BeanBox 11.5 Summary 11.6 Terminal Questions 11.7 Answers 11.1 Introduction In the last unit, we have discussed database management concepts in Java. In this unit, we shall discuss some advanced Java concepts like Remote Method Invocation, Common Object Request Broker Architecture (CORBA) and Java Beans. There are different approaches used for developing distributed applications. The Internet and the Web are examples of distributed systems that have been developed using the Client/Server approach. The transfer of data is one of the most important processes in distributed applications. The default implementation of the message passing method in Java transfers data from the calling object to the called object within a single Java Virtual Machine (JVM). Another way to achieve the same is using Remote Method Invocation (RMI), which allows objects in different hosts to send and receive messages. Both the methods achieve the same goal. However, the method call approach used by RMI is much easier to use. RMI allows objects in different JVMs belonging to different hosts to send and receive message. CORBA stands for Common Object Request Broker Architecture. CORBA is a distributed computing technology where the Sikkim Manipal University - DDE Page No. 178 OOPS with Java Unit 11 participating objects need not only be written in Java. JavaBeans is the software component architecture for Java. It allows constructing applications efficiently by configuring and connecting components called Beans. The Beans need to be written and tested with a rich set of mechanisms for interaction between objects, along with common actions that most objects will need to support such as persistence and event handling. Java Bean is a software component that has been designed to be reusable in a variety of different environments. There is no restriction on the capability of a Bean. Objectives After studying this unit, you should be able to: describe Remote Method Invocation (RMI) implement RMI describe Common Object Request Broker Architecture (CORBA) and Java Interface Definition Language (IDL) explain Java Beans 11.2 Remote Method Invocation Distributed applications are applications that execute across multiple host systems. Objects executing on one host system can invoke the methods of objects on remote hosts. The remotely invoked methods can return values to the local objects. There are different approaches used for developing distributed applications. The Internet and the Web are examples of distributed systems that have been developed using the Client/Server approach. The transfer of data is one of the most important processes in distributed applications. The default implementation of the message passing method in Java transfers data from the calling object to the called object within a single Java Virtual Machine (JVM). You have learned how to cross process boundaries to transfer the data from one host to the other using sockets. Another way to achieve the same is using Remote Method Invocation (RMI), which allows objects in different hosts to send and receive messages. Both the methods achieve the same goal. However, the method calls approach used by RMI in much easier to use. RMI allows objects in different JVMs belonging to different hosts to send and receive message. Sikkim Manipal University - DDE Page No. 179 OOPS with Java Unit 11 RMI Terminology RMI is built upon the specification of how local and remote objects interoperate. Local objects are objects that execute on the local machine. Remote objects are objects that execute on all the other machines. Objects on remote hosts are exported so that they can be invoked remotely. An object exports itself by registering itself with a Remote Registry Server. A Remote Registry Server is a service that runs on a server and helps the objects on other hosts to remotely access its registered objects. The registry service maintains a database of all the named remote objects. Figure 11.1: RMI Mechanism A Distributed Application Created Using RMI Objects that are exported for remote access must implement the interface RemoteInterface. This interface identifies the object to be accessed remotely. All the methods that are to be invoked remotely must throw a RemoteException. This exception is used to handle the errors that may occur during the invocation of a remote method. Java’s RMI approach is organized into a client/server framework. A local object that invokes a method of a remote object is referred to as a client object, and the remote object whose methods are invoked is referred to as a server object. Java’s RMI approach makes use of stubs and skeletons. A stub is a local object on the client’s machine that acts as a proxy for a remote object. The stub provides the methods of the remote object. Local objects invoke the methods of the stubs as if they were methods of the remote objects. The stub communicates this method invocation to the remote object through a Sikkim Manipal University - DDE Page No. 180 OOPS with Java Unit 11 skeleton that is implemented on a remote host. The skeleton is the proxy of the client machine’s object that is located on the remote host. Figure 11.2: Use of Stubs and Skeletons Usage of Stubs and Skeletons to support Client/Server Communication The stub and the skeleton communicate through a remote reference layer. This layer provides stubs the capability to communicate with skeletons through a transport protocol. RMI uses the TCP protocol for transporting information. Self Assessment Questions 1. RMI stands for ____________. 2. A _____ is a service that runs on a server and helps the objects on other hosts to remotely access its registered objects. 3. Objects that are exported for remote access must implement the interface called _____. 4. All the methods that are to be invoked remotely must throw the exception called _____. 5. RMI uses the _____ protocol for transporting information. 11.3 CORBA CORBA stands for Common Object Request Broker Architecture. RMI, discussed in previous section needs the 2 objects participating in communication be written in Java. CORBA is a distributed computing technology where the participating objects need not only be written in Java. Sikkim Manipal University - DDE Page No. 181 OOPS with Java Unit 11 What is Java IDL? Java IDL is a technology for distributed objects-that is, objects interacting on different platforms across a network. Java IDL is similar to RMI (Remote Method Invocation), which supports distributed objects written entirely in the Java programming language. However, Java IDL enables objects to interact regardless of whether they’re written in the Java programming language or another language such as C, C++, COBOL, or others. Java IDL is based on the Common Object Request Brokerage Architecture (CORBA), an industry-standard distributed object model. A key feature of CORBA is IDL, a language-neutral Interface Definition Language. Each language that supports CORBA has its own IDL mapping and as its name implies, Java IDL supports the mapping for Java. CORBA and the IDL mappings are the work of an industry consortium known as the OMG, or Object Management Group. To support interaction between objects in separate programs, Java IDL provides an Object Request Broker, or ORB. The ORB is a class library that enables low-level communication between Java IDL applications and other CORBA-compliant applications. Example: The Hello Client-Server This tutorial teaches the basic tasks in building a CORBA distributed application using Java IDL. You will build the classic Hello World program as a distributed application. The Hello World program has a single operation that returns a string to be printed. The client (applet or application) invokes the sayHello operation of the HelloServer. The ORB transfers that invocation to the server object registered for IDL interface. The server’s sayHello method runs, returning a Java String. The ORB transfers that String back to the client. The client prints the value of the String. Sikkim Manipal University - DDE Page No. 182 OOPS with Java Unit 11 Self Assessment Questions 6. CORBA stands for Common _____. 7. IDL stands for ___________. 8. CORBA and the IDL mappings are the work of an industry consortium known as the ______. 11.4 Java Beans JavaBeans is the software component architecture for Java. It allows constructing applications efficiently by configuring and connecting components called Beans. The Beans need to be written and tested with a rich set of mechanisms for interaction between objects, along with common actions that most objects will need to support such as persistence and event handling. The BeanBox The BeanBox is a very simple test container. It allows you to try out both the BDK example beans and your own newly created beans. The BeanBox allows you to: Drop beans onto a composition window. Resize and move beans around. Edit the exported properties of a bean. Connect a bean event source to an event handler method. Connect together bound properties on different beans. Save and restore sets of beans. Make applets from beans. Get an introspection report on a bean. Add new beans from JAR files. Note that the BeanBox is intended as a test container and as a reference base, but it is not intended as a serious application development tool. Advantages of Java Beans Java Beans is a software component architecture that provides standard mechanisms to deal with software building blocks. The following list enumerates some of the specific benefits that Java technology provides for a component developer: A Bean obtains all the benefits of Java's "write-once, run-anywhere" paradigm. The properties, events, and methods of a Bean that are exposed Sikkim Manipal University - DDE Page No. 183 OOPS with Java Unit 11 to an application builder tool can be controlled. A Bean may be designed to operate correctly in different locales, which makes it useful in global markets. Auxiliary software can be provided to help a person configure a Bean. This software is only needed when the design-time parameters for that component are being set. It does not need to be included in the run-time environment. The configuration settings of a Bean can be saved in persistent storage and restored at a later time. A Bean may register to receive events from other objects and can generate events that are sent to other objects. Running the BeanBox To start the BeanBox first change to the beanbox directory and then run beanbox. Note that you need to have the JDK “bin” directory on your path and you should be using JDK 1.1 or later. The BeanBox comes up as three separate windows: The middle window is the main beanbox composition window. The left-hand window is the Toolbox palette displaying available beans that can be dropped onto the composition window. The right-hand window is a PropertySheet showing the properties for the currently selected bean. Dropping beans onto the composition window : To add a bean to the composition window first click on the bean’s name or icon in the left-hand ToolBox window. Then click on the location in the center composition window where you want the new bean to appear. The chosen bean will appear centered at the new location and will become the current selected bean for editing. Selecting a bean in the composition window: The currently selected bean is marked with a black-and-white hashed boundary. The right-hand PropertySheet window shows its properties and the “edit” menu provides access to its events, bound properties, etc. To select a bean you must click the mouse just outside of the bean in the boundary area where the black-and-white hashed boundary appears. Some beans won’t notice a click on the bean itself, and require you to click in the surrounding border area. Sikkim Manipal University - DDE Page No. 184 OOPS with Java Unit 11 Moving or resizing a bean: You can move the currently selected bean by clicking the mouse on one of the black-and-white hashed borders and the holding the mouse down and dragging the bean. Some beans, such as the BeanBox bean or the ExplicitButton, also allow themselves to be resized. You can try to resize the currently selected bean by clicking on one of the corners of the black-and-white boundary and holding the mouse down and stretching the corner out. Editing a beans properties : You can edit the public properties of the currently selected bean using the right-hand PropertySheet window. For each editable property the PropertySheet window shows the name of the property and its current value. The current value may be shown as An editable text field. Or a selection in a choice menu Or a painted value, where you can click on the painted value to bring up a small model dialog for that property. Using a bean Customizer : For those beans that have customizers, the BeanBox allows you to run the customizer to configure your beans. If the currently selected bean has a customizer, then the “edit” menu on the central window will include a “Customize…….” entry. If you select that array, then a dialog window will come up with the bean’s customizer. Connecting an event handler : The BeanBox allows you to connect an event from the currently selected bean to a target event handling method on any other bean. The “edit” menu on the central composition window has an “events” menu that has a sub-menu for all the different kinds of events that the currently selected bean fires. These events are grouped and named according to their EventListener interfaces. Connecting a bound property : The BeanBox allows you to connect a bound property from a source bean to a target property on some other bean. Then when the bound property on the source bean is changed, the associated target property is also automatically updated. Sikkim Manipal University - DDE Page No. 185 OOPS with Java Unit 11 If the currently selected bean supports bound properties, then the “edit” menu will include a “Bind properly……” item. If you chose this menu item, then the BeanBox will bring up a dialog showing the bound properties available on the source bran. You can then select a source property and press “OK”. The beanbox will then draw a “rubber band” line. You can then click on the border of the target bean to which you want the property bound. The BeanBox will then bring up a dialog listing the target properties on the target bean that match the of the source property. You can select a target property and press “ok”. Now when you change the source property on the source bean then the target property on the target bean will also be updated. Saving and restoring beans: Once you have set up some beans in the BeanBox, you can use the “File” menu’s “Save…” sub-menu to save away the current state of the BeanBox. This uses Java Object Serialization to automatically store away all the state of the beans into a named file. You can then use the “File” menu’s “Clear” item to discard the current set of beans and use the “Load…” item to read in and recreate all the serialized beans. This provides a simple way to test the use of serialization with your beans. Getting an introspection report on a beans : If you want to see all the properties, methods, and events that the Beans introspector has found on a selected bean, you can use the BeanBox’s “report” menu item under “edit” menu. This generates a summary report to the standard output of the introspection information for the selected bean. Adding your bean to the BeanBox : When the BeanBox starts it loads all the JAR files that it finds in the “jars” directory. The BeanBox uses the manifest file in each JAR file to identify any bean classes in the JAR file, and adds those beans to the ToolBox palatte in the BeanBox. To add your bean to the BeanBox, you must wrap it up in a JAR file which contains a suitable manifest file describing the bean. Once you have a suitable JAR file, simply add it to the “jars” directory and restart the BeanBox, or load the JAR directly using the “LoadJar….”item in the “File” menu. Sikkim Manipal University - DDE Page No. 186 OOPS with Java Unit 11 Example Beans: As part of the BDK we include a number of example beans that demonstrate various aspect of the JavaBeans architecture. The following beans are all present in the default ToolBox palatte for the BeanBox. Their sources are in the “demo” directory. BridgeTester. CahngeReporter. ExplicitButton EventMonitor JellyBean Juggler Molecule OurButton TickTock Voter Create and Configure an Instance of the Molecule Bean Follow these steps to create and configure an instance of the Molecule Bean: 1. Position the cursor on the ToolBox entry labeled Molecule and click the left mouse button. You should see the cursor change to a cross. 2. Move the cursor to the BeanBox display area and click the left mouse button in approximately the area where you wish the Bean to be displayed. You should see a rectangular region appear which contains a 3-D display of a molecule. This area is surrounded by a hatched border, indicating that it is currently selected. 3. You can reposition the Molecule Bean by positioning the cursor over one of the hatched borders and dragging the Bean. 4. You can change the molecule that is displayed by changing the selection in the Properties window. Notice that the Bean display changes immediately when you change the selected molecule. Create and Configure an Instance of the OurButton Bean Follow these steps to create and configure an instance of the OurButton Bean and connect it to the Molecule Bean: Sikkim Manipal University - DDE Page No. 187 OOPS with Java Unit 11 1. Position the cursor on the ToolBox entry labeled OurButton and click the left mouse button. You should see the cursor change to a cross. 2. Move the cursor to the BeanBox display area and click the left mouse button in approximately the area where you wish the Bean to be displayed. You should see a rectangular region appear that contains a button. This area is surrounded by a hatched border indicating that it is currently selected. 3. You may reposition the OurButton Bean by positioning the cursor over one of the hatched borders and dragging the Bean. 4. Go to the Properties window and change the label of the Bean to "Rotate X". The button appearance changes immediately when this property is changed. 5. Go to the menu bar of the BeanBox and select Edit | Events | action | actionPerformed. You should now see a line extending from the button to the cursor. Notice that one end of the line moves as the cursor moves. However, the other end of the line remains fixed at the button. 6. Move the cursor so that it is inside the Molecule Bean display area, and click the left mouse button. You should see the Event Target Dialog dialog box. 7. The dialog box allows you to choose a method that should be invoked when this button is clicked. Select the entry labeled "rotateOnX" and click the OK button. You should see a message box appear very briefly, stating that the tool is "Generating and compiling adaptor class." Test the application. Each time you press the button, the molecule should move a few degrees around one of its axes. Now create another instance of the OurButton Bean. Label it "Rotate Y" and map its action event to the "rotateY" method of the Molecule Bean. The steps to do this are very similar to those just described for the button labeled "Rotate X". Test the application by clicking these buttons and observing how the molecule moves. Self Assessment Questions 9. The _____ is a very simple test container for JavaBeans. 10. A Bean obtains all the benefits of Java's "_____" paradigm. 11. The right-hand window of the beanbox contains _____showing the properties for the currently selected bean. Sikkim Manipal University - DDE Page No. 188 OOPS with Java Unit 11 11.5 Summary Distributed applications are applications that execute across multiple host system. RMI allows objects in different JVMs belonging to different hosts to send and receive message. A Remote Registry Server is a service that runs on a server and helps objects on other hosts to remotely access its registered objects. Java’s RMI approach makes use of stubs and skeletons. CORBA stands for Common Object Request Broker Architecture. RMI, discussed in previous section with RMI is that, it needs the 2 objects participating in communication be written in Java CORBA is a distributed computing technology where the participating objects need not only be written in Java. JavaBeans is the software component architecture for Java. It allows efficiently constructing applications by configuring and connecting components called Beans. The BeanBox comes up as three separate windows: o The middle window is the main beanbox composition window. o The left-hand window is the Toolbox palette displaying available beans that can be dropped onto the composition window. o The right-hand window is a PropertySheet showing the properties for the currently selected bean. 11.6 Terminal Questions 1. What are the different RMI terminologies? 2. What are the uses of CORBA? 3. Explain the working of BeanBox? 11.7 Answers Self Assessment Questions 1. Remote Method Invocation. 2. Remote Registry Server. 3. RemoteInterface. 4. RemoteException. 5. TCP 6. Common Object Request Broker Architecture. Sikkim Manipal University - DDE Page No. 189 OOPS with Java 7. 8. 9. 10. 11. Unit 11 Interface Definition Language. Object Management Group BeanBox. write-once, run-anywhere. PropertySheet. Terminal Questions 1. Local Objects, Remote Objects, Remote Registry Server. (Refer Section 11.2) 2. A key feature of CORBA is IDL, a language-neutral Interface Definition Language. Each language that supports CORBA has its own IDL mapping and as its name implies, Java IDL supports the mapping for Java. CORBA and the IDL mappings are the work of an industry consortium known as the OMG, or Object Management Group. (Refer Section 11.3) 3. The BeanBox comes up as three separate windows: The middle window is the main beanbox composition window. The left-hand window is the Toolbox palette displaying available beans that can be dropped onto the composition window. The right-hand window is a PropertySheet showing the properties for the currently selected bean. (Refer Section 11.4) Sikkim Manipal University - DDE Page No. 190 OOPS with Java Unit 12 Unit 12 Java Server Pages and Servlets Structure 12.1 Introduction Objectives 12.2 Java Server Pages (JSP) What is needed to write JSP based web application? How does JSP look? How to test a JSP? 12.3 Servlets History of Web Application Web Architecture Servlet Life Cycle 12.4 Summary 12.5 Terminal Questions 12.6 Answers 12.1 Introduction In the last unit, we have discussed various advanced features of Java like RMI, CORBA and Java Beans. In this unit, we shall discuss yet another important feature of called Java Server Pages (JSP) and Servlets. Java Server Pages (JSP) are actually, text files that combine standard HTML and new scripting tags. JSPs look like HTML, but they get compiled into Java Servlets the first time they are invoked. Java servlets are the key components of server-side Java development. A servlet is a small pluggable extension to a server that enhances the server‟s functionality. Servlets allow developers to extend and customize any Java-enabled Server- a web server, a mail server, an application server or any custom server. Objectives After studying this unit, you should be able to: explain JSP Basics describe Basics and Life Cycle of Servlets implement Basic JSP and Servlet Programs Sikkim Manipal University - DDE Page No. 191 OOPS with Java Unit 12 12.2 JSP Java Server pages are on the whole, text files that combine standard HTML and new scripting tags. JSPs look like HTML, but they get compiled into Java Servlets the first time they are invoked. The resulting servlet is a combination of the HTML from the JSP file and embedded dynamic content specified by the new tags. Some of them will contain only Java code; this is particularly useful when the JSP is responsible for a particular task like maintaining application flow. What is needed to write JSP based web application? Programming with JSP will need a thorough knowledge of how servlets are written and executed as the code segments inserted in a JSP are mostly Servlet code. If you have already written some ASP programs you may find it easy to work with JSP as there are so many similarities although they are two different technologies. To write a JSP code you require an editor. To test the JSPs you need a JSP engine. So this material considers the Java Web Server to the JSP engine. How does JSP look? Before considering more technical details regarding JSP, let us see how a JSP file looks and what its static parts are and what its dynamics parts are: Consider the HelloWorld.jsp below: 1. <HTML> 2. <HEAD> 3. <META NAME=”GENERATOR “ Content = “Microsoft Visual Studio 6.0”> 4. <TITLE></TITLE> 5. </HEAD> 6. <BODY> 7. <center><h1> 8. <% out.println(“Hello World!”); %> 9. </h1><center> 10. </BODY> 11. </HTML> As you can see a JSP page looks almost like a simple HTML file. In the above HelloWorld.jsp line number eight is the one accounting for the Sikkim Manipal University - DDE Page No. 192 OOPS with Java Unit 12 dynamic content. All the other lines are static HTML content. If you observe line eight carefully, you can notice that the written code resembles servlet code in some way. How to test a JSP? Once a JSP is written next question is how do you test it? To test JSP we are going to use Java Web Server. The steps are as following: Copy the HelloWorld.jsp to c:\JavaWebServer2.0\public_html directory as it is the document root of the Java Web Server. (Assuming that the Java Web Server is installed in c:\) Now start the Java Web Server‟s web service. Open your browser window. Now in the address bar type in an address as http://IPAddress:: 8080/HelloWorld.jsp, where IP address is the IP address of your machine. You should be able to see the output as shown below. Figure 12.1: JSP Output Self Assessment Questions 1. JSP stands for _____. 2. A _____ is a small pluggable extension to a server that enhances the server‟s functionality. Sikkim Manipal University - DDE Page No. 193 OOPS with Java Unit 12 12.3 Servlets The rise of server-side Java applications is one of the latest and most exciting trends in Java programming. The Java language was originally intended for use in small, embedded devices. Java‟s potential as a serverside development platform had been sadly overlooked until recently. Businesses in particular have been quick to recognize Java‟s potential on the server-side. Java is inherently suited for large client/server applications. The cross platform nature of Java is extremely useful for organizations that have a heterogeneous collection of servers running various flavors of the UNIX and Windows operating systems. Java’s modern, object-oriented, memory-protected design allows developers to cut development cycles and increase reliability. In addition, Java‟s built-in support for networking and enterprise APIs provides access to legacy data, easing the transition from older client/server system. Java servlets are a key component of server-side Java development. A servlet is a small pluggable extension to a server that enhances the server‟s functionality. Servlets allow developers to extend and customize any Javaenabled Server- a web server, a mail server, an application server or any custom server. History of Web Application While servlets can be used to extend the functionality of any Java-enabled server, today they are most often used to extend web servers, providing a powerful, efficient replacement for CGI (Common Gateway Interface) scripts. When you use servlet to create dynamic content for a web page or otherwise extend the functionality of a web server, you are in effect creating a Web application. While a web page merely displays static content and lets the user navigate through that content, a web application provides a more interactive experience. A web application may be as simple as a key word search on a document archive or as complex as an electronic storefront. Web applications are being deployed on the internet and on corporate intranets and extranets, where they have the potential to increase productivity and change role of servlets in any web application it is necessary to understand the architecture of any current web application. Sikkim Manipal University - DDE Page No. 194 OOPS with Java Unit 12 Web Architecture Two-tier Architecture Typical client/server systems are all two-tiered in nature where the application resides entirely on the client PC and database resides on a remote server. But two-tier systems have some disadvantages such as: The processing load is given to the PC while more powerful server acts as a traffic controller between the application and the database. Maintenance is the greatest problem. Imagine a situation where there is a small modification to be done in the application program. Then in case of a two-tier architecture system, it is necessary to go to each client machine and make the necessary modifications to the programs loaded on them. That is the reason why the modern web applications are all developed based on three-tier architecture. N-tier Architecture Although the title of this section is given as N-Tier architecture, here the concentration is on the three-tier architecture. Basic reason for this is that any web application developed based on N-tier architecture functions just similar to typical three-tier architecture. First-Tier: Basically the presentation Layer. Represented by the GUI kind of thing. Middle-Tier : Application Logic Third-Tier : Data that is needed for the application. The basic idea behind three-tier architecture is that to separate application logic from the user interface. This gives the flexibility to the design of the application as well as ease of maintenance. If you compare this with two-tier architecture, it is very clear that in three-tier architecture the application logic can be modified without affecting the user interface and the database. Typical Web Application A typical web application consists of following steps to complete a request and response. Web application will collect data from the user. (First tier) Sikkim Manipal University - DDE Page No. 195 OOPS with Java Unit 12 Send a request to the web server. Run the requested server program. (Second and third tier) Package up the data to be presented in the web browser. Send it back to the browser for display. (First tier) Servlet Life Cycle Now you have seen the basic structure of a servlet. Let‟s review the process by which a server invokes a servlet. This process can be broken down into the nine steps as follows: 1. The server loads the servlet when it is first requested by the client or if configured to do so, at server start-up. The servlet may be loaded from either a local or a remote location using the standard Java class loading facility. This step is equivalent to the following code: Class c=Class.forName(“com.sourcestream.MyServlet”); It should be noted that when referring to servlets, the term load often refers to the process of both loading and instantiating the servlet. 2. The server creates one or more instances of the servlet class. Depending on implementation the server may create a single instance that services all requests through multiple threads or create a pool of instances from which one chosen to service at each new request. This step is equivalent to the following Java code: Servlet s=(Servlet) c.newInstance(); where „c‟ is the same Class object created in previous step. 3. The server constructs a ServerConfig object that provides initialization information to the servlet. 4. The server calls the servlet‟s init() method, passing the object constructed in step 3 as a parameter. The init() method is guaranteed to finish execution prior to the servlet processing the first request. If the server has created multiple servlet instances (step 2), the init() method is called one time for each instance. 5. The server constructs a ServletRequest or HttpServletRequest object from the data included in the client‟s request. It also constructs a ServletResponse or HttpServletResponse object that provides methods for customizing the server‟s response. The type of object Sikkim Manipal University - DDE Page No. 196 OOPS with Java 6. 7. 8. 9. Unit 12 passed in these two parameters depends on whether the servlet extends the GenericServlet class or the HttpServlet class, respectively. The server calls the servlet‟s service() method passing the objects constructed in step 5 as parameters. When concurrent requests arrive, multiple service() methods can run in separate threads. The service() method processes the client request by evaluating the ServletRequest or HttpServletRequest object and responds using ServletResponse or HttpServletResponse object. If the server receives another request for this servlet, the process begins again at step 5. When instructed to unload the servlet, perhaps by the server administrator or programmatically by the servlet itself, the server calls the servlet‟s destroy() method. The servlet is then eligible for garbage collection. The above mentioned nine steps illustrate the entire lifecycle of a servlet. The following figure shows the flow of the servlet lifecycle. Figure 12.2: Servlet Life Cycle Sikkim Manipal University - DDE Page No. 197 OOPS with Java Unit 12 The Java Servlet Development Kit The Java Servlet Development Kit (JSDK) contains the class libraries that you will need to create servlets. A utility known as the servletrunner is also included, which enables you to test some of the servlets that you create. We will use this tool to execute the examples in this chapter. You can download the JSDK (freeware) from the Sun Microsystems Web site at java.sun.com. Follow the instructions to install this toolkit on your machine. For a Windows machine, the default location of Version 2 of the JSDK is c:\\Jsdk2.0. The directory c:\\Jsdk2.0\\bin contains servletrunner.exe. Update your Path environment variable so that it includes this directory. The directory c:\\Jsdk2.0\\lib contains jsdk.jar. This JAR file contains the classes and interfaces that are needed to build servlets. Update your Classpath environment variable so that it includes c:\\Jsdk2.0\\lib\\jsdk.jar. A Simple Servlet To become familiar with the key servlet concepts, we will begin by building and testing a simple servlet. The basic steps are the following: 1. Create and compile the servlet source code. 2. Start the servletrunner utility. 3. Start a Web browser and request the servlet. The following sections examine each of these steps in detail. Create and Compile the Servlet Source Code To begin, create a file named HelloServlet.java that contains the following code: import java.io.*; import javax.servlet.*; public class HelloServlet extends GenericServlet { public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>Hello!"); Sikkim Manipal University - DDE Page No. 198 OOPS with Java Unit 12 pw.close(); } } First, note that this program imports the javax.servlet package, which contains the classes and interfaces required to build servlets. You will learn more about these classes and interfaces later in this chapter. Next, the program defines HelloServlet as a subclass of GenericServlet. The GenericServlet class provides functionality that makes it easy to handle requests and responses. Inside HelloServlet, the service() method (which is inherited from GenericServlet) is overridden. This method handles requests from a client. Notice that the first argument is a ServletRequest object. This enables a servlet to read data that is provided via the client request. The second argument is an ServletResponse object. This enables a servlet to formulate a response for the client. The call to setContentType( ) establishes the MIME (Multimedia Internet Mail Extension) type of the HTTP response. In this program, the MIME type is text/html, which indicates that the browser should interpret the content as HTML source code. Next, the getWriter( ) method obtains a PrintWriter. Anything written to this stream is sent to the client as part of the HTTP response. Then, println( ) is used to write some simple HTML source code as the HTTP response. Compile this source code and place the HelloServlet.class file in the directory named c:\\Jsdk2.0\\examples. This ensures that it can be located by the servletrunner utility. Start the servletrunner Utility Open a command prompt window and type servletrunner to start that utility. This tool listens on port 8080 for incoming client requests. Start a Web Browser and Request the Servlet Start a Web browser and enter the URL shown here: http://localhost:8080/servlet/HelloServlet Sikkim Manipal University - DDE Page No. 199 OOPS with Java Unit 12 Alternatively, you may enter the URL shown here: http://127.0.0.1:8080/servlet/HelloServlet This can be done because 127.0.0.1 is defined as the IP address of the local machine. You should observe the output of the servlet in the browser display area. It should contain the string Hello! in bold face. Note The examples in this chapter assume that the servletrunner and the Web browser execute on the same machine. However, these two applications can be installed on different machines. In that case, the URLs must be changed to identify the machine on which servletrunner is executing. Self Assessment Questions 3. CGI stands for _____. 4. Middle tier of three tier architecture contains _____. 5. Servlet Life Cycle contains _____, _____ and _____ methods. 12.4 Summary Java Server Pages are the text files that combine standard HTML and new scripting tags. To write a JSP code you require an editor. To test the JSPs you need a JSP engine. Different Web Architecture are: o Simple Web Request-Response Paradigm. o Two-tier Architecture. o N-tier Architecture. 12.5 Terminal Questions 1. What are the procedures for testing JSP? 2. Explain two-tier and N-tier architecture. 3. Explain the life cycle of a Servlet. Sikkim Manipal University - DDE Page No. 200 OOPS with Java Unit 12 12.6 Answers Self Assessment Questions 1. Java Server Pages. 2. Servlet. 3. Common Gateway Interface. 4. Application Logic. 5. init(), service(), destroy(). Terminal Questions 1. JSP is tested using Java Web Server. (Refer Section 12.2) 2. In two-tier architecture application resides entirely on the client PC and database resides on remote server. N-tier consists of minimum of three tiers. (Refer Section 12.3) 3. Init(), service() and destroy(). (Refer Section 12.3) Sikkim Manipal University - DDE Page No. 201 OOPS with Java Unit 13 Unit 13 Networking in Java Structure 13.1 Introduction Objectives 13.2 Networking in Java 13.3 URL Objects 13.4 Summary 13.5 Terminal Questions 13.6 Answers 13.1 Introduction In the last unit, we have discussed JSP and Servlets. In this unit, we shall discuss Networking features of Java. The Net class library, java.net, provides a high-level interface for connections over the Internet or any other kind of TCP/IP network. Using these interfaces makes it possible for a Java application to connect to existing network services, provide its own network services, and even allow for multiuser, network-aware games over the Internet. Whereas these can be quite complicated to program in other languages, the java.net package allows the basics of socket connection to be set up in as little as 10 lines of code. Objectives After studying this unit, you should be able to: explain Networking in Java describe URL objects 13.2 Networking in Java Java’s class library includes the java.net package, which makes it possible to communicate over a network with Java programs. The package provides cross-platform abstractions for simple networking operations, including connecting and retrieving files by using Common Web protocols and creating basic UNIX like sockets. Java applets cannot read or write from the disk on the machine where the browser is running. Java applets cannot connect to system other than the Sikkim Manipal University - DDE Page No. 202 OOPS with Java Unit 13 one on which they were originally stored. By two ways, communication can done to the system: getInputStream() is a method that opens a connection to an URL and enables to extract data from that connection. The socket classes Socket and ServerSocket enables to open standard socket connections to hosts and read to and write from those connection. The following sections describe the classes in the java.net package. The ContentHandler Class ContentHandler is used to read a stream of data that is generated by a network connection and produce an object. The exact content handler called depends on the MIME type of the remote data. ContentHandler should not be called directly. This task is much better performed by URL.getContent() or URLConnection.getContent(), which simplify the process of reading a stream of data. The DatagramPacket Class DatagramPacket is used to both send and receive datagram packets. A datagram packet is a segment of data containing packet data, packet length, Internet address, and port. This allows programming at the IP packet level. DatagramPacket methods are used to determine the address, length, and port of the datagram packet, as well as retrieve the data itself. The DatagramSocket Class DatagramSocket is used for creating UDP-based connections over a network. Services such as Sun’s Network File System (NFS) use UDP as the underlying protocol. Java applications can also create and/or use UDPbased network connections by making use of this class. The InetAddress Class InetAddress makes an object of Internet addresses. This makes them able to be manipulated as String objects or within other network classes. Self Assessment Questions 1. _____ package contains all the network related classes and methods of Java. 2. _____ method opens a connection to an URL and enables to extract data from that connection. Sikkim Manipal University - DDE Page No. 203 OOPS with Java Unit 13 3. _____ class is used to read a stream of data that is generated by a network connection and produce an object. 13.3 URL Objects Addresses on WWW are represented in Java by URL objects. A URL represents any type of information which has to be linked with web. The URL is set up to perform certain activities when a connection is made to it, such as loading a web page or downloading a file. These URL classes are similar to sockets in that they allow easy integration of network applications into a program. URLs are a bit more user-friendly to work with than the sockets. The URL Class The URL class transforms a URL string into an object that can then be manipulated using associated methods. These methods serve purposes such as getting the filename, protocol, and hostname. URL also has methods that can open and maintain the data connection of an input stream. This is much easier to use than the socket classes. The URLConnection Class URLConnection is another abstract class used to create and control a connection to a platform and firewall specific location. It is a simplified version of connection interface for the URL class. The URLEncoder Class URLEncoder takes a string of text and turns it into the x-www-formurlencoded format, which is a MIME format. This can then be used in conjunction with the URL class. The URLStreamHandler Class URLStreamHandler is an abstract class. Its purpose is to create a format for opening a stream connection to a specific URL. This class is concerned with the protocol of the URL. If a programmer wants to create a new URL stream protocol, it is necessary to implement the methods specified in this abstract class. To link a new page in WWW an instance of the class URL has to be created. To create a new URL any one of the following constructors can be used: Sikkim Manipal University - DDE Page No. 204 OOPS with Java Unit 13 URL(String) creates an object from a full web address such as http://www.smude.edu.in URL(URL, String) creates an URL object with a base address provided by the specified URL and a relative path provided by the String. URL(String, String, int, String) creates a new URL object, given a protocol, host name and a filename or path name. URL(String, String, String) is the same as the previous constructor without the port number. The sun.tools.debug Library This library provides the necessary framework for debugging Java programs. Whenever Java debugger is used, this library automatically gets accessed. Own debugger can also be created. The DebuggerCallback Interface The DebuggerCallback interface is a template for implementing communications between an application and a debugger. The basic syntax for the interface is as follows: public interface DebuggerCallback { … } All communications between client applications and a debugger are asynchronous. One of the key methods in this interface is breakpointEvent(), which is used to report when a breakpoint is reached. The method accepts a RemoteThread object – the thread that reached the breakpoint-as a parameter. Other key methods in this class include exceptionEvent(), printTo Console(), quitEvent(), and threadDeathEvent(). The exceptionEvent() method is used to report that an exception has occurred. It accepts a RemoteThread object and a String object as parameters. The printToConsole() method is used whenever the DebuggerCallback interface prints messages to the console – which, as in the Java debugger. The printToConsole() method accepts a String object as a parameter. Sikkim Manipal University - DDE Page No. 205 OOPS with Java Unit 13 The quitEvent() method is used to tell the debugger that the client has exited. Generally, clients exit either by returning from the main thread or by calling System.exit(). The threadDeathEvent() is used to report that a thread has died. This method accepts a RemoteThread object, which is the thread that died, as a parameter. Methods that deal with RemoteObjects A complete listing of the types of remote objects handled by the debugger is as follows: array, boolean, byte, character, class, double, field, float, integer, long, short, string, thread, thread group, and variable value. Each of these object types is handled in a separate class. These classes include: RemoteArray RemoteBoolean RemoteByte RemoteChar RemoteClass RemoteDouble RemoteField RemoteFloat RemoteInt RemoteLong RemoteShort RemoteString RemoteThread RemoteThreadGroup RemoteValue Sikkim Manipal University - DDE Page No. 206 OOPS with Java Unit 13 Table 13.1: Methods in the RemoteObject class Method description() finalize() getClass() getField() getFields() getFieldValue() getId() setField() toString() typeName() Purpose Returns a description of the object Performs this code when garbage collection is run Returns the object’s class Returns an instance variable Returns the non-static fields of an object Returns the value of an object’s instance variable Returns the ID of an object Sets an instance variable, specified by slot or name Returns the object as a string Returns the object type The RemoteStackFrame class Using the RemoteStackFrame class, the debugger can examine a suspended thread’s stackframe. The stackframe provides a frame of reference for everything related to a thread’s stack. It works as a snapshot of a thread’s internals, including the thread’s program counter, local variables, referenced methods, referenced classes, and the current line number of execution. The methods used to retrieve this information follow a very basic syntax. For example, when the getLineNumber() method is called, the method returns the current line number of execution. This and other methods in this class are shown in the table below: Table 13.2: Methods in the RemoteStackFrame class Method getLineNumber() getLocalVariable() getLocalVariables() getMethodName() getpc() getRemoteClass() Purpose Returns the current line number of execution Returns a named stack variable in the current stackframe Returns an array of all valid local variables and method arguments for the stackframe Returns the method name that the stackframe references Returns the program counter that the stackframe references Returns the class that the stackframe references Sikkim Manipal University - DDE Page No. 207 OOPS with Java Unit 13 The RemoteStackVariable class The RemoteStackVariable class is similar to the RemoteStackFrame class. Using this class, the caller can obtain information about a specific stack variable. The class has three methods: getName(), getValue(), and inScope(). The getName() method is used to get the name of a variable on the stack. The getValue() method is used to get the value of a variable on the stack. The inScope() method is used to tell whether the variable is accessible. The RemoteDebugger class Client applications use this class as an interface to the Java debugging classes because these classes can instantiate a connection with the Java interpreter session being debugged. To create a client interface, constructors can be used. The RemoteDebugger class provides an overloaded constructor interface that allows for the two different ways the debugger can be instantiated. The first constructor is used to attach the debugger to a current interpreter session. The interpreter passes back a password, which is then passed to the debugger when it is invoked. In addition to accepting the password as a parameter, the constructor accepts a String object that identifies The host running the current interpreter session The client using the DebuggerCallback interface to receive messages from the debugger A verbose flag to turn on internal debugger message text Here is the syntax for the first constructor: public RemoteDebugger(String host, String password, DebuggerCallback client, boolean verbose) throws Exception The second constructor is used to create a remote debugger that will start a client interpreter session. When user starts the debugger directly, it in turn starts the Java interpreter with any parameters passed on the command line. For this reason, the second constructor accepts arguments that are to be passed on to the interpreter. Other parameters allow the client using the DebuggerCallback interface to receive messages from the debugger, and others set a verbose flag to turn on or off internal debugger message text. Sikkim Manipal University - DDE Page No. 208 OOPS with Java Unit 13 The syntax for the second constructor follows: public RemoteDebugger(String javaArgs, DebuggerCallback client, boolean verbose) throws Exception Methods in the RemoteDebugger class enable the user to use debugging techniques in the programs. These methods are given in the table below. Table 13.3: Methods in the RemoteDebugger class Method addSystemThread() close() findClass() freeMemory() Purpose Adds a system thread Closes the connection to the remote debugger Finds a specified class Gets a report of the free memory available to the Java interpreter being debugged gc() Frees all objects referenced by the debugger get() Gets an object from the remote object cache getExceptionCatchList() Gets the list of the exceptions on which the debugger will stop getSourcePath() Gets the source file path the client is currently using itrace() Turns instruction tracing on or off listBreakpoints() Gets a list of the current breakpoints listClasses() Gets a list of the currently known classes listThreadGroups() Gets a list of the currently known thread groups run() Loads and runs a runnable Java class setSourcePath() Sets the search path for source files totalMemory() Obtains a report of the total memory used by the Java interpreter being debugged trace(boolean) Turns method call tracing on or off The StackFrame class The StackFrame class provides a wrapper for the stackframe of a suspended thread. This class has a very basic constructor and a single method, called toString(), that returns an object as a string. Sikkim Manipal University - DDE Page No. 209 OOPS with Java Unit 13 Self Assessment Questions 4. _____ is an abstract class that is used to create and control a connection to a platform- and firewall-specific location. 5. _____ is an abstract class that is used to create a format for opening a stream connection to a specific URL. 6. The _____ method is used to report that a thread has died. 13.4 Summary The java.net package contains classes that provide an easy-to-use interface to basic network programming. The sun.tools.debug class library adds built-in debugging support to the Java programming language. When sockets are used in an applet, still it is subject to the security restrictions that prevents from connecting to any other system other than the same one the applet came from. There are many new subclasses of the SocketException class, to represent network errors on a finer level of granularity than in Java 1.02. 13.5 Terminal Questions 1. 2. 3. 4. 5. Explain the various classes available in java.net package. Explain the various URL objects. What are the various Remote Object classes? What are the methods available in RemoteStackFrame? What are the methods available in RemoteDebugger class? 13.6 Answers Self Assessment Questions 1. java.net 2. getInputStream() 3. ContentHandler() 4. URLConnection 5. URLStreamHandler 6. threadDeathEvent() Sikkim Manipal University - DDE Page No. 210 OOPS with Java Unit 13 Terminal Questions 1. ContentHandler, DatagramPacket, DatagramSocket, InetAddress. (Refer Section 13.2.) 2. URL, URLConnection, URLEncoder, URLStreamHandler. (Refer Section 13.3.) 3. RemoteArray, RemoteBoolean, RemoteByte, RemoteChar etc. (Refer Section 13.3) 4. getLineNumber(), getLocalVariable(), getMethodName() etc. (Refer Section 13.3) 5. addSystemThread(), close(), findClass(), freeMemory() etc. (Refer Section 13.3) Sikkim Manipal University - DDE Page No. 211 OOPS with Java Unit 14 Unit 14 Java Development Kit Structure 14.1 Introduction Objectives 14.2 Tools with JDK 14.3 Advanced Debugging Commands 14.4 Summary 14.5 Terminal Questions 14.6 Answers 14.1 Introduction In the last unit, we have discussed various Networking features of Java. In this unit, we shall discuss Java Development Kit (JDK). Java Development Kit includes the Java programming language core functionality, the Java Application Programming Interface. Objectives After studying this unit, you should be able to: explain various tools in Java Development Kit explain various advanced debugging commands 14.2 Tools in the JDK The development environment for Java is surprisingly rich, especially considering that the Java programming language is fairly new. Most of the Java developers and programmers find that the JDK contains everything they need to get started creating powerful Java programs. This is because the developer’s kit includes the Java programming language core functionality, the Java Application Programming Interface (API) complete with multiple package sets, and essential tools for creating Java programs. The Java Developer’s Kit (JDK) is currently available for most operating systems. The heart of the Java programming language is contained in a set of packages called java.lang, which is a part of the Java API. Although the java.lang package provides the core functionality of the Java programming language, it is not the only package included in the Java Developer’s Kit. Sikkim Manipal University - DDE Page No. 212 OOPS with Java Unit 14 The JDK includes the following packages: java.applet, java.awt, java.awt.image, java.awt.peer, java.io, java.lang, java.net, and java.util. These packages provide everything that needs to start creating powerful Java applications quickly. The JDK also includes an additional package called sun.tools.debug, which is designed to make the applicationdebugging process easier. The JDK includes many terrific tools that make programming in Java a joy. Using these tools user can create Java bytecode, view programs, and debug code. In the current version of the JDK, the Java interpreter and the Java compiler have been modified to load classes from zip files. Table 14.1: Tools in the JDK Executable Appletviewer Tool Name The Java applet viewer Java Javac The Java interpreter The Java compiler Javadoc The Java API documentation generator Javah The Java header and stub file generator Javap The Java class file disassemble Jdb The Java language debugger Description Used to view applets without a Web browser Runs Java bytecode Compiles Java programs into bytecode Creates API documentation in HTML format from Java source code Creates C-language header and stub files from a Java class, which allows the Java and C code to interact Disassembles Java files and prints out a representation of Java bytecode Helps to find and fix problems in Java code The appletviewer browser The Java appletviewer is used to run Java programs that require a web browser and are presented as a part of web page. Consider a commandline-argument Sikkim Manipal University - DDE Page No. 213 OOPS with Java Unit 14 appletviewer index.html When a page is loaded by appletviewer, every applet on that page will begin running in its own window. The size of these windows depends on the HEIGHT and WIDTH attributes that were set in the applet’s HTML tag. The appletviewer cannot be used to view the web page itself. The following menu options are available in appletviewer: The Restart and Reload options are used to restart the execution of an applet. The difference is that Restart option does not unload the applet before restarting it, while Reload does. Reload option is equivalent to closing the appletviewer and opening it up again on the same web page. Start and Stop option calls the start() and stop() methods of the applet. The Clone option creates a second copy of the same applet running in its own window. The Tag option displays the program’s <APPLET> tag, along with the HTML for any <PARAM> tags that configure the applet. The Info option calls the getAppletInfo() method and getParameterInfo() methods of the applet. The first method returns a string where as the second returns an array of strings which gives the name, type, and description of each parameter. The Quit option allows the user to quit the appletviewer. The Properties option allows setting access options for the applet. appletviewer Security Mechanisms The appletviewer loads local and remote applets using two different mechanisms. Applets that exist on the local file system and in a directory defined in the CLASSPATH environment variable are loaded by the file system loader. Applets downloaded from the network or that are not in the directory defined in the CLASSPATH environment variable are loaded by the applet class loader. Applets loaded by the applet class loader are subject to the restrictions of the applet security manager. The security manager adds an additional layer of security controls to un-trusted applets, which ensures that the integrity of the client machine is not compromised when accessing remote information. These security controls place restrictions on what un-trusted applets can and cannot do on the client system. Sikkim Manipal University - DDE Page No. 214 OOPS with Java Unit 14 Specifically, un-trusted applets cannot Read or write files Make directories List files in a directory Check file type, size, or modification date Start another program on the client Access other clients or IP addresses Access native code or libraries Although applets loaded by the file system loader are trusted, the appletviewer still maintains security controls over them. These security controls can be relaxed by setting property values. The property values can be set in the file called properties. This file is located in the .hotjava directory under the Java installation directory and can be edited with a plain text editor. The java Interpreter The java interpreter is used to run Java applications from the command line. It takes name of a class file as an argument. The java interpreter executes Java bytecode files. The JDK includes two versions of the interpreter. The first version, java, is optimized for normal use and has only limited debugging capabilities. The second version, java_g, is optimized for debugging and is intended for use with the Java debugger. The interpreter is run from the command line and passes the name to Java class file without the .class extension. For applications that include many classes, wants to pass the name of the class that declares the application’s main() method to the interpreter. The interpreter executes the main() method and any threads specified in the main() method. If no threads are created by the main() method, the interpreter executes the main() method and then exits. If threads are created by the main() method, the interpreter exits when the last thread exits. Because the interpreter expects the class file to contain a main() method, that interpreter cannot be used to run Java applets. Sikkim Manipal University - DDE Page No. 215 OOPS with Java Unit 14 The interpreter expects the following type of syntax: java [options] classname [args] There are two ways to specify the class file that should be run by the Java interpreter. If the class is not part of any package, it can be run by the name of the class. Consider that myresume class is a part of the com.mydata package. To run this application, the following command is used: java com.mydata.myresume Each element of the package name corresponds to its own subfolder, so the java interpreter will look for the myresume class file in several different places. The javac Compiler The javac compiler converts Java source code into one or more class files of bytecode that can be run by a Java interpreter. Java source code is stored in a file with the .java file extension. This file can be created with any text editor or word processor that can save a document without any special formatting codes. A Java source code file can contain more than one class, but only one of the classes can be declared to be public. To compile a file, the javac tool is run with the name of the file as an argument, as in the following: javac myresume.java More than one source file can be compiled by including separate filenames in command-line argument. Wildcard characters like ‘*’, ‘?’ can also be used. To compile all java files we can use command like this: javac *.java When more than one java source code files are compiled, a separate .class file will be created for each java class that compiles successfully. Another useful compiler option is –verbose. With this option, we can turn on verbose messaging and see everything the compiler and linker are doing. Sikkim Manipal University - DDE Page No. 216 OOPS with Java Unit 14 Not only will verbose messaging tells what source files are being read, but the following also can be seen: How long it took to parse each source file? When and from where the compiler is loading each class? When classes are being checked? When the class file is being written? How long it took to complete the compilation? Because the –verbose option tells what the compiler is doing to class and source files, it can be used in conjunction with the –debug option to get a complete picture of everything the compiler is doing. Multiple parameters can be passed to the compiler, but each option must precede with an hyphen. If optimization of the code has to be done the –verbose option can be used as below: javac –O –verbose QuizMaker.java The command-line syntax for the compiler is javac [options] filename.java Table 14.2: The available compiler options Option -classpath -d -debug -g -nowarn -O -verbose Description Overrides the default or current CLASSPATH environment variable setting Specifies a destination directory for class files Generates a full trace of compiler activity for methods and declarations Adds debugging information, including line numbers Turns off compiler warnings Optimizes source code by inlining static, final, and private methods Tells what the compiler is doing to class and source files The javadoc Documentation Tool Sikkim Manipal University - DDE Page No. 217 OOPS with Java Unit 14 The API Java documentation tool, javadoc takes the .java source code file or package as input and generates detailed information in HTML format. The options used with the documentation generator are –classpath, -d, and –verbose. If there is a program for which documentation is created that makes use of classes that are not stored in the current directory, then either the CLASSPATH environment variable has to be set or the –classpath option should be used. The –d option specifies the destination directory for the HTML documentation. The –verbose option turns on verbose messaging and allows the user to view what classes and source files the compiler and linker are using. The command-line syntax for the header and stub file generator is javadoc [options] sourcefile.java or javadoc [options] packagename Java has a more structured type of comment that can be read by the javadoc tool. Comments are used to describe program elements such as classes, variables, objects, and methods. It takes the following format: /** A descriptive sentence or paragraph * @tag1 description of this tag * @tag2 description of this tag */ A Java documentation comment should be placed immediately above the program element it is documenting and should explain what program element it is. The items used for the documentation purpose of the program element are called tags, which are preceded by an @ sign and are followed by a space and a descriptive sentence or paragraph. @author – program author. This tag can be used only when documenting a class, and it will be ignored unless the – author option is used when javadoc is run. @version text – program’s version number. This also restricted to class documentation, and it requires the – version option when javadoc is run. @return text – the variable or object returned by the method being documented. Sikkim Manipal University - DDE Page No. 218 OOPS with Java Unit 14 @serial text – description of the data type and possible values for a variable or object that can be serialized. @see – adds a hypertext reference to an HTML document. @param – adds a parameter to the parameters section of the document. @exception – specifies an exception a class throws. @deprecated text – a note that this class, method, object, or variable has been deprecated. This causes the javac compiler to issue a depreciation warning when the feature is used in a program that’s being compiled. @since text – a note describing when a method or feature was added to its class library. The java Header The Java C Header and Stub File Generator is an extremely useful environment tool. It is used when user need to implement native methods. C header and stub files are necessary for Java and C programs to interact. As C programmers know, header and stub files are used by C programs to reference an object’s instance variables. If the user plans to interface the Java program C or C++, user should generate header and stub files after compiling the Java source code. The JDK includes two versions of this tool. The first version, javah, is optimized for normal use and has only limited debugging capabilities. The second version, javah_g, is optimized for debugging and is intended for use with the Java debugger. Run the Java C Header and Stub File Generator from the command line and pass it the name of the Java class file without the .class extension. By default, javah creates a header file with the .h extension for each class name the programmer passes to it and stores the file in the current directory. Header files are named with the class name and the .h extension. It can be overrided this default with the –o option. The –o option lets the user specify a single output file for all generated source information. This is useful when the user has Java programs that contain multiple class files and wants to store the associated header and Sikkim Manipal University - DDE Page No. 219 OOPS with Java Unit 14 stub information in one file. As javah stores the output in the exact file as the users name, user should always specify the .h extension in the destination filename. The following example creates a header file called concat.h for a Java program that has four classes associated with it. javah –o concat.h RGBeanvas RGBcontrols HexInt RGB2Hex Generated header files contain C struct definitions, define all the variables that are needed, and create a handle for passing values back and forth between C and Java. The layout of the header file approximates the layout of the original class file with fields that correspond to instance variables. For every class in the Java program, there will be a struct definition with the package name prepended to the class name. Java replaces file path separators with the underscore character. Here are some examples: struct Hjava_awt_peer_ComponentPeer; struct Hjava_awt_Container; struct Hjava_awt_Color; Whereas header files are generated automatically, stubs options are used to create a stub file with C declarations. Stub files are named with the class name and the .c extension – in the C programming language source files named with this extension. The following option can be used: javah –stubs RGB2Hex During the generation of header and stub files, javah builds temporary files. These files are generally stored in the \tmp directory on UNIX systems and on the C:\temp directory on Windows based systems. If all classes are compiled, associated with an advanced application, these files can grow to be quite large. The user can override the default directory with the –td option, which lets the user to specify the location of the temporary directory. Specifying a new location for the temporary directory is often useful, especially if primary disk or the root partition doesn’t have a lot of free space. Sikkim Manipal University - DDE Page No. 220 OOPS with Java Unit 14 Table 14.3: The header and stub file generator options Option -classpath -d -o -stubs -td -v Description Overrides the default or current CLASSPATH environment variable setting Specifies a destination directory for header and stub files Specifies a single output file for all generated header and source information Creates stub files with C declarations in addition to the C header files Specifies a directory for temporary files and overrides the default Tells what classes and temp directory javah is using The jdb Debugger The Java Debugger, jdb, is a sophisticated tool that helps to find and fix bugs in Java programs. The Java Debugger has two features that are extremely useful while searching a bug that cannot be found by breakpoints. The debugger works by running a program using a version of the Java interpreter that it has complete control over. Before using the debugger the program has to be compiled with –g option which causes extra information to be included in the class file. While debugging an application, the jdb tool can be run with a java class as an argument. jdb myresume While running a debugger all the files should be available in the same folder which corresponds to the myresume.class and mydata.java. The debugger loads this program and displays the following message: Initializing jdb….. 0x9e:class(myresume) > The debugger is controlled by typing commands at the > prompt. Sikkim Manipal University - DDE Page No. 221 OOPS with Java Unit 14 To set a break point in a program stop statement is used. stop in myresume.mydata This command sets a breakpoint at the first line of the mydata method. No arguments or parenthesis are needed after the method name. This command sets a breakpoint at a specific line number with a class. stop at myresume:20 Breakpoints can be set in desired point within a class. To clear the breakpoints that are currently set, clear command can be used. By using the clear with a class name and line number as an argument, break points can be removed. clear myresume:200 Self Assessment Questions 1. The heart of the Java programming language is contained in a set of packages called _____, which is a part of the Java API. 2. The JDK also includes a package called _____, which is designed to make the application-debugging process easier. 3. _____ and _____ are two Java interpreters. 14.3 Advanced Debugging Commands There are some advanced commands for debugging. They are: up – moves up the stack frame so that locals and print can be used to examine the program at the point before the current method was called. down – moves down the stack frame to examine the program after the method call. In Java, chain method is entertained. One method calls another method which in turn calls another and so on. At each point Java keeps track of all the objects and variables within that scope by grouping them together. This grouping is called a stack. The various stacks in existence as a program runs are called the stack frame. Following commands can also be used while debugging: classes – lists the classes currently loaded into memory methods – lists the methods of a class memory – lists the total memory and the amount that is not currently in use Sikkim Manipal University - DDE Page No. 222 OOPS with Java Unit 14 threads – lists the threads that are executing suspend thread – suspends threads (by default all are suspended) resume thread – resume threads (by default all) where – dumps a thread’s stack threadgroups – lists the threadgroups print – prints an object locals – print all local variables in current stack frame dump – print all object information cont – continue execution from breakpoint catch <class id> - break for the specified exception ignore <class id> - ignore when the specified exception gc – free unused objects load classname – load Java class to be debugged run <class> [args] – start execution of a loaded Java class !! – repeat last command help (or ?) – list commands exit (or quit) – exit debugger Actually all the threads are numbered when an application is running. Whenever some thread has to resume it can be done through the resume command along with the thread number. Self Assessment Questions 4. The various stacks in existence as a program runs are called the _____. 5. _____ method prints all object information. 6. _____ method frees all unused objects. 14.4 Summary The JDK tools are Appletviewer, Java header Javac, Javadoc, Javap, Jdb When writing a Java application, programmer must compile the code before the interpreter can load and execute the program The interpreter is the only tool that can run a Java application. because the compiler produces Java byte-code files rather than executable files like most other compilers Sikkim Manipal University - DDE Javah, source This is regular Page No. 223 OOPS with Java Unit 14 To get a list of options supported by the interpreter, type the command javac – help Byte-code files have the .class file extension. These are the types of files that the interpreter can load and execute 14.5 Terminal Questions 1. What command starts a program that’s loaded into the debugger? 2. How to start a debugging session with jdb? 3. What does the javap tool do? 4. What are native methods? 5. How does javah helps to use native methods? 6. How to set a breakpoint with the debugger? 7. How to set a different target directory for the compiler’s output files? 8. What does the –g command line option do? 9. What does the –nowarn command line option do? 10. What does the –checksource command line option do? 14.6 Answers Self Assessment Questions 1. java.lang, 2. sun.tools.debug, 3. java, java_g 4. stack frame. 5. dump. 6. gc. Terminal Questions 1. Run command. 2. To start a debugging session with jdb, type jdb app.class, where app.class is the .class file of the application user wants to debug. 3. The javap tool is a disassembler that converts byte-code .class files into a description of the source code. 4. Native methods are methods written in a language other than Java. Sikkim Manipal University - DDE Page No. 224 OOPS with Java Unit 14 5. The javah tool helps to implement native methods by creating the header files needed to gain access to data fields in Java classes from the C source code. 6. To set a breakpoint with the debugger, type stop at class:line, where class:line is the class’s name and breakpoint line number separated by a colon. 7. –d option followed by the name of the directory is used. 8. The –g command-line option instructs the compiler to add debugging information to the byte-code files it generates. 9. The –nowarn command-line option instructs the compiler to suppress warning messages as it compiles a file. The compiler will still generate error messages. 10. The –checksource (or –cs) command-line option instructs the interpreter to recompile any source-code files that have been changed since the last compilation. Sikkim Manipal University - DDE Page No. 225 OOPS with Java Unit 15 Unit 15 Security in Java Structure 15.1 Introduction Objectives 15.2 Using Digital Signatures to identify Applets 15.3 JDK Security Tools 15.4 Working with Certificates 15.5 Summary 15.6 Terminal Questions 15.7 Answers 15.1 Introduction In the previous unit, we have discussed Java Development Kit. In this unit, we shall discuss various security mechanisms available in Java. Java was the first programming language that could be used to send interactive programs over the World Wide Web. Since these programs run on the user’s system, Java requires highly restrictive security to prevent a malicious programmer from using the language to wreak havoc on the systems of anyone who runs programs from a web page. After the launch of Java language, its core security features have been well established. Objectives After studying this unit, you should be able to: explain how digital signatures are used to identify applets explain various JDK security tools work with Certificates 15.2 Using Digital Signatures to identify Applets One of the fundamental assumptions of Java’s applet security strategy is that anything can happen at any time on the Web. Java’s security assumes that someone try to write malicious applets, so, that has to be prevented. They have anticipated the following situations: Reading files from the system the applet is running on. Writing files to the system that applet is running on. Sikkim Manipal University - DDE Page No. 226 OOPS with Java Unit 15 Getting information about a file on the system. Deleting a file on the system. Making a network connection to any machine other than the one that delivered the Web page containing the applet. Displaying a window that does not include the standard “Java applet window” warning. Java 2 makes it possible to do everything that a Java application can do – but if and only if they come from a trusted applet provider and are digitally signed to verify their authenticity. A digital signature is an encrypted file or files that accompany a program, indicating exactly from whom the file came. The document that represents this digital signature is called a Certificate. An applet provider must verify its identity using a group called a Certificate Authority. Self Assessment Questions 1. _____ was the first programming language that could be used to send interactive programs over the World Wide Web. 2. A _____ is an encrypted file or files that accompany a program, indicating exactly from whom the file came. 3. The document that represents this digital signature is called a _____. 4. An applet provider must verify its identity using a group called a _____. 15.3 JDK Security Tools Three tools are included in the JDK (Java Development Kit): Keytool, Jar and Jarsigner. Keytool Keytool, the Java security key tool, is used to create and manage public keys, private keys and security certificates. It can be used to do the following: Manages the own public key / private key pairs. Stores the public keys of people and groups which communicates with. Uses the certificates associated with these keys to authenticate the user to others. Authenticate the source and integrity of data. Sikkim Manipal University - DDE Page No. 227 OOPS with Java Unit 15 All information which are managed by keytool are stored in a database called keystore. This utility works with any key store that is stored as a file. Sun Microsystems includes a default key store that uses a new file format called JKS (Java Key Store). Keytool can work with different key stores through the use of the – keystore option. Working with Public and Private key pairs The –genkey option of keytool is used to create a new public / private key pair. There are many configuration options that can be used to retrieve, replace or delete the pair. Key store aliases are not case sensitive. If the –keystore option is not used, the key pair will be stored in the default key store on the system. Keystore option can be added like keytool –genkey – alias samplekey While working with the keys the security of the private key is essential. This key is necessary to prove the identity of a company, or other entity. If its security is compromised, the key pair cannot be used reliably any longer. There are two passwords involved in adding a key pair to a key store. The first is the key store password, which must be used to access any keys that it contains. Whenever a new key is added to the keystore it will ask for the password. The second password is one for the private key in the key pairs. If more than one key pair is going to use the same key store then each private key will have different passwords. While creating a new key pair for a new key store, password is required. While creating a new key pair, the keytool will ask a number of questions: Creators first name and last name Organizational unit Organizational name City or locality State or province Two letter country code As a group these answers are called the X.500 distinguished name of the source. Every group individual on the Internet will have a unique name. Sikkim Manipal University - DDE Page No. 228 OOPS with Java Unit 15 When a key pair is added to the default key store, then a keytool can be used. Keytool –list is used to view the key store. To delete a key pair from this database, following command is used: keytool –delete –alias aliasName aliasName represents the name of the key to delete. Keytool includes numerous command-line options to configure how a key pair is created. Some of the options are: -dname text – sets the X.500 distinguished name of the pair using the specified text. -storepass text – if the keystore does not exist, sets its password to the specified text. If it does exist, uses this password when key tool tries to access the store. -keypass text – as with –storepass, either creates or uses the specified password; depending on whether the key pair existed prior to the use of this command. -validity value – makes this key valid for the specified number of days, after which it expires and cannot be used. Self Assessment Questions 5. _____ is used to create and manage public keys, private keys and security certificates. 6. All information which are managed by keytool is stored in a database called _____. 7. Sun Microsystems includes a default key store that uses a new file format called _____. 15.4 Working with Certificates The keytool utility can display import and export certificates, in addition to key pairs. These certificates are called X.509 certificates because they follow the X.509 standard, the only one presently supported by keytool. X.509 certificates contain a digital signature and the following information: The version of the X.509 standard used by the certificate. The entity that issued the certificate – certification authority. A unique serial number generated by the certification authority, which distinguishes this certificate from all others that it has issued. Sikkim Manipal University - DDE Page No. 229 OOPS with Java Unit 15 An identifier indicating the algorithm used by the authority to create the certificate. The valid dates of the certificate. The distinguished name of the individual or group identified by the certificate. The public key of this individual or group. Certification For acquiring a certification first create a private / public key pair using the key tool. This automatically bundles the new public key with a new certificate that is signed by the same entity that created the public key. These are called self-signed certificates. But for this it is needed to create a certificate signing request. This request is created using keytool with –certreq option. The –file option is used to specify a file where the certificate signing request should be saved. The certificate signing request is simply a means of encoding the information needed by a certification authority. Once the authentication request is received, a certificate authority will follow its own procedures for verifying the identity of the person or group seeking its services. If everything is okay, the certificate authority will send back a certificate that can be used as proof of identity. This certificate is composed of a chain of different certificates. Each certificate verifies the next in the chain. When a certificate is received from an authority, it can be imported into a key store by using the –import option of the keytool. The jar Archival Tool and jarsigner The Java archival tool jar is used to package into a single archive file a Java program and all resource files that it requires. The advantage of jar tool is to speed up the loading time for an applet on the web, especially when the applet needs a group of other files in order to function. Jar is also necessary to create a digitally signed Java program. Before a Java program can be signed it must be packaged into an archive file with all class files and other files which are needed for the program to run. When a jar file is included in the program it should be signed using a jarsigner. The following two activities should be performed: Digitally signing a java archive file Sikkim Manipal University - DDE Page No. 230 OOPS with Java Unit 15 Verifying the digital signature and contents of a java archive To digitally sign a java archive file, following have to be specified i.e. a name of the jar archive and the name of the private key to sign it with. The jarsigner tool has several command-line options that are identical to those offered by keytool, including –keystore, which is used to specify the folder and the file location of a key store. The jar tool also can be used to verify a digitally signed archive by adding the –verify option to the command. If the private key matches the Java archive and the archive’s contents did not change after it was signed, it will be verified by the jarsigner. Self Assessment Questions 8. _____ is the only certificate standard, presently supported by keytool. 9. The Java archival tool _____ is used to pack into a single archive file a Java program and all resource files that it requires. 10. When a jar file is included in the program it should be signed using a _____. 15.5 Summary Java’s security tools are keytool, jarsigner and jar archive tool. Keytool can output a verbose listing of the contents of a key store using the –v option. Keytool utility can display, import and export certificates in addition to key pairs. 15.6 Terminal Questions 1. What are the various JDK security tools? 2. What is the information required while creating a new key pair using keytool? 3. What are self-signed certificates? 15.7 Answers Self Assessment Questions 1. Java. 2. Digital signature. 3. Certificate. Sikkim Manipal University - DDE Page No. 231 OOPS with Java 4. 5. 6. 7. 8. 9. 10. Unit 15 Certificate Authority. Keytool. Keystore JKS (Java Key Store). X.509 Jar Jarsigner Terminal Questions 1. Jar, Jarsigner, and Keytool. 2. Required information is a. b. c. d. e. Creators first and last name Organizational unit and name City or locality State or province Two letter country code 3. For acquiring a certification first create a private / public key pair using the key tool. This automatically bundles the new public key with a new certificate that is signed by the same entity that created the public key. These are called self-signed certificates. Sikkim Manipal University - DDE Page No. 232 OOPS with Java Unit 15 Acknowledgements, References and Suggested Readings: 1. Balaguruswamy, E. Programming with Java. 2. Flanagan, D. Java in a Nutshell. 3. Ganesan Subra, Gopal Chitra, An Introduction to Object Oriented Programming using Java, Anuradha Publications. 4. Morelli, R. Java, Java, Java: Object-Oriented Program Solving. 5. Naughton Patrick, Schildt Herbert. Java - The Complete Reference, TMH. 6. Weber Joseph. Using Java 1.2. Sikkim Manipal University - DDE Page No. 233