I – UNIT Procedure Oriented Programming

Slides:



Advertisements
Similar presentations
Understand and appreciate Object Oriented Programming (OOP) Objects are self-contained modules or subroutines that contain data as well as the functions.
Advertisements

CS0007: Introduction to Computer Programming Console Output, Variables, Literals, and Introduction to Type.
Object Oriented Programming in JAVA
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Lecture 2 Classes and objects, Constructors, Arrays and vectors.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
Data types and variables
Chapter 2 Data Types, Declarations, and Displays
C++ fundamentals.
Objectives You should be able to describe: Data Types
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
CONCEPTS OF OBJECT ORIENTED PROGRAMMING. Topics To Be Discussed………………………. Objects Classes Data Abstraction and Encapsulation Inheritance Polymorphism.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Introduction to Java Java Translation Program Structure
Copyright Curt Hill Variables What are they? Why do we need them?
Learners Support Publications Object Oriented Programming.
What is an Object? Real world objects are things that have: 1) state 2) behavior Example: your dog: 1) state – name, color, breed, sits?, barks?, wages.
9-Dec Dec-15  INTRODUCTION.  FEATURES OF OOP.  ORGANIZATION OF DATA & FUNCTION IN OOP.  OOP’S DESIGN.
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
By Mr. Muhammad Pervez Akhtar
Introduction to OOP CPS235: Introduction.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
Java-02 Basic Concepts Review concepts and examine how java handles them.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
OOP Features Object Oriented Programming Main issues in software engineering – –maintainability, reusability, portability, security, integrity, user.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
Information and Computer Sciences University of Hawaii, Manoa
Definition of the Programming Language CPRL
1. Introduction To JAVA.
Visit for more Learning Resources
JAVA MULTIPLE CHOICE QUESTION.
Working with Java.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
II – UNIT Procedure Oriented Programming
Java Primer 1: Types, Classes and Operators
Tokens in C Keywords Identifiers Constants
Object Oriented Programming
Multiple variables can be created in one declaration
Data types and variables
Fundamental of Java Programming Basics of Java Programming
Java Programming: From Problem Analysis to Program Design, 4e
Constructor Overloading
IDENTIFIERS CSC 111.
Starting JavaProgramming
Chapter 3 Introduction to Classes, Objects Methods and Strings
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Java - Data Types, Variables, and Arrays
Variables ICS2O.
Basics of ‘C’.
Object Oriented Programming
PHP.
Chapter-3 Operators.
Classes and Objects.
Principles of object – oriented programming UNIT-1 Chapter-1.
Expressions and Assignment
elementary programming
UNIT I OBJECT ORIENTED PROGRAMMING FUNDAMENTALS
Focus of the Course Object-Oriented Software Development
Chapter 2: Introduction to C++.
Chap 2. Identifiers, Keywords, and Types
OPERATORS in C Programming
OPERATORS in C Programming
Presentation transcript:

I – UNIT Procedure Oriented Programming Object Oriented Programming Paradigm Basic Concepts of OOPS Benefits of OOPS What is Java? Simple Java Program Java Tokens Variables and Constants Data Types Type conversions and Castings Array Operators Control Statements Class fundamentals Declaring Objects 16. Assigning Object References 17. Introducing Methods 18. Constructors 19. this keyword 20. Garbage Collection 21. finalize ( ) Method 22. Overloading Methods 23. Object as parameters 24. Returning Objects 25. Access Control 26. static and final keyword 27. Nested classes and Inner Class 28. Classes with Command Line arguments

PROCEDURE ORIENTED PROGRAMMING 1. In Procedural programming, Programmer combines related sequences of statements into one single place, called procedure. 2. A procedure call is used to invoke the procedure. 3. After the sequence is processed, flow of control proceeds right after the position where the call was made. 4. But the approach in oops is that classes and objects are used to model real world entity taking help of methods which performs the functions. 5. This technique is also known as Top – down programming OBJECT ORIENTED PROGRAMMING PARADIGM 1. The major objective of object oriented approach is to eliminate some of the flaws encountered in the procedural approach. 2. OOP treats data as a critical element to the program development and does not allow it to flow freely around the system. 3. It ties data more closely to the function that operate on it an protects it from unintentional modification by other functions.

4. OOP allows us to decompose a problem into a number of entities called Objects and then build data and functions (known as methods in Java) around these entities. 5. The combination of data and methods make up an object Methods Data Object = Data + Methods 6. The data of an object can be accessed only by the methods associated with that object. 7. However, methods of one object can access the methods of other object.

8. Some of the features of object oriented paradigm are: Emphasis is on data rather than procedure. Programs are divided into what are known as Objects. Data Structures are designed such that they characterize the objects. Methods that operate on the data of an object are tied together in the data structure. Data is hidden and cannot be accessed by external functions. Objects may communicate with each other through methods. New data and methods can be easily added whenever necessary. Follows bottom – up approach in program design. 9. Our definition of object oriented programming is: Object oriented programming is an approach that provides a way of modularizing programs by creating partitioned memory area for both data and function that can be used as templates for creating copies of such modules on demand.

BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING Class 2. Objects 3. Data Abstraction 4. Data Encapsulation 5. Data Hiding 6. Inheritance 7. Polymorphism 8. Dynamic Binding 9. Message Communication Class The entire set of data and code of an object can be made a user – defined data type using the concept of a class. A class may be thought of as a ‘data type’ and an object as a ‘variable’ of that data type. Once a class has been defined, we can create any number of objects belonging to that class. Each object is associated with the data of type class with which they are created. A class is thus a collection of objects of similar type. 2. Objects Objects are the basic runtime entities in an object – oriented system. They may represent a person, a place, a bank account, a table of data or any item that the program may handle. They may also represent user – defined data types such as vectors and lists. Any programming problem is analyzed in terms of objects and the nature of communication between them.

Representation of an object Person Name BasicPay Salary() Tax() Object Data Methods Representation of an object 3. Data Abstraction, 4. Data Encapsulation and 5. Data Hiding The wrapping up of data and methods into a single unit is known as encapsulation. Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world and only those methods, which are wrapped in the class, can access it, these methods provide the interface between the object’s data and the program,

This insulation of the data from direct access by the program is called data hiding. Encapsulation makes it possible for objects to be treated like ‘black boxes’, each performing a specific task without any concern for internal implementation. Data And Method Information “in” Information “out” Abstraction refers to the act of representing essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, weight and cost, and methods that operator on these attributes, They encapsulate all the essential properties of the objects that are to be created. 6. Inheritance Inheritance is the process by which objects of one class acquire the properties of objects of another class. Inheritance supports the concept of hierarchical classification. In OOP, the concept of inheritance provides the idea of reusability. This means that we can add additional features to an existing one. The new class will have the combined features of both the classes.

Thus the real appeal and power of the inheritance mechanism is that it allows the programmer to reuse a class that is almost, but not exactly, what he wants, and to tailor the class in such a way that it does not introduce any undesirable side effects into the rest of the classes. In java, the derived class is known as ‘subclass’ Bird Attributes: Feathers Lay eggs Flying Bird Non FlyingBird

7. Polymorphism Polymorphism is another important OOP concept. Polymorphism means the ability to take more than one form. For example, an operation may exhibit different behaviour in different instances. The behaviour depends upon the types of data used in the operation. For example consider the operation of addition. For two number, the operation will generate a sum. If the operands are strings, then the operation would produce a third string by concatenation. Consider the following example: Shape Draw() Circle Object Draw(circle) Box Object Draw(box) Triangle Object Draw(triangle) Polymorphism plays an important role in allowing objects having different interval structures to share the same external interface. This means that a general class of operations may be accessed in the same manner even though specific actions associated with each operation may differ. Polymorphism is extensively used in implementing inheritance.

Dynamic Binding Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at runtime. It is associated with polymorphism and inheritance. A procedure call associated with a polymorphic reference depends on the dynamic type of that reference. Message Communication An object – oriented program consists of a set of objects that communicate with each other. The process of programming in an object – oriented language, therefore, involves the following basic steps: 1. Creating classes that define objects and their behaviour 2. Creating objects from class definitions. 3. Establishing communication among objects. Objects communicate with one another by sending and receiving information much the same way as people pass messages to one another. The concept of message passing makes it easier to talk about building systems that directly model or simulate their real world counterparts.

Network of objects communicating between them

Benefits of OOPS 1. Through inheritance, we can eliminate redundant code and extend the use of existing classes. 2. We can build programs from the standard working modules that communicate with one another, rather than having to start writing the code from scratch. This leads to saving of development time and higher productivity. 3. The principle of data binding helps the programmer to build secure programs that cannot be invaded by code in other parts of the program. 4. It is possible to map objects in the problem domain to those objects in the program. 5. It is possible to have multiple objects to coexist without any interference. 6. It is easy to partition the work in a project based on objects. 7. The data – centered design approach enables us to capture more details of a model in an implementable form. 8. Object – Oriented systems can be easily upgraded from small to large systems. 9. Message passing techniques for communication between objects make the interface descriptions with external systems much simpler. 10. Software complexity can be easily managed.

Application of OOPS 1. Real – time systems. 2. Simulation and modelling. 3. Object – oriented databases. 4. Hypertext, hypermedia and expertext. 5. AI and expert systems. 6. Neural networks and parallel programming. 7. Decision support. 8. Office automation systems. 9. CIM / CAD / CAM system.

The Java Buzzwords or Java Features or Java Characteristics ■ Simple ■ Secure ■ Portable ■ Object-oriented ■ Robust ■ Multithreaded ■ Architecture-neutral ■ Interpreted ■ High performance ■ Distributed ■ Dynamic 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 a small number of clearly defined ways to accomplish a given task. 14

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 purist’s “everything is an object” paradigm and the pragmatist’s “stay out of my way” model. The object model in Java is simple and easy to extend, while simple types, such as integers, are kept as high-performance nonobjects. 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 deallocation for you. (In fact, deallocation 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 run-time 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 elegant yet sophisticated solution for multiprocess synchronization that enables you to construct smoothly running interactive systems. Java’s easy-to-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 the Java Virtual Machine in 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 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 crossplatform solutions have done so 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. “High-performance 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 intraaddress- space messaging. This allowed objects on two different computers to execute procedures remotely. Java revived these interfaces in a package called Remote Method Invocation (RMI). This feature brings an unparalleled level of abstraction to client/ server programming. Dynamic Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run time. This makes it possible to dynamically link code in a safe and expedient manner. This is crucial to the robustness of the applet environment, in which small fragments of bytecode may be dynamically updated on a running system.

What is Java? 1. It is a Pure Object Oriented Programming language. 2. Independent platform language. 3. Java a really simple, reliable, portable, and powerful language. 4. The new language Java on C and C++ but removed a number of features of C and C++. A Simple Java Program class Sample { public static void main(String args[ ]) System.out.println(“Java is Better than C and C++); }

JAVA COMPILATION PROCESS Java Source Code Java Compiler Java Byte Code (Java Class File) Java Interpreter Java Machine Code JAVA VIRTUAL MACHIN (JVM) The Java Compiler is converting from Source code into the Byte code. But java compiler is not executable code. Rather, it is byte code. Bytecode is 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.

Java Tokens Smallest individual units in a program are known as tokens. The compiler recognizes them for building up expressions and statements. A Java program is a collection of tokens, comments and white spaces. Java language includes five types of tokens. They are: 1. Reserved Keywords 2. Identifiers 3. Literals 4. Operators 5. Separators Reserved Keywords Keywords are an essential part of a language definition. They implement specific features of the language. Java language has reserved 60 words as keywords. Java keywords, combined with operators and separators according to a syntax, form definition of the Java language.

Identifiers Identifiers are programmer – designed tokens. They are used for nameing classes, methods, variables, objects, labels, packages and interfaces in a program. Java identifiers follow the following rules: 1. They can have alphabets, digits, and the underscore and dollar sign characters. 2. They must not begin with a digit. 3. Uppercase and Lowercase letters are distinct. 4. They can be of any length. Names of all public methods and instance variables start with a leading lowercase letter. Example: average sum When more than one word are used in a name, the second and subsequent words are marked with a leading uppercase letters. dayTemperature firstDayofMonth totalMarks

All private and local variables use only lowercase letters combined with underscores Example: length batch_strength All classes and interfaces start with a leading uppercase letter(and each subsequent word with a leading uppercase letter). Student HelloJava Vehicle MototCycle Variables that represent constant values use all uppercase letters and underscores between words. TOTAL F_MAX PRINCIPAL_AMOUNT

Literals Literals in java are a sequence of characters (digits, letters, and other characters) that represent constant values to be stored in variables. Java language specifies five major types of literals. They are: Integer literals Floating_point literals Character literals String literals Boolean literals Operators An operator is a symbol that takes one or more arguments and operates on them to produce a result. Arithmetic operators Relational operators Logical operators Assignment operators Increment and Decrement operators Conditional operators Bitwise operators Special operators

Separators Separators are symbols used to indicate where groups of code are divide and arranged. They basically define the shape and function of our code. Name What it is used for paraentheses() Method definitions and invocation braces { } Automatically initialized arrays brackets [ ] declare array types semicolon ; Used to separate statements comma , Used to separate variable declaration period Used to separate package name

Literals Literals in java are a sequence of characters (digits, letters, and other characters) that represent constant values to be stored in variables. Java language specifies five major types of literals. They are: Integer literals Floating_point literals Character literals String literals Boolean literals

Single Character Literals Java Literals Character Literals Boolean Literals Numeric Literals Integer Literals Real Single Character Literals String Integer Literals An Integer literal refers to a sequence of digits. There are two types of integers. Namely, Decimal integer Literals Ex: 123 -321 0 654321 - Valid Ex: 15 750 20,000 $1000 - Invalid Hexadecimal integer Literals Ex: 0X2 0X9F 0Xbcd 0x 28

are all valid real literals. Integer literals are inadequate to represent quantities that vary continuously, such as distances, height temperatures, prices and so on. These quantities are represented by numbers containing fractional par, like 17.548. Such numbers are called real (or floating point) numbers. Further examples of real literals are: 0.0083 -0.75 435.36 These numbers are shown in decimal notation, having a whole number followed by a decimal part and the fractional part, which is an integer. It is possible that the number may not have. digits before d decimal point, or digits after the decimal point. That is, 215. .95 -.71 are all valid real literals. A real literal may also be expressed in exponential (or scientific) notation. For example, the value 215.65 may be written as 2.1565e2 in exponential notation. e2 means multiply by 102. The general form is: mantissa e exponent The mantissa is either a real number expressed in decimal notation or an integer. The exponent integer with an optional plus or minus sign. The letter' e' separating the mantissa and the exponent o' be written in either lowercase or uppercase. Since the exponent causes the decimal point to 'float', t!. notation is said to represent a real number in floating-point form. Examples of legal floating-points literals are: 29

Embedded white (blank) space is not allowed in any numeric constant. Example: 0.65e4 12e-2 1.5e+5 3.18E3 -1.2E-1 Embedded white (blank) space is not allowed in any numeric constant. Exponential notation is useful for representing numbers that are either very large or very small magnitude. For example, 7500000000 may be written as 7.5E9 or 75E8. Similarly, -0.000000368, equivalent to -3.68E-7. A floating-point literal may thus comprise four parts: . a whole number . a decimal point . a fractional part . an exponent 30

There are two Boolean literal values: . true . false Boolean Literals There are two Boolean literal values: . true . false Single Character Literals A single-character literal (or simply character constant) contains a single character enclosed within a pair of single quote marks. Examples of character in the examples above constants are: ‘5’ ‘X’ ‘;’ ‘ ‘ String Literals A string literal is a sequence of characters enclosed between double quotes. The characters may be alphabets, digits, special characters and blank spaces. Examples are: “Hello C#” “2001” “WELL DONE” “?.....!” “5+3” “X” 31

Backslash Character Literal Java supports some special backslash character constants that are used in output methods. For example, ue the symbol '\n' stands for a new-line character. A list of such backs lash character literals is given in CONSTANT MEANING ‘\a’ Alert ‘\b’ Back space ‘\f’ Form feed ‘\n New – line ‘\r’ Carriage return ‘\t’ Horizontal tab ‘\v’ Vertical tab ‘\’’ Single quote ‘\\’ Backslash ‘\o’ Null ‘\’’’ Double quote 32

1. They must not begin with a digit. VARIABLE A variable is an identifier that denotes a storage location used to store a data value. Unlike constant that remain unchanged during the execution of a program, a variable may take different values at different times during the execution of the program. Every variable has a type that determines what values ca be stored in the variable. A variable name can be chosen by the programmer in a meaningful way so as to reflect what represents in the program. Some examples of variable names are: average height totaCheight classStrength As mentioned earlier, variable names may consist of alphabets, digits and the underscore ( - ), subject to the following conditions: 1. They must not begin with a digit. 2. Uppercase and lowercase are distinct. This means that the variable Total is not the same as total or TOTAL. 3. It should not be a keyword. 4. White space is not allowed. 5. Variable names can be of any length. 33

CONSTANTS Constants in Java refer to fixed values that do not change during the execution of a program. Java supports several types of constants:

Single Character Constants Java Constants Character Constants Boolean Constants Numeric Constants Integer Constants Real Single Character Constants String Integer Constants An Integer literal refers to a sequence of digits. There are two types of integers. Namely, Decimal integer Constants Ex: 123 -321 0 654321 - Valid Ex: 15 750 20,000 $1000 - Invalid Hexadecimal integer Constants Ex: 0X2 0X9F 0Xbcd 0x 35

are all valid real constants. Integer Constants are inadequate to represent quantities that vary continuously, such as distances, height temperatures, prices and so on. These quantities are represented by numbers containing fractional par, like 17.548. Such numbers are called real (or floating point) numbers. Further examples of real Constants are: 0.0083 -0.75 435.36 These numbers are shown in decimal notation, having a whole number followed by a decimal part and the fractional part, which is an integer. It is possible that the number may not have. digits before d decimal point, or digits after the decimal point. That is, 215. .95 -.71 are all valid real constants. A real literal may also be expressed in exponential (or scientific) notation. For example, the value 215.65 may be written as 2.1565e2 in exponential notation. e2 means multiply by 102. The general form is: mantissa e exponent The mantissa is either a real number expressed in decimal notation or an integer. The exponent integer with an optional plus or minus sign. The letter' e' separating the mantissa and the exponent o' be written in either lowercase or uppercase. Since the exponent causes the decimal point to 'float', t!. notation is said to represent a real number in floating-point form. Examples of legal floating-points constants are: 36

Embedded white (blank) space is not allowed in any numeric constant. Example: 0.65e4 12e-2 1.5e+5 3.18E3 -1.2E-1 Embedded white (blank) space is not allowed in any numeric constant. Exponential notation is useful for representing numbers that are either very large or very small magnitude. For example, 7500000000 may be written as 7.5E9 or 75E8. Similarly, -0.000000368, equivalent to -3.68E-7. A floating-point literal may thus comprise four parts: . a whole number . a decimal point . a fractional part . an exponent 37

There are two Boolean constant values: . true . false Single Character Constant A single-character constant (or simply character constant) contains a single character enclosed within a pair of single quote marks. Examples of character in the examples above constants are: ‘5’ ‘X’ ‘;’ ‘ ‘ String Constant A string constant is a sequence of characters enclosed between double quotes. The characters may be alphabets, digits, special characters and blank spaces. Examples are: “Hello C#” “2001” “WELL DONE” “?.....!” “5+3” “X” 38

Backslash Character Constant Java supports some special backslash character constants that are used in output methods. For example, ue the symbol '\n' stands for a new-line character. A list of such backs lash character literals is given in CONSTANT MEANING ‘\a’ Alert ‘\b’ Back space ‘\f’ Form feed ‘\n New – line ‘\r’ Carriage return ‘\t’ Horizontal tab ‘\v’ Vertical tab ‘\’’ Single quote ‘\\’ Backslash ‘\o’ Null ‘\’’’ Double quote 39

DATA TYPES Every variable in java has a data type. Data types specify the size and type of values that can be stored. Java language is rich in its data types. The variety of data types available allow the programmer to select the type appropriate to the needs of the applications. DATA TYPES IN JAVA Premitive (Intrinsic) Non – Primitive ( Derived Classes Arrays Numeric Non -Numeric Interface Integer Floating - Point Character Boolean

Integer Types Type Size Minimum Size Maximum Size byte One byte -128 short int long Type Size Minimum Size Maximum Size byte One byte -128 127 short Two byte -32,768 32, 767 int Four byte -2, 147, 483, 648 2, 147, 483, 647 long Eight byte -9, 223, 372, 036, 854, 775, 808

Floating Point Types Type Size Minimum Size Maximum Size Float 4 bytes Double Type Size Minimum Size Maximum Size Float 4 bytes 3.4e – 038 3.4e + 038 Double 8 bytes 1.7e – 308 1.7e + 308

Character Type In order to store character constants in memory. Java provides a character data type called char. The char type assumes a size of 2 bytes but, basically, it can hold only a single character Boolean Type Boolean type is used when we want to test a particular condition during the execution of the program. There are only two values that a boolean type can take: true or false. Remember, both these words have been declared as keywords. Boolean type is denoted by the keyword boolean and uses only one bit of storage.

Arithmetic Operations TYPE CONVERSION Type Conversion Casting Operations Arithmetic Operations Explicit Conversion Implicit Conversion Convert a data of one type to another before it is used in arithmetic operations or to store a value of one type into a variable of another type. Example: byte b1 = 50; byte b2 = 60; byte b3 = b1 + b2; Error: “cannot implicitly covert type int to type byte” int b3 = b1 + b2; // No Error In C#, type conversions take place in two ways 1. Implicit conversions 2. Explicit conversions 44

Some Examples of implicit conversion are: byte x1 = 75; short x2 = x1; Implicit Conversions The conversion can always be performed without any loss of data. For numeric types, this implies that the destination type can fully represent the range of the source type. For example, a short can be converted implicitly to an int, because the short range is a subset of the int range. Therefore, short b = 75; int a = b; C# does the conversion automatically. An implicit conversion is also known as automatic type conversion. The process of assigning a smaller type to a larger one is known as widening or promotion. Some Examples of implicit conversion are: byte x1 = 75; short x2 = x1; int x3 = x2; long x4 = x3; float x5 = x4; decimal x6 = x4; 45

Java Conversion hierarchy chart 8 – bit types byte 16 – bit types short char 32 – bit types int long 64 – bit types float double 46

type variable1 = (type) variable2 Explicit Conversions The process of assigning a larger type to a smaller one is known as norrowing. The norrowing may result in loss of information. There are many conversions that cannot be implicitly made between types. If we attempt such conversions, the compiler will give an error message. For example, the following conversions cannot be made implicitly: int to short int to long long to int float to int decimal to any numeric type any numeric type to char However, we can explicitly carry out such conversions using the ‘cast’ operator. The process is known as casting and is done as follows: type variable1 = (type) variable2 47

Automatic Type Promotion in Expressions Example: int m = 50; byte n = (byte) m; long x = 1234L; int y = (int) x; float f = 50.0F long y = (long) f; Automatic Type Promotion in Expressions In addition to assignments, there is another place where certain type conversions may occur: in expressions. To see why, consider the following. In an expression, the precision required of an intermediate value will sometimes exceed the range of either operand. For example, examine the following expression: byte a = 40; byte b = 50; byte c = 100; int d = a * b / c; The result of the intermediate term a * b easily exceeds the range of either of its byte operands. To handle this kind of problem, Java automatically promotes each byte or short operand to int when evaluating an expression. This means that the subexpression a * b is performed using integers—not bytes. Thus, 2,000, the result of the intermediate expression, 50 * 40, is legal even though a and b are both specified as type byte. As useful as the automatic promotions are, they can cause confusing compile-time errors. For example, this seemingly correct code causes a problem: b = b * 2; // Error! Cannot assign an int to a byte! 48

The Type Promotion Rules The code is attempting to store 50 * 2, a perfectly valid byte value, back into a byte variable. However, because the operands were automatically promoted to int when the expression was evaluated, the result has also been promoted to int. Thus, the result of the expression is now of type int, which cannot be assigned to a byte without the use of a cast. This is true even if, as in this particular case, the value being assigned would still fit in the target type. In cases where you understand the consequences of overflow, you should use an explicit cast, such as byte b = 50; b = (byte)(b * 2); which yields the correct value of 100. The Type Promotion Rules In addition to the elevation of bytes and shorts to int, Java defines several type promotion rules that apply to expressions. They are as follows. First, all byte and short values are promoted to int, as just described. Then, if one operand is a long, the whole expression is promoted to long. If one operand is a float, the entire expression is promoted to float. If any of the operands is double, the result is double. The following program demonstrates how each value in the expression gets promoted to match the second argument to each binary operator:

class Promote { public static void main(String args[]) byte b = 42; char c = 'a'; short s = 1024; int i = 50000; float f = 5.67f; double d = .1234; double result = (f * b) + (i / c) - (d * s); System.out.println((f * b) + " + " + (i / c) + " - " + (d * s)); System.out.println("result = " + result); }

OPERATORS 51

Subtraction or Unary Minus C# supports a rich set of operators. Arithmetic operators Relational operators Logical operators Assignment operators Increment and Decrement operators Conditional operators Bitwise logical operators Special operators ARITHMETIC OPERATORS Integer Arithmetic a % b equivalent to a – ( a / b ) * b -14 % 3 = -2 -14 % -3 = -2 -14 % -3 = 2 Real Arithmetic Mixed – Mode Arithmetic Ex: 15 / 10.0 produces the result 1.5 15 / 10 produces the result 1 Operator Meaning + Addition or Unary plus - Subtraction or Unary Minus * Multiplication / Division % Modulo Division 52

Is greater than or equal to RELATIONAL OPERATOR LOGICAL OPERATOR Operator Meaning < Is less than <= Is less than or equal to > Is greater than >= Is greater than or equal to == Is equal to != Is not equal to Operator Meaning && Logical AND || Logical OR ! Logical NOT BITWISE LOGICAL OPERATOR C# supports operators that may be used for manipulation of data at bit level. These operators may be used for testing the bits or shifting them to the right or left. Bitwise operators may not be applied to floating – point data. Operator Meaning & Bitwise Logical AND | Bitwise Logical OR ^ Bitwise Logical XOR ~ One’s Complement << Left Shift >> Right Shift 53

Bitwise Complement ( ~ ) Variable Value Binary Pattern X 23 0 0 0 1 0 1 1 1 ~X 132 1 1 1 0 1 0 0 0 Y FF 1 1 1 1 1 1 1 1 ~Y 00 0 0 0 0 0 0 0 0 Shift Operations Left Shift Variable Value Binary Pattern X 33 0 0 1 0 0 0 0 1 (8 bits) X << 3 the bit pattern of X value is left shifted by thrice. 0 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 0 0 0 The Resultant bit pattern will be 0 0 0 0 1 0 0 0 54

Variable Value Binary Pattern Y 41 0 0 1 0 1 0 0 1 Right Shift Variable Value Binary Pattern Y 41 0 0 1 0 1 0 0 1 Y>>3 the bit pattern of the Y value is right shifted by thrice. 0 0 1 0 1 0 0 1 0 0 0 1 0 1 0 0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 1 0 The Resultant bit pattern will be 0 0 0 0 0 1 0 1 Bitwise Logical AND Bitwise Logical OR Bitwise Exclusive OR Variable Value Binary Pattern X 5 0 1 0 1 Y 2 0 0 1 0 X & Y 0 0 0 0 A 6 0 1 1 0 B 3 0 0 1 1 A & B Variable Value Binary Pattern X 5 0 1 0 1 Y 2 0 0 1 0 X | Y 7 0 1 1 1 A 6 0 1 1 0 B 1 0 0 0 1 A & B Variable Value Binary Pattern X 5 0 1 0 1 Y 2 0 0 1 0 X ^ Y 7 0 1 1 1 A 6 0 1 1 0 B 3 0 0 1 1 A ^ B 55

op - is the binary operator v op= exp is equivalent to v = v op(exp); Assignment Operator Assignment operators are used to assign the value of an expression to a variable. C# has a set of ‘shorthand’ assignment operators which are used in the form v op= exp v - is the variable exp - is the expression op - is the binary operator v op= exp is equivalent to v = v op(exp); Ex: x + = y + 1; is equivalent to x = x + (y +1) Advantages: . What appears on the left – hand side need not be repeated and therefore it becomes easier to write. . The statement is more concise and easier to read. . The use of shorthand operators results in a more efficient code. 56

Increment and Decrement Operator The operators are ++ and - - ++ means Increment Operator - - means Decrement Operator The operator ++ adds 1 to the operand while – subtracts 1. Both are unary operators and are used in the following form: ++m; or m++ --m or m— ++m; is equivalent to m = m + 1 (or m + = 1;) --m; is equivalent t o m = m – 1 (or m - = 1;) We use the increment and decrement operators extensively in for and while loops For Example: Case 1 m = 5; y = ++m; The statement a [ i ++ ] = 10; is equivalent to a [ i ] = 10; i = i + 1; Case 2 m = 5; y = m--; 57

Special Operators Conditional Operator It is also known as Ternary operator Syntax: exp_1? exp_2: exp_3 Special Operators Instanceof Operator The instanceof is an object reference operator and returns true if the object on the left – hand side is an instance of the class given on the right – hand side. This operator allows us to determine whether the object belongs to a particular class or not. Example: person instanceof student Dot Operator The dot operator (.) is used to access the instance variables and methods of class objects. person1.age //Reference to the variable age person1.salary( ) //Reference to the method salary( ) 58

DECISION MAKING – BRANCHING and LOOPING 59

Decision making with IF statement 1. Simple if statement 2. if… else statement 3. Nested if…else statement 4. else if ladder Simple if statement if (Boolean-expression) { Statement-block } Statement – x if…else statement if (Boolean-expression) { True-block statement(s) } else Flase-block statement(s) Statement-x; 60

Nesting if…else statement if (Boolean-expression) { True-block statement(S) True-block Statement(s) } else False-block Statement(s) False-block statement(s) 61

Default-Statement-x; else if Ladder if (condition_1) Statement_1; else if (condition_2) Statement_2; else if (condition_3) Statement_3; . else if (condition_n) Statement_n; else Default-Statement-x; 62

THE SWITCH STATEMENT switch (expression) { case value_1: block_1; break; case value_2: block_2; case value_3: block_3; --------------- default: default_block } Statement_x; 63

DECISION MAKING AND LOOPING The C# language provides for four constructs for performing loop operations. They are: The while statement The do statement The for statement The do statement Syntax: initialization do { Body of the Loop } while (test_condition); The while statement Syntax: initialization; while(test_condition) { Body of the Loop } The for statement Syntax: for (initialization;test_condition;increment) { Body of the Loop } 64

Case 6: for (j = 1000; j>0; j = j – 1); Case 7: Additional Features of the for Loop Case 1: p = 1; for (n = 0; n<17;++n) can be rewritten as for (p=1,n=0;n<17;++n) Case 2: for (n=1,m=50;n<=m; n=n+1,m=m-1) { ---------- } Case 3: sum = 0; for ( i =1, i<20 && sum <100; i++) ----------- Case 4: for (x = (m+n)/2; x>0;x = x/2) Case 5: --------- m = 5; for (;m != 100;) System.out.println(m); m = m + 5; -------- Case 6: for (j = 1000; j>0; j = j – 1); Case 7: for (j = 1000;j>0; j= j-1); 65

Jumps in Loops break; continue; goto; class Gobreakcontinue { public static void main(String args[ ] ) for (int i = 1;i< 100;i++) System.out.println( “ “); if (i >= 10) Break; for(int j = 1;j<100;j++) System.out.println(“ * “); if (j == i) goto loop1; } loop: continue; System.out.println(“Termination by BREAK”); 66

ARRAY 67

3. Multi Dimensional Array Array is collection of homogenous Data items. Array is classified into three types. 1. One Dimensional Array 2. Two Dimensional Array 3. Multi Dimensional Array One Dimensional Array Two Dimensional Arrays X Y 68

Multidimensional Arrays X Z Creating an Array 1. Declaring the array 2. Creating memory locations 3. Putting values into the memory locations. 1. Declaration of Arrays Syntax: type [ ] arrayname; Example: int [ ] counter; float [ ] marks; int [ ] x,y; 69

2. Creating memory locations Syntax: arrayname = new type [size]; Examples: number = new int [5]; average = new float [10]; 3. Declaration and Creation in one step Syntax: type [ ] arrayname = new type [size]; Examples: int [ ] number = new int [5]; 4. Initialization of Arrays Syntax: type [ ] arrayname = {list of values}; Example: int [ ] number = {32,45,34,56,34}; int [ ] number = new int [3] {10,20,30}; 70

class NumberSorting { public static void main(String args[]) int number[] = {55,40,80,65,71}; int n = number.length; System.out.println("Given List"); for(int i = 0;i<n;i++) System.out.println(" " + number[i]); } System.out.print("\n"); for(int i = 0;i < n; i++) for(j = 1;j < n; j++) if (number[i] < number [j]) int temp = number[i]; number[i] = numbdf[j]; number[j] = temp;

System.out.println("Sorted list:"); for(int i = 0;i < n;i++) { System.out.println(" " + number[i]); } System.out.println(" ");

Two Dimensional Array Case: It is possible to assign an array object to another. Ex: int [ ] a = {1,2,3}; int [ ] b; b = a; Two Dimensional Array Declaration for the Two Dimensional Array int [ ][ ] myArray; myArray = new int[3,4]; OR int [ ][ ] myArray = new int[3,4]; int[ ][ ] table = {{0,0,0},{1,1,1}}; 73

class MultiTable { final static int ROWS = 20; final static int COLUMNS = 20; public static void main(String args[]) int product[][] = new int[ROWS][COLUMNS]; int row,column; System.out.println("Multiplication Table"); System.out.println(" "); int i,j; for(i=10;i<ROWS;i++) for(j=10;j<COLUMNS;j++) product[i][j] = i * j; System.out.println(" " + product[i][j]); }

int [ ] [ ] x = new int [3] [ ]; //Three rows array Variable – Size Arrays Variable – Size array is called Array of Array or Nested Array or Jagged Array Ex: int [ ] [ ] x = new int [3] [ ]; //Three rows array x [0] = new int [2] //First Rows has two elements x [1] = new int [4] //Second Rows has four elements x [2] = new int [3] //Third Rows has three elements x[0] x[1] x[2] x[0] [1] x[1] [3] x[2] [2] 75

public static void main(String args[ ]) public class MyArrayc2 { public static void main(String args[ ]) BufferedReader br = new BufferedRead(new InputStreamReader(System.in)) int [ ][ ]arr=new int[4][ ]; arr[0]=new int[3]; arr[1]=new int[2]; arr[2]=new int[5]; arr[3]=new int[4]; System.out.println("Enter the numbers for Jagged Array"); for(int i=0 ; i < arr.Length ; i++) for(int x=0 ; x < arr[i].Length ; x++) String st= br.readLine(); int num=Integer.parseInt(st); arr[i][x]=num; } 76

System.out.println("Printing the Elemnts"); for(i=0 ; i < arr.Length ; i++) { for(y=0 ; y < arr[i].Length ; y++) System.out.println(arr[x][y]); System.out.println("\0"); } 77

CLASS FUNDAMENTALS

The General Form of a Class When you define a class, you declare its exact form and nature. You do this by specifying the data that it contains and the code that operates on that data. While very simple classes may contain only code or only data, most real-world classes contain both. As you will see, a class’ code defines the interface to its data. A class is declared by use of the class keyword. The classes that have been used up to this point are actually very limited examples of its complete form. Classes can (and usually do) get much more complex. The general form of a class definition is shown here: class classname { type instance-variable1; type instance-variable2; // ... type instance-variableN; type methodname1(parameter-list) // body of method } type methodname2(parameter-list) type methodnameN(parameter-list)

// APPLICATION OF CLASSES AND OBJECTS using System; class Rectangle { public int length, width; public void GetData(int x,int y) length = x; width = y; } public int RectArea () int area = length * width; return (area); class RectArea public static void Main() int area1,area2; Rectangle rect1 = new Rectangle (); Rectangle rect2 = new Rectangle (); rect1.length = 15; rect1.width = 10; area1 = rect1.length * rect1.width ; rect2.GetData (20,10); area2 = rect2.RectArea (); System.out.println("Area1 = " + area1); System.out.println("Area2 = " + area2);

Assigning Object Reference Variables Object reference variables act differently than you might expect when an assignment takes place. For example, what do you think the following fragment does? Box b1 = new Box(); Box b2 = b1; You might think that b2 is being assigned a reference to a copy of the object referred to by b1. That is, you might think that b1 and b2 refer to separate and distinct objects. However, this would be wrong. Instead, after this fragment executes, b1 and b2 will both refer to the same object. The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer to the same object as does b1. Thus, any changes made to the object through b2 will affect the object to which b1 is referring, since they are the same object. This situation is depicted here: Although b1 and b2 both refer to the same object, they are not linked in any other way. For example, a subsequent assignment to b1 will simply unhook b1 from the original object without affecting the object or affecting b2. For example: Box b1 = new Box(); Box b2 = b1; // ... b1 = null; Here, b1 has been set to null, but b2 still points to the original object.

ADDING METHODS class Box { double width; double height; double depth; // display volume of a box void volume() System.out.print("Volume is "); System.out.println(width * height * depth); } class BoxDemo3 public static void main(String args[] Box mybox1 = new Box(); Box mybox2 = new Box();

// assign values to mybox1's instance variables mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // display volume of first box mybox1.volume(); // display volume of second box mybox2.volume(); }

Returning a Value class Box { double width; double height; double depth; // compute and return volume double volume() return width * height * depth; } class BoxDemo4 public static void main(String args[]) Box mybox1 = new Box(); Box mybox2 = new Box(); double vol;

// assign values to mybox1's instance variables mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); }

Adding a Method That Takes Parameters class Box { double width; double height; double depth; // compute and return volume double volume() return width * height * depth; } // sets dimensions of box void setDim(double w, double h, double d) width = w; height = h; depth = d;

class BoxDemo5 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // initialize each box mybox1.setDim(10, 20, 15); mybox2.setDim(3, 6, 9); // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); }

Constructors class Box { double width; double height; double depth; // This is the constructor for Box. Box() System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } // compute and return volume double volume() return width * height * depth;

class BoxDemo6 { public static void main(String args[]) // declare, allocate, and initialize Box objects Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); }

Parameterized Constructors class Box { double width; double height; double depth; // This is the constructor for Box. Box(double w, double h, double d) width = w; height = h; depth = d; } // compute and return volume double volume() return width * height * depth;

class BoxDemo7 { public static void main(String args[]) // declare, allocate, and initialize Box objects Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(3, 6, 9); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); }

The this Keyword Garbage Collection Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword. this can be used inside any method to refer to the current object. That is, this is always a reference to the object on which the method was invoked. You can use this anywhere a reference to an object of the current class’ type is permitted. To better understand what this refers to, consider the following version of Box( ): // A redundant use of this. Box(double w, double h, double d) { this.width = w; this.height = h; this.depth = d; } Garbage Collection Since objects are dynamically allocated by using the new operator, you might be wondering how such objects are destroyed and their memory released for later reallocation. In some languages, such as C++, dynamically allocated objects must be manually released by use of a delete operator. Java takes a different approach; it handles deallocation for you automatically. The technique that accomplishes this is called garbage collection.

The finalize( ) Method The constructor method is used to initialize an object when it is declared. This process is known as initalisation. Similarly, Java supports a concept called finalization, which is just opposite to initialization. We know that java run – time is an automatic garbage collecting system. It automatically frees up the memory resources used by the objects. But objects may hold other non – object resources such as file descriptors or window system fonts. The garbage collector cannot free these resources. In order to free resources we must use a finaliser method. This is similar to destructor in C++. The finalize( ) method has this general form: protected void finalize( ) { // finalization code here }

Overloading Methods class OverloadDemo { void test() System.out.println("No parameters"); } // Overload test for one integer parameter. void test(int a) System.out.println("a: " + a); // Overload test for two integer parameters. void test(int a, int b) System.out.println("a and b: " + a + " " + b); // overload test for a double parameter double test(double a) System.out.println("double a: " + a); return a*a;

class Overload { public static void main(String args[]) OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); }

Overloading Constructors class Box { double width; double height; double depth; // 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; class OverloadCons public static void main(String args[]) // create boxes using the various constructors Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); double vol;

// get volume of first box vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); // get volume of cube vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); }

Using Objects as Parameters // Objects may be passed to methods. class Test { int a, b; Test(int i, int j) a = i; b = j; } // return true if o is equal to the invoking object boolean equals(Test o) if(o.a == a && o.b == b) return true; else return false; class PassOb public static void main(String args[]) Test ob1 = new Test(100, 22); Test ob2 = new Test(100, 22); Test ob3 = new Test(-1, -1); System.out.println("ob1 == ob2: " + ob1.equals(ob2)); System.out.println("ob1 == ob3: " + ob1.equals(ob3));

Returning Objects // Returning an object. class Test { int a; Test(int i) a = i; } Test incrByTen() Test temp = new Test(a+10); return temp; class RetOb public static void main(String args[]) Test ob1 = new Test(2); Test ob2; ob2 = ob1.incrByTen(); System.out.println("ob1.a: " + ob1.a); System.out.println("ob2.a: " + ob2.a); ob2 = ob2.incrByTen(); System.out.println("ob2.a after second increase: “ + ob2.a);

Access Specifier Accessing Level ACCESS CONTROL Access Specifier Accessing Level private Same Class in Same Package private protected Sub Class in Same Package friendly (not a keyword Non – Sub Class in Same Package protected Sub Class in Other Package public Other Class in Other Package class Test { int a; // default access public int b; // public access private int c; // private access // methods to access c void setc(int i) // set c's value c = i; } int getc() // get c's value return c; } }

class AccessTest { public static void main(String args[]) Test ob = new Test(); // These are OK, a and b may be accessed directly ob.a = 10; ob.b = 20; // This is not OK and will cause an error // ob.c = 100; // Error! // You must access c through its methods ob.setc(100); // OK System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc()); }

Understanding static There will be times when you will want to define a class member that will be used independently of any object of that class. Normally a class member must be accessed only in conjunction with an object of its class. However, it is possible to create a member that can be used by itself, without reference to a specific instance. To create such a member, precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. You can declare both methods and variables to be static. The most common example of a static member is main( ). main( ) is declared as static because it must be called before any objects exist. Instance variables declared as static are, essentially, global variables. When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable. Methods declared as static have several restrictions: ■ They can only call other static methods. ■ They must only access static data. ■ They cannot refer to this or super in any way.

Public class stat { Int rollno; String name; Static string college =“SRM”; Stat(int r,string n) Rollno=r; Name=n; } Void display()]{ System.out.println(rollno+” ”+name+” “+college); Public static void main(String a[]) Stat s1=new stat(111,”Deepa”); Stat s2=new stat(222,”Jothi”); S1.dispaly(); S2.dispaly();

Nested and Inner Classes It is possible to define a class within another class; such classes are known as nested classes. The scope of a nested class is bounded by the scope of its enclosing class. Thus, if class B is defined within class A, then B is known to A, but not outside of A. A nested class has access to the members, including private members, of the class in which it is nested. However, the enclosing class does not have access to the members of the nested class. There are two types of nested classes: static and non-static. A static nested class is one which has the static modifier applied. Because it is static, it must access the members of its enclosing class through an object. That is, it cannot refer to members of its enclosing class directly. Because of this restriction, static nested classes are seldom used. The most important type of nested class is the inner class. An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do. Thus, an inner class is fully within the scope of its enclosing class.

// Demonstrate an inner class. class Outer { int outer_x = 100; void test() Inner inner = new Inner(); inner.display(); } // this is an inner class class Inner void display() System.out.println("display: outer_x = " + outer_x); class InnerClassDemo public static void main(String args[]) Outer outer = new Outer(); outer.test(); } }

Using Command-Line Arguments Sometimes you will want to pass information into a program when you run it. This is accomplished by passing command-line arguments to main( ). A command-line argument is the information that directly follows the program’s name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy—they are stored as strings in the String array passed to main( ). For example, the following program displays all of the command-line arguments that it is called with: // Display all command-line arguments. class CommandLine { public static void main(String args[]) for(int i=0; i<args.length; i++) System.out.println("args[" + i + "]: " + args[i]); } Try executing this program, as shown here: java CommandLine this is a test 100 -1 When you do, you will see the following output: args[0]: this args[1]: is args[2]: a args[3]: test args[4]: 100 args[5]: -1

II – UNIT Inheritance Inheritance with Super Keyword Inheritance with Method Overriding Inheritance with Abstract Class Inheritance with Final Keyword Interfaces Packages String Functions StringBuffer Functions

INHERITANCE

INHERITANCE A B What is Inheritance? Inheritance is the mechanism which allows a class B to inherit properties/characteristics- attributes and methods of a class A. We say “B inherits from A". A Super Class or Base Class or Parent Class B Sub Class or Derived Class or Child Class What are the Advantages of Inheritance 1. Reusability of the code. 2. To Increase the reliability of the code. 3. To add some enhancements to the base class.

Inheritance achieved in two different forms 1. Classical form of Inheritance 2. Containment form of Inheritance Classical form of Inheritance We can now create objects of classes A and B independently. Example: A a; //a is object of A B b; //b is object of B A Super Class or Base Class or Parent Class B Sub Class or Derived Class or Child Class

In Such cases, we say that the object b is a type of a In Such cases, we say that the object b is a type of a. Such relationship between a and b is referred to as ‘is – a’ relationship Example 1. Dog is – a type of animal 2. Manager is – a type of employee 3. Ford is – a type of car Animal Horse Dog Lion

Containment Inheritance We can also define another form of inheritance relationship known as containership between class A and B. Example: class A { -------- } class B --------- A a; // a is contained in b B b; ------------

In such cases, we say that the object a is contained in the object b In such cases, we say that the object a is contained in the object b. This relationship between a and b is referred to as ‘has – a’ relationship. The outer class B which contains the inner class A is termed the ‘parent’ class and the contained class A is termed a ‘child’ class. Example: 1. car has – a radio. 2. House has – a store room. 3. City has – a road. Car object Radio object

1. Single Inheritance (Only one Super Class and One Only Sub Class) Types of Inheritance 1. Single Inheritance (Only one Super Class and One Only Sub Class) 2. Multilevel Inheritance (Derived from a Derived Class) 3. Hierarchical Inheritance (One Super Class, Many Subclasses) 1. Single Inheritance (Only one Super Class and Only one Sub Class) A B

2. Multilevel Inheritance (Derived from a Derived Class) B C 4. Hierarchical Inheritance (One Super class, Many Subclasses) A B C D

Single Inheritance (Only one Super Class and One Only Sub Class) class Room { protected int length, breadth; Room() length = 10; breadth = 20; } void Room_Area() System.out.println("The Area of the Room is:" + (length * breadth)); class HallRoom extends Room int height; HallRoom() length = 10; breadth = 20; height = 30; void HallRoom_Volume() System.out.println("The Valoume of the HallRoom is:" + (length * breadth * height));

class MainRoom { public static void main(String [] args) HallRoom hr = new HallRoom(); hr.Room_Area(); hr.HallRoom_Volume(); }

Multilevel Inheritance (Derived from a Derived Class) class Room { protected int length, breadth; Room() length = 10; breadth = 20; } void Room_Area() System.out.println("The Area of the Room is:" + (length * breadth)); class HallRoom extends Room int height; HallRoom() length = 10; breadth = 20; height = 30; void HallRoom_Volume() System.out.println("The Volume of the HallRoom is:" + (length * breadth * height));

class BedRoom extends HallRoom { int height_1; BedRoom() length = 10; breadth = 20; height = 30; height_1 = 40; } void BedRoom_Volume1() System.out.println("The Volume of the the BedRoom is:" + (length * breadth * height * height_1)); class MainRoom public static void main(String [] args) BedRoom br = new BedRoom(); br.Room_Area(); br.HallRoom_Volume(); br.BedRoom_Volume1();

Hierarchical Inheritance (One Super Class, Many Subclasses) class Room { protected int length, breadth, height; Room() length = 10; breadth = 20; height = 30; } class HallRoom extends Room void HallRoom_Area() System.out.println("The Area of the HallRoom is:" + (length * breadth));

class BedRoom extends Room { void BedRoom_Volume() System.out.println("The Volume of the BedRoom is:" + (length * breadth * height)); } class MainRoom public static void main(String [] args) HallRoom hr =new HallRoom(); BedRoom br = new BedRoom(); hr.HallRoom_Area(); br.BedRoom_Volume();

INHERITANCE WITH super KEYWORD

The purpose of the ‘super’ keyword: 1. Using super to call Superclass Constructors 2. Using super to call Superclass Methods Using super to Call Superclass Constructor 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 parameter needed by the constructor in the superclass, super() must always be the first statement executed inside a subclass constructor. Restriction of the Subclass constructor 1. super may only be used within a subclass constructor method. 2. The call to superclass constructor must appear as the first statement within the subclass constructor 3. The parameters in the super call must match the order and type of the instance variable declared in the superclass.

class Room { protected int length, breadth, height; Room(int length, int breath) this.length = length; this.breadth = breath; } void Room_Area() System.out.println("The Area of the Room is:" + (length * breadth)); class HallRoom extends Room int height; HallRoom(int length, int breath, int height) super(length,breath); this.height = height; void HallRoom_Volume() System.out.println("The Volume of the HallRoom is:" + (length * breadth * height));

class MainRoom { public static void main(String [] args) HallRoom hr =new HallRoom(10,20,30); hr.Room_Area(); hr.HallRoom_Volume(); }

//super keyword in Multilevel Inheritance class Room { protected int length, breadth, height; Room(int length, int breath) this.length = length; this.breadth = breath; } void Room_Area() System.out.println("The Area of the Room is:" + (length * breadth)); class HallRoom extends Room int height; HallRoom(int length, int breath, int height) super(length,breath); this.height = height; void HallRoom_Volume() System.out.println("The Volume of the HallRoom is:" + (length * breadth * height));

class BedRoom extends HallRoom { int height_1; BedRoom(int length, int breath, int height, int height_1) super(length,breath,height); this.height_1 = height_1; } void BedRoom_Volume_1() System.out.println("The Volume 1 of the BedRoom is:" + (length * breadth * height * height_1)); class MainRoom public static void main(String [] args) BedRoom br =new BedRoom(10,20,30,40); br.Room_Area(); br.HallRoom_Volume(); br.BedRoom_Volume_1();

2. Using super to Call Superclass Method //super keyword call Super Class Methods class Room { void Room_Super() System.out.println("The Room Base is Displayed"); } class HallRoom extends Room void HallRoom_Intermetiate() System.out.println("The Hall Room is Displayed"); class BedRoom extends HallRoom void BedRoom_Sub() super.Room_Super(); super.HallRoom_Intermetiate(); System.out.println("The Bed Room is Displayed"); class MainRoom public static void main(String [] args) BedRoom br = new BedRoom(); br.BedRoom_Sub(); } }

Inheritance with Method Overriding

1. Method overriding in java means a subclass method overriding a super 2. Superclass method should be non-static. 3. Subclass uses extends keyword to extend the super class. 4. In the example class B is the sub class and class A is the super class. 5. In overriding methods of both subclass and superclass possess same signatures. 6. Overriding is used in modifying the methods of the super class. 7. In overriding return types and constructor parameters of methods should match.

//Method Overriding class Room { void Room_Super() System.out.println("The Room Base is Displayed"); } class HallRoom extends Room System.out.println("The Sub Class Room Base is Displayed"); class MainRoom public static void main(String [] args) HallRoom br = new HallRoom(); br.Room_Super(); } O/P: The Sub Class Room Base is Displayed

Super Keyword in Method Overriding If your method overrides one of its super class's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). //Super keyword in Method Overriding class Room { void Room_Super() System.out.println("The Room Base is Displayed"); } class HallRoom extends Room System.out.println("The Sub Class Room Base is Displayed"); super.Room_Super(); class MainRoom public static void main(String [] args) HallRoom br = new HallRoom(); br.Room_Super(); } O/P: The Sub Class Room Base is Displayed } The Room Base is Displayed

Inheritance with Abstract Class

abstract type name (parameter – list) Abstract Class You can require that certain methods be overridden by subclasses by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the super class . Thus, a subclass must override them – it cannot simply use the version defined in the superclass. To declare an abstract method, use this general form: abstract type name (parameter – list) Any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract, you simply use the abstract keyword in from of the class keyword at the beginning of the class declaration. Conditions for the Abstract Class 1. We cannot use abstract classes to instantiate objects directly. For example. Shape s = new Shape(); is illegal because shape is an abstract class. 2. The abstract methods of an abstract class must be defined in its subclass. 3. We cannot declare abstract constructors or abstract static methods.

//Abstract Class Implementation abstract class A { abstract void callme( ); // Abstract Method void callmetoo( ) // Concrete Method System.out.println("This is a Concrete method"); } class B extends A void callme( ) //Redefined for the Abstract Method System.out.println("B's Implementation of Callme"); class MainRoom public static void main(String [] args) B b = new B( ); b.callme( ); b.callmetoo( ); } } O/P: B's Implementation of Callme This is a Concrete method

Inheritance with final Keyword

What is the purpose of final keyword? 1. Can’t initialize to variable again and again (Equivalent to Constant) 2. Can’t Method Overriding 3. Can’t Inherited 1. Can’t initialize to variable again and again (Equivalent to Constant) class Final { public static void main(String args[]) final int a = 45; a = 78; //cannot assign the value to final Variable System.out.println("The A Value is:" + a); }

2. Can’t Method Overriding class Super { final void Super_Method() System.out.println("This is Super Method"); } class Sub extends Super //Super method in sub cannot override Super_Method() in super; Overridden //method is final void Super_Method() System.out.println("This is Sub Method"); class Final public static void main(String args[]) Sub s = new Sub(); s.Super_Method();

3. Can’t Inherited final class Super { void Super_Method() System.out.println("This is Super Method"); } class Sub extends Super //cannot inherit from final super System.out.println("This is Sub Method"); class Final public static void main(String args[]) Sub s = new Sub(); s.Super_Method();

Interface

Why are you using Interface? 1. Java does not support multiple inheritances. That is, classes in java cannot have more than one superclass. For instances, 2. a is not permitted in Java. However, the designers of java could not overlook the importance of multiple inheritances. 3. A large number of real life applications require the use of multiple inheritances whereby we inherit methods and properties from several distinct classes. 4. Since C++ like implementation of multiple inheritances proves difficult and adds complexity to the language, Java provides an alternate approach known as interfaces to support the concept of multiple inheritances. 5. Although a java class cannot be a subclass or more than one superclass, it can implement more than one interface, thereby enabling us to create classes that build upon other classes without the problems created by multiple inheritances. class A extends B extends C { ------------------- }

Defining Interfaces An interface is basically a kind of class. Like classes, interfaces contain methods and variables but with major difference. The difference is that interfaces define only abstract methods and final fields. This means that interfaces do not specify any code to implement these methods and data fields contain only constants. Syntax: interface Interface_name { Variable declaration; Method declaration; } Ex: interface Item { static final int code = 1001; static final String name = “CCET”; void display (); } Ex: interface Area { final static float pi = 3.142F; float compute (float x,float y); void show(); }

How to Interface implements to the Classes Syntax: class class_name implements interface_name { //Member of the Classes //Definition of the Interfaces } Ex: interface student { int slno = 12345; String name = "CCET"; void print_details(); } class Inter_Def implements student void print_details() System.out.println("The Serial Number is:" + slno); System.out.println("The Student name is:" + name);

Abstract classes Interfaces Difference between Abstract Classes and Interfaces Abstract classes Interfaces Abstract classes are used only when there is a “is-a” type of relationship between the classes. Interfaces can be implemented by classes that are not related to one another. You cannot extend more than one abstract class. You can implement more than one interface. it contains both abstract methods and non Abstract Methods Interface contains all abstract methods Abstract class can implemented some methods also. Interfaces can not implement methods. With abstract classes, you are grabbing away each class’s individuality. With Interfaces, you are merely extending each class’s functionality.

Difference between Classes and Interfaces Interface is little bit like a class... but interface is lack in instance variables....that's u can't create object for it. Interfaces are developed to support multiple inheritances. 3. The methods present in interfaces are pure abstract. 4. The access specifiers public, private, protected are possible with classes. But the interface uses only one spcifier public Interfaces contain only the method declarations.... no definitions....... 6. In Class the variable declaration as well as initialization, but interface only for initializing.

Types of Interfaces A B C A B C D E A B C Interface Implementation Class Extension A B C D E Class Extension Interface Implementation A B C Interface Implementation Class

A B C D Interface Implementation Class Extension

// HIERARICHICAL INHERITANCE USING INTERFACE interface Area { final static float pi = 3.14F; float compute (float x,float y); } class Rectangle implements Area public float compute(float x,float y) return (x * y); class Circle implements Area return (pi * x * x); A B C Interface Implementation Class

class InterfaceTest { public static void main(String args[]) Rectangle rect = new Rectangle (); Circle cir = new Circle(); Area area; //Interface object area = rect; System.out.println("Area of Rectangle = " + area.compute(10,20)); area = cir; System.out.println("Area of Circle = " + area.compute(10,0)); }

D //HYBRID INHERITANCE USING INTERFACES class Student { int rollnumber; void getnumber(int n) rollnumber = n; } void putnumber() System.out.println("Roll No: " + rollnumber); class Test extends Student float part1, part2; void getmarks(float m1,float m2) part1 = m1; part2 = m2; void putmarks() System.out.println("Marks obtained"); System.out.println("Part1 = " + part1); System.out.println("Part2 = " + part2); A B C Interface Implementation Class Extension D

interface Sports { float sportwt = 6.0F; void putwt(); } class Results extends Test implements Sports float total; public void putwt() System.out.println("Sports Wt = " + sportwt); void display() total = part1 + part2 + sportwt; putnumber(); putmarks(); putwt(); System.out.println("Total Score = " + total);

class Hybrid { public static void main(String args[]) Results stud = new Results(); stud.getnumber(1234); stud.getmarks(27.5F, 33.0F); stud.display(); }

What is Partial Implementation? The Interface is implementation to the Abstract class is called Partial Implementation. Example: interface Partial_Interface { public void display_one(); } abstract class Abstract_Class implements Partial_Interface public void display_one() //Definition for the Interface Method System.out.println("This is Interface Method"); void display_two() //Concrete Method System.out.println("This is Concrete Method"); abstract void display_three(); //Abstract Method

class Pure_Class extends Abstract_Class { void display_three() //Definition for the Abstract Method System.out.println("This is Abstract Method"); } class Final public static void main(String args[]) Pure_Class pc = new Pure_Class(); pc.display_one(); pc.display_two(); pc.display_three();

Package

What is Packages? Packages are java’s way of grouping a variety of classes and / or interfaces together. The grouping is usually done according to functionality. In fact, packages act as “containers” for classes. What are the benefits of Packages? 1. The classes contained in the packages of other programs can be easily reused. 2. In packages, classes can be unique compared with classes in other packages. That is, two classes in two different packages can have the same name. They may be referred by their fully qualified name, comprising the package name and class name. 3. Packaged provide a way to “hide classes thus preventing other programs or package from accessing classes that are meant for internal use only. 4. Packages also provide a way for separating “design” from “coding”. First we can design classes and decide their relationships, and then we can implement the java code needed for the methods. It is possible to change the implementation of any method without affecting the rest of the design.

Java packages are therefore classified into two types. Types of Packages Java packages are therefore classified into two types. 1. Pre – defined packages (Java API Packages) 2. User – defined packages Java API Packages Package Name Contents java.lang Language support classes. These are classes that java compiler itself uses and therefore they are automatically imported. They include classes for primitive types, strings, math functions, threads and exceptions java.util Language utility classes such as vectors, hash tables, random numbers, date, etc. java.io Input / Output support classes. They provide facilities for the input and output of data. java.awt Set of classes for implementing graphical user interface. They include classes for windows, buttons, lists, menus and so on. java.net Classes for networking. They include classes for communicating with local computers as well as with internet servers. java.applet Classes for creating and implementing applets.

2. USER DEFINED PACKAGES How to Creating our own Packages Creating our own package involves the following steps: 1. Declare the package at the beginning of a file using the form package package_name; 2. Define the class that is to be put in the package and declare it public 3. Create a subdirectory under the directory where the main source files are stored. 4. Store the listing as the classname.java file in the subdirectory created. 5. Compile the file. This creates .class file in the subdirectory. 6. The subdirectory name must match the package name exactly. Note: Java also supports the concept of package hierarchy. This done by specifying multiple names in a package statement, separated by dots. Example: package firstPackage.secondpackage;

Example: Create Package: package package1; public class ClassA { public void displayA() System.out.println("Class A"); } How to import the package: import package1.ClassA; class PackageTest1 { public static void main(String args[]) ClassA objectA = new ClassA() objectA.displayA(); }

ACCESS PROTECTION Access Modifier Access Location Public Protected friendly (default) private protected private Same Class Yes Subclass in same package No Other classes in same package Subclass in other package Non – subclasses in other packages

Example program for the above Access Protection Tabular Protection.java: package p1; public class Protection { int n = 1; private int n_pri = 2; protected int n_pro = 3; public int n_pub = 4; public Protection() System.out.println("base constructor"); System.out.println("n = " + n); System.out.println("n_pri = " + n_pri); System.out.println("n_pro = " + n_pro); System.out.println("n_pub = " + n_pub); }

This is file Derived.java: package p1; class Derived extends Protection { Derived() System.out.println("derived constructor"); System.out.println("n = " + n); //System.out.println("n_pri = " + n_pri); //Cannot Access because //accessing level is same class //in same package System.out.println("n_pro = " + n_pro); System.out.println("n_pub = " + n_pub); }

This is file SamePackage.java: package p1; class SamePackage { SamePackage() Protection p = new Protection(); System.out.println("same package constructor"); System.out.println("n = " + p.n); //System.out.println("n_pri = " + p.n_pri); //Cannot Access because //accessing level is same //class in same package System.out.println("n_pro = " + p.n_pro); System.out.println("n_pub = " + p.n_pub); }

This is file OtherPackage.java: package p2; class Protection2 extends p1.Protection { Protection2() System.out.println("derived other package constructor"); // System.out.println("n = " + n); //Cannot Access because //accessing level is non – sub //class same class // System.out.println("n_pri = " + n_pri); //Cannot Access because //accessing level is same //class in same package System.out.println("n_pro = " + n_pro); System.out.println("n_pub = " + n_pub); }

This is file OtherPackage.java: package p2; class OtherPackage { OtherPackage() p1.Protection p = new p1.Protection(); System.out.println("other package constructor"); // System.out.println("n = " + p.n); // Cannot access because the // accessing level is non – sub // class in same package // System.out.println("n_pri = " + p.n_pri); // Cannot access // because the accessing // level is same class in // same package // System.out.println("n_pro = " + p.n_pro); // Cannot access // because the accessing // level is sub – class in // other package System.out.println("n_pub = " + p.n_pub); }

String functions

SPECIAL STRING OPERATIONS 1. Automatic creation of new String instances from string literals. 2. Concatenation of multiple String object by used of the + operators 3. Conversion of other data types to a string representation. String Literals class String_Operation { public static void main(String args[]) char chars [ ] = {'a', 'b', 'c'}; String s1 = new String(chars); String s2 = "Chettinad"; //Use String Literals, Java automatically //constructs a String object System.out.println("The Displayed String_1 is:" + s1); System.out.println("The Displayed String_2 is:" + s2); System.out.println("The Length of the String is: " + "Chettinad".length()); }

2. String Concatenation class String_Operation { public static void main(String args[]) String age = " 9 "; String s = "He is" + age + "Years old."; //Java does not allow ( + // )operators to be // applied to String // objects. System.out.println(s); }

3. String Concatenation with Other Data Types class String_Operation { public static void main(String args[]) int age = 9; String s1 = "He is " + age + " Years old. "; // The int value in age is // automatically // converted into its string // representation within a //String object. System.out.println(s1); String s2 = "four: " + 2 + 2; System.out.println(s2); String s3 = "four: " + (2 + 2); System.out.println(s3); }

4. String Conversion and toString() To implement toString(), simply return a String object that contains the human readable string. 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 String_Operation { 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); System.out.println(s); }

CHARACTER EXTRACTION The String class provides a number of ways in which characters can be extracted form a String object. That is Character Extraction. charAt() Syntax: char charAt(int where) class String_Operation { public static void main(String args[ ]) char ch; ch = "Chettinad".charAt(4); System.out.println("The 4 Character is:" + ch); }

2. getChars() If you need to extract more than one character at a time, you can use the getChars() method. Syntax: void getChars(int sourceStart,int sourceEnd,char target [ ],int targetStart) class String_Operation { 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); }

3. getBytes() There is an alternative to getChars() that stores the character 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 character. For example, most Internet protocols and text file formats use 8 - bit ASCII for all text interchage. class String_Operation { public static void main(String args[]) String msg="HelloWorld"; byte b[ ]=msg.getBytes(); System.out.println("The Character in array of Bytes is: " + b); }

4. 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. 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. class String_Operation { public static void main(String args[]) String str = "einstein relativity concept is still a concept of great discussion"; char heram[ ] = str.toCharArray(); System.out.print("Converted value from String to char array is: "); System.out.println(heram); }

STRING COMPARISON equals() and equalsIgnoreCase() To compare two strings for equality, use equals() Syntax: 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 string, it considers A - Z to be the same as a - z. 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.

class String_Operation { 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)); System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4)); System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " + s1.equalsIgnoreCase(s4)); }

2. 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 comparisions Syntax: boolean regionMatches(int startIndex,String str2,int str2StartIndex,int numChars) boolean regionMatches(boolena ignorCase,int startIndex,String str2,int strStrartIndex,int numChars)

class String_Operation { public static void main(String args[]) String str1 = new String("Java is a wonderful language"); String str2 = new String("It is an object-oriented language"); boolean result = str1.regionMatches(20, str2, 25, 0); System.out.println(result); } class String_Operation { public static void main(String args[]) String str1 = new String("Java is a wonderful language"); String str2 = new String("It is an object-oriented language"); boolean result = str1.regionMatches(true, 20, str2, 25, 0); System.out.println(result); }

3. startsWith() and endsWith() The startsWith() method determines whether a given String begins with a specified string. The endsWith() method determines whether the String in questions ends with a specified string. Syntax: boolean startsWith(String str) boolean endsWith(String str) str is the String object being tested. If the string matches, true is returned. Otherwise false is returned class String_Operation { public static void main(String args[]) boolean a, b; a = "Chettinad".startsWith("Chi"); b = "Chettinad".endsWith("nad"); System.out.println("The Start of the String is: " + a); System.out.println("The Ends of the String is:" + b); }

4. equals() Versus == The equals function and == operator are perform two different operations 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. class String_Operation { public static void main(String args[]) String s1 = "Hello1234"; String s2 = new String(s1); System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2)); System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2)); } The Contents of the two String objects are identical, but they are distinct object, This means that s1 and s2 do not refer to the same objects.

5. compareTo() Syntax: int compareTo(String str); Value Meaning Less than zero The invoking string is less than str. Greater than zero The invoking string greater than str. Zero The two strings are equal.

class String_Operation { public static void main(String args[]) String s1 = "Chettinad"; String s2 = "Chettinad"; int n = s1.compareTo(s2); if (n==0) System.out.println("The Two String are Equal"); else if(n>0) System.out.println("The First Strings is Greater than the Second String"); else if(n<0) System.out.println("The First String is Smaller than the }

MODIFYING A STRING substring() substring() has tow forms. 1. String substring(int startIndex) 2. String substring(int startIndex,int endIndex) class String_Operation { public static void main(String args[ ]) String s1 = "This is a test. This is, too."; String s2 = s1.substring(5); String s3 = s1.substring(5,8); System.out.println("The Sub String of S2 is: " + s2); System.out.println("The Sub String of S3 is: " + s3); }

2. concat() You can concatenate two strings using concat() Syntax: String concat(String str); class String_Operation { public static void main(String args[ ]) String s1 = "One"; String s2 = s1.concat(" Two"); System.out.println("The Concatenation of Two String is: " + s2); }

String replace(char original, char replacement) The replace() method replaces all occurences of one character in the invoking string with another character. Syntax: String replace(char original, char replacement) class String_Operation { public static void main(String args[ ]) String s = "Hello".replace('l','w'); System.out.println("The Replacement of the String is:" + s); } 4. trim() The trim() method returns a copy of the invoking string from which any leading and trailing whitespace has been removed. Syntax: String trim() class String_Operation { public static void main(String args[ ]) String s = " Hello world ".trim(); System.out.println("The Removable Whitspace of the String is: " + s); }

StringBuffer Functions StringBuffer is a peer class of String that provides much of the functionality of strings. 2. String Buffer represents growable and writeable character sequences. 3. String Buffer may have characters and substrings inserted in the middle or appended to the end. 4. String Buffer will automatically grow to make room for such additions and often has more characters preallocated than are actually needed, to allow room for growth. StringBuffer Constructors StringBuffer defined these three constructors: 1. StringBuffer() 2. StringBuffer(int size) 3. StringBuffer(String str)

(1) The default constructor reserves room for 16 characters without reallocation. (2) The second version accepts an integer argument that explicitly sets the size of the buffer. (3) 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. length() and capacity() Syntax: int length() int capacity() class String_Operation { 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()); //Its capacity is 21 //because room for 16 additional characters is automatically added. }

2. ensureCapacity() 1. If you want to preallocate room for a certain number of characters after a StringBuffer has been constructed, you can use ensureCapacity() to set the size of the buffer. 2. This is useful if you know in advance that you will be appending a large number of small strings to a StringBuffer.ensureCapacity() has this general form: void ensureCapacity(int capacity); Here, capacity specifies the size of the buffer. class String_Operation { public static void main(String args[]) StringBuffer sb = new StringBuffer("Rose India"); //Returns the current capacity of the String buffer. System.out.println("Buffer : "+sb+"\nCapacity : " + sb.capacity()); //Increases the capacity, as needed, to the specified amount in the //given string buffer object sb.ensureCapacity(27); System.out.println("New Capacity = " + sb.capacity()); }

3. setLength() To set the length of the buffer within a StringBuffer object, use setLength(). Syntax: void setLength(int len) Here, len specifies the length of the buffer. This value must be non - negative. when you increase the size of the buffer, null characters are added to the end of the existing buffer. class String_Operation { public static void main(String[ ] args) // Construct a StringBuffer object: StringBuffer s = new StringBuffer("Hello world!"); // Change the length of buffer to 5 characters: s.setLength(5); System.out.println(s); }

4. charAt() and setCharAt() 1. The value of a single character can be obtained from a StringBuffer via the charAt() method. Syntax: char charAt(int where) For charAt(), where specifies the index of the character being obtained. 2. You can set the value of a character within a StringBuffer using setCharAt(). void setCharAt(int where,char ch) For setCharAt(), where specifies the index of the character being set, and ch specifies the new value of that character. For both methods, where must be nonnegative and must not specify a location beyond the end of the buffer.

class String_Operation { 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'); sb.setLength(2); System.out.println("Buffer after = " + sb); System.out.println("charAt(1) after = " + sb.charAt(1)); }

5. getChars() To copy a substring of a StringBuffer into an array, use the getChars() method. Syntax: void getChars(int sourceStart,int sourceEnd,char target[],int targetStart); class String_Operation { public static void main(String[] args) // Construct a StringBuffer object: StringBuffer src = new StringBuffer("To learn JAVA, start with keywords."); // Declare a new char array: char[] dst = new char[2]; // Copy the chars #9 and #10 to dst: src.getChars(9,11,dst,0); // Display dst: System.out.println(dst); }

3. Here are a few of its forms: StringBuffer append(String str) 1. The append() method concatenates the string representation of any other type of data ot the end of the invoking StringBuffer object. 2. It has overloaded versions for all the built - in types and for Object. 3. Here are a few of its forms: StringBuffer append(String str) StringBuffer append(int num) StringBuffer append(Object obj) 4. String.valueOf() is called for each parameter to obtain its string representation. 5. The result is appended to the current StringBuffer object. The buffer itself is returned by each version of append(). StringBuff append(String str) public class String_Operation { public static void main(String[] args) // Construct a String object: String s1 = new String("3.14"); // Construct a StringBuffer object: StringBuffer s = new StringBuffer("The ratio is: "); // Append the string and display the buffer: System.out.println(s.append(s1) + "."); }

StringBuffer append(int num) class String_Operation { 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); } StringBuffer append(Object obj) /*class String_Operation { public static void main(String[] args) // Declare and initialize an object: Object d = new Double(3.14); // Construct a StringBuffer object: StringBuffer s = new StringBuffer("The ratio is: "); // Append the object and display the buffer: System.out.println(s.append(d) + "."); }

1. The insert() method inserts one string into another. 2. It is overloaded to accept values of all the simple types, plus Strings and Objects. 3. Like append(), it calls String.valueOf() to obtain the string representation of the value it is called with. 4. 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) Here, index specifies the index at which point the string will be inserted into the invoking StringBuffer object. StringBuffer insert(int index,String str) class String_Operation { public static void main(String[] args) // Construct a StringBuffer object: StringBuffer buf = new StringBuffer("Hello !"); // Construct a String object: String s = new String("there"); // Insert the string "s" at offset 6: buf = buf.insert(6,s); // Display the buffer: System.out.println(buf); }

StringBuffer insert(int index,char ch) public class String_Operation { public static void main(String[] args) // Construct a StringBuffer object: StringBuffer buf = new StringBuffer("Hello #!"); // Insert 'J' at the offset 6: buf = buf.insert(6,'J'); // Display the buffer: System.out.println(buf); } StringBuffer insert(int index, object obj) class String_Operation { public static void main(String[] args) // Construct a StringBuffer object: StringBuffer buf = new StringBuffer("Hello !"); // Construct an object: Object d = new Double(3.45); // Insert d at the offset 6: buf = buf.insert(6,d); // Display the buffer: System.out.println(buf); } }

8. reverse() You can reverse the character within s StringBuffer object using reversed(). Syntax: StringBuffer reverse() class String_Operation { public static void main(String args[]) StringBuffer s = new StringBuffer("abcdef"); System.out.println(s); s.reverse(); }

9. delete() and deleteCharAt() StringBuffer the ability to delete characters using the methods delete() and deleteCharAt(). Syntax: StringBuffer delete(int startIndex, int endIndex) StringBuffer deleteCharAt(int loc) class String_Operation { 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); }

10. replace() It replace one set of character with another set inside a StringBuffer object. StringBuffer replace(int startIndex, int endIndex, String str); class String_Operation { 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); }

11. substring() Syntax: String substring(int startIndex) String substring(int startIndex,int endIndex) class String_Operation { public static void main(String args[]) StringBuffer sb = new StringBuffer("Chettinad"); sb.substring(6); System.out.println("The Substring is: " + sb); sb.substring(2,5); }

UNIT – III Balance Chapters

THE CHARACTER STREAMS

The character Streams While the byte stream classes provide sufficient functionality to handle any type of I/O operation, they cannot work directly with Unicode characters. Since one of the main purposes of Java is to support the “write once, run anywhere” philosophy, it was necessary to include direct I/O support for characters. At the top of the character stream hierarchies are the Reader and Writer abstract classes. Reader Reader is an abstract class that defines java’s model of streaming character input. All of the methods in this class will throw an IOException on error conditions. Writer Writer is an abstract class that defines streaming character output . All of the methods in this class return a void value and throw an IOException in the case of errors.

The Methods Defined by Reader Description abstract void close() Closes the input source. Further read attempts will generate an IOException. void mark(int numChars) Places a mark at the current point in the input stream that will remain valid until numChars characters are read boolean markSupported() Returns true if mark() / reset() are supported on this stream int read() Returns an integer representation of the next available character from the invoking input stream. -1 is returned when the end of the file is encountered. int read(char buffer[]) Attempts to read up to buffer.length characters into buffer and returns the actual number of character that were successfully read. -1 is returned when the end of the file encountered. abstract int read( char buffer[], int offset, int numChars) Attempts to read up to numChars characters into buffer starting at buffer[offset], returning the number of characters successfully read. -1 is returned when the end of the file is encountered.

Method Description boolean ready() Returns true if the next input request will not wait. Otherwise, it returns false. void reset() Resets the input pointer to the previously set mark long skip( long numChars) Skips over numChars characters of input , returning the number of characters actually skipped.

The Methods Defined by Writer Description abstract void close() Closes the output stream. Further write attempts will generate an IOException. abstract void flush() Finalizes the output state so that any buffers are cleared. That is, it flushes the output buffers. void write (int ch) Writes a single character to the invoking output stream. Note that the parameter is an int, which allows you to call write with expressions without having to cast them back to char. void write(char buffer[]) Writes a complete array of characters to the invoking output stream. abstract void write( char buffer[], int numChars) Writes a subrange of numChars characters from the array buffer, beginning at buffer[offset] to the invoking output stream. void write(String str) Writes str to the invoking output stream. void write(String str, int offset, Writes a subrange of numChars characters from the array str, beginning at the specified offset.

FileReader The FileReader class creates a Reader that you can use to read the contents of a file. Its most commonly used constructors are shown here: FileReader (String filePath) FileReader (File filObj) Note: Either can throw a FileNotFoundException. Here, filePath is the full path name of a file and fileobj is a File object that describes the file.

import java.io.*; class FileReaderDemo { public static void main(String args[]) throws IOException FileReader fr = new FileReader("FileReaderDemo.java"); BufferedReader br = new BufferedReader(fr); String s; while((s = br.readLine()) != null) System.out.println(s); } fr.close();

FileWriter The FileWriter class creates a Writer that you can use to writet to a file. Its most commonly used constructors are shown here: FileWriter(String filePath) FileWriter(String filePath, boolean append) FileWriter(File fileObj) FileWriter(File fileObj, boolean append) They can throw an IOException. Here, filePath is the full path name of a file, and fileObj is a File Object that describes the file. If append is true, then output is appended to the end fo the file.

import java.io.*; class FileWriterDemo { public static void main(String args[]) try // Create file FileWriter fstream = new FileWriter("out.txt"); BufferedWriter out = new BufferedWriter(fstream); out.write("Hello Java"); //Close the output stream out.close(); } catch (Exception e) //Catch exception if any System.err.println("Error: " + e.getMessage());

CharArrayReader CharArrayReader is an implementation of an input stram that uses a character array as the source. The class has two constructos, each of which requires a character array to provide the data source: CharArrayReader(char arrray[]) CharArrayReader(char array[],int start,int numChars) Here, array is the input source. The second constructor creates a Reader from a subset of your character array that begins with the character at the index specified by start and is numChars long.

import java.io.*; class CharArrayReaderDemo { public static void main(String args[]) throws IOException String tmp = "abcdefghijklmnopqrstuvwxyz"; int length = tmp.length(); char c[] = new char[length]; tmp.getChars(0, length, c, 0); CharArrayReader input1 = new CharArrayReader(c); CharArrayReader input2 = new CharArrayReader(c, 0, 5); int i; System.out.println("input1 is:"); while((i = input1.read()) != -1) System.out.print((char)i); } System.out.println(); System.out.println("input2 is:"); while((i = input2.read()) != -1)

CharArrayWriter(int numChars) CharArrayWriter is an implementation of an output stram that uses a character array as the destination. The class has two constructos, each of which requires a character array to provide the data destination: CharArrayWriter() CharArrayWriter(int numChars) In the first form, a buffer with a default size is created. In the second, a buffer is created with a size equal to that specified by numChars. The buffer is held in the buf field of CharArrayWriter. The buffer size will be increased automatically, if needed. The number of characters held by the buffer is contained in the count field of CharArrayWriter. Both buf and count are protected fields.

import java.io.*; class CharArrayWriterDemo { public static void main(String args[]) throws IOException CharArrayWriter f = new CharArrayWriter(); String s = "This should end up in the array"; char buf[] = new char[s.length()]; s.getChars(0, s.length(), buf, 0); f.write(buf); System.out.println("Buffer as a string"); System.out.println(f.toString()); System.out.println("Into array"); char c[] = f.toCharArray(); for (int i=0; i<c.length; i++) System.out.print(c[i]); } System.out.println("\nTo a FileWriter()"); FileWriter f2 = new FileWriter("test.txt"); f.writeTo(f2); f2.close(); System.out.println("Doing a reset"); f.reset(); for (int i=0; i<3; i++) f.write('X'); } }

BufferedReader BufferedReader improves performance by buffering input. It has two constructors: BufferedReader(Reader inputStream) BufferedReader(Reader inputStream,int bufsize) The first form creates a buffered character stream using a default buffer size. In the second, the size of the buffer is passed in bufsize.

import java.io.*; class BufferedReaderDemo { public static void main(String args[]) throws IOException String s = "This is a © copyright symbol " + "but this is &copy not.\n"; char buf[] = new char[s.length()]; s.getChars(0, s.length(), buf, 0); CharArrayReader in = new CharArrayReader(buf); BufferedReader f = new BufferedReader(in); int c; while((c = f.read()) != -1) System.out.print((char)c); }

BufferedWriter A BufferedWriter is a Writer that adds a flush() method that can be used to ensure that data buffers are physically wirtten to the actual output stream. Using a BufferedWriter can increase performance by reducing the number of times data is actually physically written to the output stream. A BufferedWriter has these two constructors: BufferedWriter(Writer outputStream) BufferedWriter(Writer outputStream,int bufsize) The first form creates a buffered character stream using a default buffer size. In the second, the size of the buffer is passed in bufsize.

import java.io.*; class BufferedWriterDemo { public static void main(String args[]) throws Exception // Create a new instance of a BufferedWriter object using a StringWriter. StringWriter sw = new StringWriter(); BufferedWriter bw = new BufferedWriter(sw); // Write to the underlying StringWriter. String str = new String("This is the string being written."); // Print out the 6 characters. bw.write(str, 12, 6); bw.flush(); System.out.println(sw.getBuffer()); // Close the BufferedWriter object and the underlying StringWriter object. sw.close(); bw.close(); }

PushbackReader The PushbackReader class allows one or more characters to be returned to the input stream. This allows you to look ahead in the input stream. Here are its two constructors: PushbackReader(Reader inputStream) PushbackReader(Reader inputStream,int bufSize) The first form creates a buffered stream that allows one character to be pushed back. In the second, the size of the pushback buffer is passed in bufSize. PushbackReader provides unread(), which returns one or more characters to the invoking input stream. It has the three forms shown here: void unread(int ch) void unread(char buffer[]) void unread(char buffer[], int offset, int numChars) The first form pushes back the character passed in ch. This will be the next character returned by a subsequent call to read(). The second form returns the characters in buffer. The third form pushes back numChars characters beginning at offset from buffer. An IOException will be thrown if there is an attempt to return a character when the pushback buffer is full.

import java.io.*; class PushbackReaderDemo { public static void main(String args[]) throws IOException String s = "if (a == 4) a = 0 ; \\n"; char buf[] = new char[s.length()]; s.getChars(0, s.length(), buf, 0); CharArrayReader in = new CharArrayReader(buf); PushbackReader f = new PushbackReader(in); int c; while ((c = f.read()) != -1) switch(c) case '=': if ((c = f.read()) == '=') System.out.print(".eq."); else System.out.print("<-"); f.unread(c); } break; default: System.out.print((char) c); } } }

PrintWriter PrintWriter is essentially a character – oriented version of PrintStream. It provides the formatted output methods print() and println(). PrintWriter has four constructors: PrintWriter(OutputStream outputStream) PrintWriter(OutputStream outputStream, boolean flushOnNewline) PrintWriter(Writer outputStream) PrintWriter(Writer outputStream, boolean flushOnNewline) Where flushOnNewline controls whether Java flushes the output stream every time println() is called. If flushOnNewline is true, flushing automatically takes place. If false, flushing is not automatic. The first and third constructors do not automatically flush.

import java.io.*; class PrintWriterDemo { public static void main(String args[]) PrintWriter pw = new PrintWriter(System.out, true); pw.println("This is a string"); int i = -7; pw.println(i); double d = 4.5e-7; pw.println(d); }

SERIALIZATION

Serialization Serialization is the process of writing the state of an object to a byte stream. This is useful when you want to save the state of your program to a persistent storage area, such as a file. At a later time, you may restore these objects by using the process of deserialization. Serialization is also needed to implement Remote Method Invocation (RMI). RMI allows a Java object on one machine to invoke a method of a Java object on a different machine. An object may be supplied as an argument to that remote method. The sending machine serializes the object and transmits it. The receiving machine deserializes it.

void writeExternal(ObjectOutput outStream) throws IOException Serializable Only an object that implements the Serializable interface can be saved and restored by the serialization facilities. The Serializable interface defines no members. It is simply used to indicate that a class may be serialized. If a class is serializable, all of its subclasses are also serializable. Variables that are declared as transient are not saved by the serialization facilities. Also static variable are not saved. Externalizable The Java facilities for serialization and deserialization have been designed so that much of the work to save and restore the state of an object occurs automatically. However, there are cases in which the programmer may need to have control over these processes. For example, it may be desirable to use compression or encryption techniques. The Externalizable interface is designed for these situations. The Externalizable interface defines these two methods: void readExternal(ObjectInput inStream) throws IOException, ClassNotFoundException void writeExternal(ObjectOutput outStream) throws IOException In these methods, inStream is the byte stream from which the object is to be read, and outStream is the byte stream to which the object is to be written.

ObjectOutput The ObjectOutput interface extends the DataOutput interface and support object Serialization. The following Methods is called the serialize an object. All of these methods will throw an IOException on error condition. Method Description void close() Closes the invoking stream. Further write attempts will generate an IOException. void flush() Finalizes the output state so that any buffers are cleared. That is, it flushes the output buffers. void wirte(byte buffer[]) Writes an array of bytes to the invoking stream. void write(byte buffer[], int offset, int numBytes) Writes a subrange of numBytes bytes from the array buffer, beginning at buffer[offset]. void write(int b) Writes a single byte to the invoking stream. The byte written is the low – order byte of b. Void writeObject(Object obj) Writes object obj to the invoking stream.

ObjectOutputStream(OutputStream outStream) throws IOException The ObjectOutputStream class extends the OutputStream class and implements the ObjectOutput interface. It is responsible for writing objects to a stream. A constructor of this class is: ObjectOutputStream(OutputStream outStream) throws IOException The argument outStream is the output stream to which serialized objects will be written. Method Description void close() Closes the invoking stream. Further write attempts will generate an IOException. void flush() Finalizes the output state so that any buffers are cleared. That is, it flushes the output buffers. void wirte(byte buffer[]) Writes an array of bytes to the invoking stream. void write(byte buffer[], int offset, int numBytes) Writes a subrange of numBytes bytes from the array buffer, beginning at buffer[offset]. void write(int b) Writes a single byte to the invoking stream. The byte written is the low – order byte of b. void writeBoolean(boolean b) Writes boolean to the invoking stream.

Method Description void writeByte(int b) Writes a byte to the invoking stream. The byte written is the low – order byte of b. void writeBytes(String str) Writes the bytes representing str to the invoking stream. void writeChar(int c) Writes a char to the invoking stream. void writeChars(String str) Writes the characters in str to the invoking stream. void writeDouble(double d) Writes a double to the invoking stream. void writeFloat(float f) Writes a float to the invoking stream. void writeInt(int i) Writes a int to the invoking stream. void WriteShort(int i) Writes a short to the invoking stream. void writeLong(long i) Writes a long to the invoking stream. final void writeObject(Object obj) Writes a obj to the invoking stream.

ObjectInput The ObjectInput interface extends the DataInput interface and support object Serialization. The following Methods is called the serialize an object. All of these methods will throw an IOException on error condition. Method Description int available() Returns the number of bytes that are now available in the input buffer. void close() Closes the invoking stream. Further read attempts will generate an IOException. int read() Returns an integer representation of the next available byte of input. -1 is returned when the end of the file is encountered. int read(byte buffer[]) Attempts to read up to buffer length bytes into buffer, returning the number of bytes that were successfully read. -1 is returned when the end of the file is encountered. int read(byte buffer[], int offset, int numBytes) Attempts to read up to numBytes bytes into buffer starting at buffer[offset], returning the number of bytes that were successfully read. -1 is returned when the end of the file is encountered.

ObjectInputStream Method Description Object readObject() Reads an object from the invoking stream. Long skip(long numBytes) Ignores(that is, skips) numBytes bytes in the invoking stream, returnign the number of bytes actually ignored. ObjectInputStream The ObjectInputStream class extends the InputStream class and implements the ObjectInput interface. It is responsible for Reading objects from a stream. A constructor of this class is: ObjectInputStream(InputStream inStream) throws IOException, StreamCorruptedException The argument inStream is the input stream from which serialized objects should be read.

Method Description int available() Returns the number of bytes that are now available in the input buffer. void close() Closes the invoking stream. Further read attempts will generate an IOException int read() Returns an integer representation of the next available byte of input. -1 is returned when the end of the file is encountered. int read(byte buffer[],int offset,int numBytes) Attempts to read up to numBytes bytes into buffer starting at buffer[offset], returning the number of bytes successfully read. -1 is returned when the end of the file is encountered. boolean readBoolena() Reads and returns boolean from the invoking stream. byte readByte() Reads and returns a byte from the invoking stream. char readChar() Reads and returns a char from the invoking stream. double readDouble() Reads and returns a double from the invoking stream. float readFloat() Reads and returns a float from the invoking stream. void readFully(byte buffer[]) Reads buffer length bytes into buffer. Returns only when all bytes have been read. void readFully(byte buffer[], int offset, int numBytes) Reads numBytes bytes into buffer starting at buffer[offset]. Returns only when numBytes have been read.

Method Description int readInt() Reads and returns an int from the invoking stream. long readLong() Reads and returns a long from the invoking stream. final Object readObject() Reads and returns an object from the invoking stream. short readShort() Reads and returns a short from the invoking stream. int readUnsignedByte() Reads and returns an unsigned byte from the invoking stream. int readUnsignedShort() Reads an unsigned short from the invoking stream.

import java.io.*; class SerializationDemo { public static void main(String arg[]) //Object Serialization try MyClass object1 = new MyClass("Hello", -7,2.7e10); System.out.println("Object1: " + object1); FileOutputStream fos = new FileOutputStream("serial"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(object1); oos.flush(); oos.close(); } catch(Exception e) System.out.println("Exception during serialization: " + e); System.exit(0);

//Object Deserialization try { MyClass object2; FileInputStream fis = new FileInputStream("serial"); ObjectInputStream ois = new ObjectInputStream(fis); object2 = (MyClass)ois.readObject(); ois.close(); System.out.println("object2: " + object2); } catch(Exception e) System.out.println("Exception during deserialization: " + e); System.exit(0); class MyClass implements Serializable String s; int i; double d; public MyClass(String s,int i,double d) this.s = s; this.i = i; this.d = d; public String toString() return "S=" + s + "; i=" + i + "; d=" + d; } }

EXCEPTION HANDLING OR ERROR HANDLING

- Error means mistakes or buggs - Error is classified into types What is Error? - Error means mistakes or buggs - Error is classified into types Error Compile Time Error Run Time Error All syntax errors will be detected And displayed by the Java compi ler and therefore these errors Are known as compile – time – errors A program may compile success fully creating the .exe file but not run properly. Such programs may produce wrong results due to wrong loaic or may terminate due to errors Missing Semicolon Missing brackets in classes and methods 3. Use of undeclared variables Dividing an integer by zero Accessing an element that is out of the bounds of an array

Some Example of Runtime Errors class Error_Handling { public static void main(String args[]) int a,b,c; a = 10; b = 0; c = a / b; System.out.println("The Value of the C Value is:" + c); } Output: / by zero

Exception Types Throwable Exception (or) RuntimeException Error 1. All Exception types are subclasses of the built – in class Throwable. Throwable is at the top of the exception class hierarchy Throwable Exception (or) RuntimeException Error This class is used for exceptional conditions that user programs should catch. This is also the class That you will subclass to create your own custom exception types Which defines exceptions that are not Expected to be caught under normal Circumstances by our program. Ex. Stack overflow

Uncaught Exception class Error_Handling { public static void main(String args[]) int i,j,k1,k2; i = 10; j = 0; k1 = i / j; k2 = i + j; System.out.println("The Division of the K1 Value is: " + k1); System.out.println("The addition of the K2 Value is: " + k2); } Output: java.lang.ArithmeticException: / by zero at Error_Handling.main(Error_Handling.java:4) In this example, we haven’t supplied any exception handlers of our own, so the exception is caught by the default handler provided by the java run – time system

What is Exceptions? An Exception is condition that is caused by a run – time error in the program. What is Exception Handling? If the exception object is not caught and handled properly, the compiler will display an error message and will terminate the program. If we want the program to continue with the execution of the remaining appropriate message for taking corrective actions. This task is known as exception handling. Exceptions Types Exception Asynchronous Exception Synchronous Exception Keyboard Interrupt Mouse Interrupt Division by Zero

Catches and handles the Exception Handling Mechanism The purpose of the exception handling mechanism is to provide means to detect and report an “exceptional circumstance”, so that appropriate action can be taken. The Error Handling code that performs the following tasks: 1. Find the problem (Hit the Exception) 2. Inform that an error has occurred (Throw the exception) 3. Receive the error information (Catch the exception) 4. Take corrective actions (Handle the exception) try block Detects and throws an exception catch block Catches and handles the exception Exception object

Using try and catch //Block of statements which detects and ------------------ try { ------------- } catch(Exception_Type e) -------------- //Block of statements which detects and //throws an exception //Catches exception //Block of statements that handles the //exception

Example Program for Exception Handling Mechanism class Error_Handling { public static void main(String args[]) int i,j,k1,k2; i = 10; j = 0; try k1 = i / j; System.out.println("The Division of the K1 Value is: " + k1); } catch(ArithmeticException e) System.out.println("Division by Zero"); k2 = i + j; System.out.println("The addition of the K2 Value is: " + k2); There is an Exception Catches the exception Output: Division by Zero, The addition of the K2 Value is:10

Multiple Catch Statements It is possible that a program segment has more than one condition to throw an exception. try { //statements } catch(Exception-Type-1 e) catch(Exception-Type-2 e) ----------- catch(Exception-Type-N e)

class Error_Handling { public static void main(String args[]) int a[ ] = {5,10}; int b = 5; try int x = a[2] / b - a[1]; } catch(ArithmeticException e) System.out.println("Division by Zero"); catch(ArrayIndexOutOfBoundsException e) System.out.println("Array Index Error"); catch(ArrayStoreException e) System.out.println("Wrong data type"); int y = a[1] / a[0]; System.out.println("Y = " + y);

COMMAN EXCEPTION HANDLER class Error_Handling { public static void main(String args[]) int a[ ] = {5,10}; int b = 5; try int x = a[2] / b - a[1]; } catch(ArithmeticException e) System.out.println("Division by Zero"); /*catch(ArrayIndexOutOfBoundsException e) System.out.println("Array Index Error"); }*/ catch(ArrayStoreException e) System.out.println("Wrong data type");

catch(Exception e) { System.out.println("The Producing any Runtime Error" + e.getMessage()); } int y = a[1] / a[0]; System.out.println("Y = " + y);

EXCEPTION HIERARCHY class Error_Handling { public static void main(String args[]) int a[ ] = {5,10}; int b = 5; try int x = a[2] / b - a[1]; } catch(ArithmeticException e) System.out.println("Division by Zero"); catch(Exception e) System.out.println("The Producing any Runtime Error" + e.getMessage()); /*catch(ArrayIndexOutOfBoundsException e) System.out.println("Array Index Error"); }*/

catch(ArrayStoreException e) { System.out.println("Wrong data type"); } int y = a[1] / a[0]; System.out.println("Y = " + y);

Nested try Statements class Error_Handling { public static void main(String args[]) try int a = args.length; int b = 42 / a; //If no command - line args are present, //the following statement will generate a divide - by - zero exception System.out.println("a = " + a); // nested try bloack // If one command - line arg is used, then a divide - by //- zero exception will be generated by the following code.

try { if ( a == 1) a = a / (a - a); //division by zero 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); catch(ArithmeticException e) System.out.println("Divide by Zero: " + e);

Nested try Statements using Subroutine class Error_Handling { static void nesttry(int a) try if ( a == 1) a = a / (a - a); //division by zero 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; int b = 42 / a; //If no command - line args are present, the //following statement will generate a divide - by - zero exception System.out.println("a = " + a); // nested try bloack // If one command - line arg is used, then a divide - by - //zero exception will be generated by the following code. nesttry(a); // Calling Static Method } catch(ArithmeticException e) System.out.println("Divide by Zero: " + e);

throw You have only been catching exceptions that are thrown by the java run – time system. However, it is possible for your program to throw an exception explicitly. Using throw statement. Syntax: throw ThrowableInstance; Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Simple types, such as int or char, as well as non – Throwable classes, such as String and Object, cannot be used as exception. There are two ways you can obtain a Throwable object: using a parameter into a catch clause, or creating one with the new operator.

class Error_Handling { static void display() try throw new NullPointerException("Demo"); } catch(NullPointerException e) throw e; public static void main(String args[]) display(); System.out.println("Recaught : " + e);

throws If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. A throws clause list the types of exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile – time error will result. type method-name (parameter-list) throws exception-list { //body of method } Here, exception – list is comma – separated list of the exceptions that a method can throw

class Error_Handling { static void throwdemo() throws IllegalAccessException System.out.println("Inside throwdemo"); } public static void main(String args[]) try throwdemo(); catch(IllegalAccessException e) System.out.println("Caught " + e);

Using finally Statement Java supports another statement known as finally statement that can be used to handle an exception that is not caught by any of the previous catch statements. finally block can be used to handle any exception generated within a try block. It may be added immediately after the try block or after the last catch block. try { //statements } catch(Exception-Type-1 e) catch(Exception-Type-2 e) ----------- catch(Exception-Type-N e) finally ------------------- try { //statements } finally -------------------

class Error_Handling { static void procA() try System.out.println("Inside ProcA"); throw new RuntimeException("demo"); } finally System.out.println("ProcA's finally"); static void procB() System.out.println("inside ProcB"); //return; System.out.println("ProcB's finally");

static void procC() { try System.out.println("inside ProcC"); } finally System.out.println("ProcC's finally"); public static void main(String args[]) procA(); catch(Exception e) System.out.println("Exception Caught"); System.out.println("Procedure A is Wind up"); procB(); procC(); } }

Java’s Built – in Exceptions The standard package java.lang, Java defines several exception classes. A few have been used by the preceding examples. The most general of these exceptions are subclasses of the standard type RuntimeException. Since java.lang is implicitly imported into all java programs, most exceptions derived from RuntimeException are automatically available. Furthermore, they need not be included in any method’s throws list. In the language of Java, these are called unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions. The other exceptions defined by java.lang that must be included in a method’s throws list if that method can generate one of these exceptions and does not handle it itself. These are called checked exceptions.

Java’s Unchecked RuntimeException Subclasses Meaning ArithmeticException Arithmetic error, such as divde – by – zero ArrayIndexOutOfBoundsException Array index is out – of – bounds. ArrayStoreException Assignment to an array element of an incompatible type. ClassCastException Invalid Cast. IllegalArgumentException Illegal argument used to invoke a method IllegalMonitoStateException Illegal Monitor Operation, such as waiting on an unlocked thread. IllegalStateException Environment or application is in incorrect state. IllegalThreadStateException Requested operation not compatible with current thread state. IndexOutOfBoundsException Some type of index is out – of – bounds NegativeArraySizeException Array Created with a negative size.

Exception Meaning NullPointerException Invalid use of a null reference. NumberFormatException Invalid conversion of a string to a numeric format. SecurityException Attempt to violate security StringIndexOutOfBounds Attempt to index outside the bounds of a string. UnsupportedOperationException An unsupported Operation was encountered.

Java’s Checked Exception Defined in java.lang Meaning ClassNotFoundException Class not found CloneNotSupportedException Attempt to clone an object that does not implement the cloneable interface. IllegalAccessException Access to a class is denied InstantiationException Attempt to create an object of an abstract class or interface InterruptedException One thread has been interrupted by another thread. NoSuchFieldException A requested field does not exist. NoSuchMethodException A requested method does not exist.

throw new Throwable_subclass; Throwing our own Exceptions There may be times when we would like to throw our own exceptions. We can do this by using the keyword throw as follows: throw new Throwable_subclass; Example: throw new ArithmeticException(); throw new NumberFormatException(); Note: Exception is subclass of Throwable and therefore MyException is a subclass of Throwable class. An object of a class that extends Throwable can be thrown and caught

import java.lang.Exception; class MyException extends Exception { MyException(String message) super(message); } class Exception_Handling public static void main(String args[]) int x = 5, y = 1000; try float z = (float) x / (float) y; if (z < 0.01) throw new MyException("Number is too small");

catch(MyException e) { System.out.println("Caught my exception"); System.out.println(e.getMessage()); } finally System.out.println("I am always here");

Using Exceptions Exception handling provides a powerful mechanism for controlling complex programs that have many dynamic run – time characteristics. It is important to think of try, throw and catch as clean ways to handle errors and unusual boundary conditions in your program’s logic. If you are like most programmers, then you probably are used to returning an error code when a method fails. When you are programming in Java, you should break this habit. When a method can fail, have it throw an exception. This is a cleaner way to handle failure modes. One last point: Java’s Exception – handling statements should not be considered a general mechanism for nonlocal branching. If you do so, it will only confuse your code and make it hard to maintain.

THE CHARACTER STREAMS

The character Streams While the byte stream classes provide sufficient functionality to handle any type of I/O operation, they cannot work directly with Unicode characters. Since one of the main purposes of Java is to support the “write once, run anywhere” philosophy, it was necessary to include direct I/O support for characters. At the top of the character stream hierarchies are the Reader and Writer abstract classes. Reader Reader is an abstract class that defines java’s model of streaming character input. All of the methods in this class will throw an IOException on error conditions. Writer Writer is an abstract class that defines streaming character output . All of the methods in this class return a void value and throw an IOException in the case of errors.

The Methods Defined by Reader Description abstract void close() Closes the input source. Further read attempts will generate an IOException. void mark(int numChars) Places a mark at the current point in the input stream that will remain valid until numChars characters are read boolean markSupported() Returns true if mark() / reset() are supported on this stream int read() Returns an integer representation of the next available character from the invoking input stream. -1 is returned when the end of the file is encountered. int read(char buffer[]) Attempts to read up to buffer.length characters into buffer and returns the actual number of character that were successfully read. -1 is returned when the end of the file encountered. abstract int read( char buffer[], int offset, int numChars) Attempts to read up to numChars characters into buffer starting at buffer[offset], returning the number of characters successfully read. -1 is returned when the end of the file is encountered.

Method Description boolean ready() Returns true if the next input request will not wait. Otherwise, it returns false. void reset() Resets the input pointer to the previously set mark long skip( long numChars) Skips over numChars characters of input , returning the number of characters actually skipped.

The Methods Defined by Writer Description abstract void close() Closes the output stream. Further write attempts will generate an IOException. abstract void flush() Finalizes the output state so that any buffers are cleared. That is, it flushes the output buffers. void write (int ch) Writes a single character to the invoking output stream. Note that the parameter is an int, which allows you to call write with expressions without having to cast them back to char. void write(char buffer[]) Writes a complete array of characters to the invoking output stream. abstract void write( char buffer[], int numChars) Writes a subrange of numChars characters from the array buffer, beginning at buffer[offset] to the invoking output stream. void write(String str) Writes str to the invoking output stream. void write(String str, int offset, Writes a subrange of numChars characters from the array str, beginning at the specified offset.

FileReader The FileReader class creates a Reader that you can use to read the contents of a file. Its most commonly used constructors are shown here: FileReader (String filePath) FileReader (File filObj) Note: Either can throw a FileNotFoundException. Here, filePath is the full path name of a file and fileobj is a File object that describes the file.

import java.io.*; class FileReaderDemo { public static void main(String args[]) throws IOException FileReader fr = new FileReader("FileReaderDemo.java"); BufferedReader br = new BufferedReader(fr); String s; while((s = br.readLine()) != null) System.out.println(s); } fr.close();

FileWriter The FileWriter class creates a Writer that you can use to writet to a file. Its most commonly used constructors are shown here: FileWriter(String filePath) FileWriter(String filePath, boolean append) FileWriter(File fileObj) FileWriter(File fileObj, boolean append) They can throw an IOException. Here, filePath is the full path name of a file, and fileObj is a File Object that describes the file. If append is true, then output is appended to the end fo the file.

import java.io.*; class FileWriterDemo { public static void main(String args[]) try // Create file FileWriter fstream = new FileWriter("out.txt"); BufferedWriter out = new BufferedWriter(fstream); out.write("Hello Java"); //Close the output stream out.close(); } catch (Exception e) //Catch exception if any System.err.println("Error: " + e.getMessage());

CharArrayReader CharArrayReader is an implementation of an input stram that uses a character array as the source. The class has two constructos, each of which requires a character array to provide the data source: CharArrayReader(char arrray[]) CharArrayReader(char array[],int start,int numChars) Here, array is the input source. The second constructor creates a Reader from a subset of your character array that begins with the character at the index specified by start and is numChars long.

import java.io.*; class CharArrayReaderDemo { public static void main(String args[]) throws IOException String tmp = "abcdefghijklmnopqrstuvwxyz"; int length = tmp.length(); char c[] = new char[length]; tmp.getChars(0, length, c, 0); CharArrayReader input1 = new CharArrayReader(c); CharArrayReader input2 = new CharArrayReader(c, 0, 5); int i; System.out.println("input1 is:"); while((i = input1.read()) != -1) System.out.print((char)i); } System.out.println(); System.out.println("input2 is:"); while((i = input2.read()) != -1)

CharArrayWriter(int numChars) CharArrayWriter is an implementation of an output stram that uses a character array as the destination. The class has two constructos, each of which requires a character array to provide the data destination: CharArrayWriter() CharArrayWriter(int numChars) In the first form, a buffer with a default size is created. In the second, a buffer is created with a size equal to that specified by numChars. The buffer is held in the buf field of CharArrayWriter. The buffer size will be increased automatically, if needed. The number of characters held by the buffer is contained in the count field of CharArrayWriter. Both buf and count are protected fields.

import java.io.*; class CharArrayWriterDemo { public static void main(String args[]) throws IOException CharArrayWriter f = new CharArrayWriter(); String s = "This should end up in the array"; char buf[] = new char[s.length()]; s.getChars(0, s.length(), buf, 0); f.write(buf); System.out.println("Buffer as a string"); System.out.println(f.toString()); System.out.println("Into array"); char c[] = f.toCharArray(); for (int i=0; i<c.length; i++) System.out.print(c[i]); } System.out.println("\nTo a FileWriter()"); FileWriter f2 = new FileWriter("test.txt"); f.writeTo(f2); f2.close(); System.out.println("Doing a reset"); f.reset(); for (int i=0; i<3; i++) f.write('X'); } }

BufferedReader BufferedReader improves performance by buffering input. It has two constructors: BufferedReader(Reader inputStream) BufferedReader(Reader inputStream,int bufsize) The first form creates a buffered character stream using a default buffer size. In the second, the size of the buffer is passed in bufsize.

import java.io.*; class BufferedReaderDemo { public static void main(String args[]) throws IOException String s = "This is a © copyright symbol " + "but this is &copy not.\n"; char buf[] = new char[s.length()]; s.getChars(0, s.length(), buf, 0); CharArrayReader in = new CharArrayReader(buf); BufferedReader f = new BufferedReader(in); int c; while((c = f.read()) != -1) System.out.print((char)c); }

BufferedWriter A BufferedWriter is a Writer that adds a flush() method that can be used to ensure that data buffers are physically wirtten to the actual output stream. Using a BufferedWriter can increase performance by reducing the number of times data is actually physically written to the output stream. A BufferedWriter has these two constructors: BufferedWriter(Writer outputStream) BufferedWriter(Writer outputStream,int bufsize) The first form creates a buffered character stream using a default buffer size. In the second, the size of the buffer is passed in bufsize.

import java.io.*; class BufferedWriterDemo { public static void main(String args[]) throws Exception // Create a new instance of a BufferedWriter object using a StringWriter. StringWriter sw = new StringWriter(); BufferedWriter bw = new BufferedWriter(sw); // Write to the underlying StringWriter. String str = new String("This is the string being written."); // Print out the 6 characters. bw.write(str, 12, 6); bw.flush(); System.out.println(sw.getBuffer()); // Close the BufferedWriter object and the underlying StringWriter object. sw.close(); bw.close(); }

PushbackReader The PushbackReader class allows one or more characters to be returned to the input stream. This allows you to look ahead in the input stream. Here are its two constructors: PushbackReader(Reader inputStream) PushbackReader(Reader inputStream,int bufSize) The first form creates a buffered stream that allows one character to be pushed back. In the second, the size of the pushback buffer is passed in bufSize. PushbackReader provides unread(), which returns one or more characters to the invoking input stream. It has the three forms shown here: void unread(int ch) void unread(char buffer[]) void unread(char buffer[], int offset, int numChars) The first form pushes back the character passed in ch. This will be the next character returned by a subsequent call to read(). The second form returns the characters in buffer. The third form pushes back numChars characters beginning at offset from buffer. An IOException will be thrown if there is an attempt to return a character when the pushback buffer is full.

import java.io.*; class PushbackReaderDemo { public static void main(String args[]) throws IOException String s = "if (a == 4) a = 0 ; \\n"; char buf[] = new char[s.length()]; s.getChars(0, s.length(), buf, 0); CharArrayReader in = new CharArrayReader(buf); PushbackReader f = new PushbackReader(in); int c; while ((c = f.read()) != -1) switch(c) case '=': if ((c = f.read()) == '=') System.out.print(".eq."); else System.out.print("<-"); f.unread(c); } break; default: System.out.print((char) c); } } }

PrintWriter PrintWriter is essentially a character – oriented version of PrintStream. It provides the formatted output methods print() and println(). PrintWriter has four constructors: PrintWriter(OutputStream outputStream) PrintWriter(OutputStream outputStream, boolean flushOnNewline) PrintWriter(Writer outputStream) PrintWriter(Writer outputStream, boolean flushOnNewline) Where flushOnNewline controls whether Java flushes the output stream every time println() is called. If flushOnNewline is true, flushing automatically takes place. If false, flushing is not automatic. The first and third constructors do not automatically flush.

import java.io.*; class PrintWriterDemo { public static void main(String args[]) PrintWriter pw = new PrintWriter(System.out, true); pw.println("This is a string"); int i = -7; pw.println(i); double d = 4.5e-7; pw.println(d); }

SERIALIZATION

Serialization Serialization is the process of writing the state of an object to a byte stream. This is useful when you want to save the state of your program to a persistent storage area, such as a file. At a later time, you may restore these objects by using the process of deserialization. Serialization is also needed to implement Remote Method Invocation (RMI). RMI allows a Java object on one machine to invoke a method of a Java object on a different machine. An object may be supplied as an argument to that remote method. The sending machine serializes the object and transmits it. The receiving machine deserializes it.

void writeExternal(ObjectOutput outStream) throws IOException Serializable Only an object that implements the Serializable interface can be saved and restored by the serialization facilities. The Serializable interface defines no members. It is simply used to indicate that a class may be serialized. If a class is serializable, all of its subclasses are also serializable. Variables that are declared as transient are not saved by the serialization facilities. Also static variable are not saved. Externalizable The Java facilities for serialization and deserialization have been designed so that much of the work to save and restore the state of an object occurs automatically. However, there are cases in which the programmer may need to have control over these processes. For example, it may be desirable to use compression or encryption techniques. The Externalizable interface is designed for these situations. The Externalizable interface defines these two methods: void readExternal(ObjectInput inStream) throws IOException, ClassNotFoundException void writeExternal(ObjectOutput outStream) throws IOException In these methods, inStream is the byte stream from which the object is to be read, and outStream is the byte stream to which the object is to be written.

ObjectOutput The ObjectOutput interface extends the DataOutput interface and support object Serialization. The following Methods is called the serialize an object. All of these methods will throw an IOException on error condition. Method Description void close() Closes the invoking stream. Further write attempts will generate an IOException. void flush() Finalizes the output state so that any buffers are cleared. That is, it flushes the output buffers. void wirte(byte buffer[]) Writes an array of bytes to the invoking stream. void write(byte buffer[], int offset, int numBytes) Writes a subrange of numBytes bytes from the array buffer, beginning at buffer[offset]. void write(int b) Writes a single byte to the invoking stream. The byte written is the low – order byte of b. Void writeObject(Object obj) Writes object obj to the invoking stream.

ObjectOutputStream(OutputStream outStream) throws IOException The ObjectOutputStream class extends the OutputStream class and implements the ObjectOutput interface. It is responsible for writing objects to a stream. A constructor of this class is: ObjectOutputStream(OutputStream outStream) throws IOException The argument outStream is the output stream to which serialized objects will be written. Method Description void close() Closes the invoking stream. Further write attempts will generate an IOException. void flush() Finalizes the output state so that any buffers are cleared. That is, it flushes the output buffers. void wirte(byte buffer[]) Writes an array of bytes to the invoking stream. void write(byte buffer[], int offset, int numBytes) Writes a subrange of numBytes bytes from the array buffer, beginning at buffer[offset]. void write(int b) Writes a single byte to the invoking stream. The byte written is the low – order byte of b. void writeBoolean(boolean b) Writes boolean to the invoking stream.

Method Description void writeByte(int b) Writes a byte to the invoking stream. The byte written is the low – order byte of b. void writeBytes(String str) Writes the bytes representing str to the invoking stream. void writeChar(int c) Writes a char to the invoking stream. void writeChars(String str) Writes the characters in str to the invoking stream. void writeDouble(double d) Writes a double to the invoking stream. void writeFloat(float f) Writes a float to the invoking stream. void writeInt(int i) Writes a int to the invoking stream. void WriteShort(int i) Writes a short to the invoking stream. void writeLong(long i) Writes a long to the invoking stream. final void writeObject(Object obj) Writes a obj to the invoking stream.

ObjectInput The ObjectInput interface extends the DataInput interface and support object Serialization. The following Methods is called the serialize an object. All of these methods will throw an IOException on error condition. Method Description int available() Returns the number of bytes that are now available in the input buffer. void close() Closes the invoking stream. Further read attempts will generate an IOException. int read() Returns an integer representation of the next available byte of input. -1 is returned when the end of the file is encountered. int read(byte buffer[]) Attempts to read up to buffer length bytes into buffer, returning the number of bytes that were successfully read. -1 is returned when the end of the file is encountered. int read(byte buffer[], int offset, int numBytes) Attempts to read up to numBytes bytes into buffer starting at buffer[offset], returning the number of bytes that were successfully read. -1 is returned when the end of the file is encountered.

ObjectInputStream Method Description Object readObject() Reads an object from the invoking stream. Long skip(long numBytes) Ignores(that is, skips) numBytes bytes in the invoking stream, returnign the number of bytes actually ignored. ObjectInputStream The ObjectInputStream class extends the InputStream class and implements the ObjectInput interface. It is responsible for Reading objects from a stream. A constructor of this class is: ObjectInputStream(InputStream inStream) throws IOException, StreamCorruptedException The argument inStream is the input stream from which serialized objects should be read.

Method Description int available() Returns the number of bytes that are now available in the input buffer. void close() Closes the invoking stream. Further read attempts will generate an IOException int read() Returns an integer representation of the next available byte of input. -1 is returned when the end of the file is encountered. int read(byte buffer[],int offset,int numBytes) Attempts to read up to numBytes bytes into buffer starting at buffer[offset], returning the number of bytes successfully read. -1 is returned when the end of the file is encountered. boolean readBoolena() Reads and returns boolean from the invoking stream. byte readByte() Reads and returns a byte from the invoking stream. char readChar() Reads and returns a char from the invoking stream. double readDouble() Reads and returns a double from the invoking stream. float readFloat() Reads and returns a float from the invoking stream. void readFully(byte buffer[]) Reads buffer length bytes into buffer. Returns only when all bytes have been read. void readFully(byte buffer[], int offset, int numBytes) Reads numBytes bytes into buffer starting at buffer[offset]. Returns only when numBytes have been read.

Method Description int readInt() Reads and returns an int from the invoking stream. long readLong() Reads and returns a long from the invoking stream. final Object readObject() Reads and returns an object from the invoking stream. short readShort() Reads and returns a short from the invoking stream. int readUnsignedByte() Reads and returns an unsigned byte from the invoking stream. int readUnsignedShort() Reads an unsigned short from the invoking stream.

import java.io.*; class SerializationDemo { public static void main(String arg[]) //Object Serialization try MyClass object1 = new MyClass("Hello", -7,2.7e10); System.out.println("Object1: " + object1); FileOutputStream fos = new FileOutputStream("serial"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(object1); oos.flush(); oos.close(); } catch(Exception e) System.out.println("Exception during serialization: " + e); System.exit(0);

//Object Deserialization try { MyClass object2; FileInputStream fis = new FileInputStream("serial"); ObjectInputStream ois = new ObjectInputStream(fis); object2 = (MyClass)ois.readObject(); ois.close(); System.out.println("object2: " + object2); } catch(Exception e) System.out.println("Exception during deserialization: " + e); System.exit(0); class MyClass implements Serializable String s; int i; double d; public MyClass(String s,int i,double d) this.s = s; this.i = i; this.d = d; public String toString() return "S=" + s + "; i=" + i + "; d=" + d; } }

Constructor Calling Conversion Action Method Calling Conversion Action Converting Primitive Numbers to Object Numbers using Constructor Methods Constructor Calling Conversion Action Integer intval = new Integer(i) Primitive integer to Integer object Float floatval = new Float(f) Primitive float to Float object Double doubleval = new Double(d) Primitive double to Double object Long longval = new Long(l) Primitive long to Long object Converting Object Numbers to Primitive Numbers using typeValue() method Method Calling Conversion Action int i = IntVal.intValue() Object to Primitive integer float f = FloatVal.floatValue() Object to Primitive float long l = LongVal.longValue() Object to Primitive long double d = DoubleVal.doubleValue() Object to Primitive double

Constructor Calling Conversion Action Method Calling Conversion Action Converting Numbers to Strings Using a String( ) Method Constructor Calling Conversion Action str = Integer.toString(i) Primitive Integer to string str = Float.toString(f) Primitive float to string str = Double.toString(d) Primitive double to string str = Long.toString(l) Primitive long to string Converting String Objects to Numeric Object Using the Static Method ValueOf() Method Calling Conversion Action DoubleVal = Double.ValueOf(str) Converts String to Double object FloatVal = Float.ValueOf(str) Converts String to Float object IntVal = Integer.ValueOf(str) Converts string to Integer object LongVal = Long.Valueof(str) Converts string to Long object

Constructor Calling Conversion Action Converting Numberic Strings to Primitive Numbers Using Parsing Methods Constructor Calling Conversion Action int i = Integer.parseInt(str) Converts String to Primitive Integer long l = Long.parseLong(str) Converts String to Primitive long

THREAD MODEL

INTRODUCTION Those who are familiar with the modern operation systems such as windows 95 may recognize that they can execute several programs simultaneously. This ability is known as multitasking. In System’s terminology, it is called multithreading. Multithreading is a conceptual programming paradigm where a program is divided into two or more subprograms, which can be implemented at the same time in parallel. For example, one subprogram can display an animation on the screen while another may build the next animation to be displayed. This something similar to dividing a task into subtasks and assigning them to different people for execution independently and simultaneously. In most of our computers, we have only a single processor and therefore, in reality, the processor is doing only one thing at a time. However, the processor switches between the processes so fast that it appears to human beings that all of them are being done simultaneously. Java programs contain only a single sequential flow of control. This is what happens when we execute a normal program. The program begins, runs through a sequence of executions, and finally ends. At any given point of time, there is only one statement under execution. A thread is similar to a program that has a single flow of control. It has a beginning, a body and an end, and executes commands sequentially. In fact, all main programs in our earlier examples can be called single – threaded programs. A unique property of Java is its support for multithreading. That is, java enables us to use multiple flows of control in developing programs. Each flow of control may be thought of as in separate tiny program known as thread that runs in parallel to others.

SINGLE THREADED PROGRAM class ABC { ----------- } Beginning Single – threaded body of execution End

MULTITHREADED PROGRAM Main Thread _______________ Main method module start start start _______________ _______________ _______________ switching switching Thread A Thread B Thread C

7. A program that contains multiple flows of control is known as multithreaded program. 8. The above fig. is a java program with four threads, one main and three others. The main thread is actually the main method module, which is designed to create and start the other three threads, namely A, B and C 9. Once initiated by the main thread, the threads A, B and C run concurrently and share the resources jointly. The ability of a language to support multithreads is referred to as concurrency. 10. Threads in java are subprograms of main application program and share the same memory space, they are known as lightweight threads or lightweight processes.. Note: It is important to remember that ‘threads running in parallel’ does not really mean that they actually run at the same time. Since all the threads are running on a single processor, the flow of execution is shared between the threads.

1. Creating threads in Java is simple. 2. Threads are implemented in the form of objects that contain a method called run(). 3. The run() method is the heart and soul of any thread. It makes up the entire body of a thread and is the only method in which the thread’s behaviour can be implemented. 4. A typical run() would appear as follows: public void run() { ------------------ } Statements for implementing thread

5. The run() method should be invoked by an object for the concerned thread. 6. This can be achieved by creating the thread and initiating it with the help of another thread method called start(). 7. A new thread can be created in two ways. a. By creating a thread class: Define a class that extends Thread class and override its run() method with the code required by the thread. b. By converting a class to a thread: Define a class that implements Runnable interface. The Runnable interface has only one method, run(), that is to be defined in the method with the code to be executed by the thread.

EXTENDING THE THREAD CLASS We can make our class runnable as a thread by extending the class java.lang.Thread. This gives us access to all the thread methods directly. It includes the following steps: 1. Declare the class as extending the Thread class 2. Implement the run() method that is responsible for executing the sequence of code that the thread will execute. 3. Create a thread object and call the start() method to initiate the thread execution. 1. Declaring the class class MyThread extends Thread { --------------- }

2. Implementing the run() Method public void run() { ----------------- } Thread Code Here 3. Starting New Thread MyThread aThread = new MyThread(); aThread.start(); //Invoke run() method

Creating threads using the thread class class A extends Thread { public void run() for(int i = 1;i <= 5;i++) System.out.println("\tFrom Thread A : i = " + i); } System.out.println("Exit from A "); class B extends Thread for(int j = 1;j <= 5;j++) System.out.println("\tFrom Thread B : j = " + j); System.out.println("Exit from B ");

class C extends Thread { public void run() for(int k = 1;k <= 5;k++) System.out.println("\tFrom Thread C : k = " + k); } System.out.println("Exit from C "); class ThreadTest public static void main(String args[]) A a = new A(); B b = new B(); C c = new C(); a.start(); b.start(); c.start();

IMPLEMENTING THE ‘RUNNABLE’ INTERFACE The Runnable interface declares the run() method that is required for implementing threads in our programs. To do this, we must perform the steps listed below: 1. Declare the class an implementing the Runnable interface. 2. Implementing the run() method. 3. Create a thread by defining an object that is instanitiated form the “runnable” class as the target of the thread. 4. Call the thread’s start() method to run the thread.

import java.lang.Thread; class X implements Runnable { public void run() for(int i = 1;i <= 5;i++) System.out.println("\tFrom Thread A : i = " + i); } System.out.println("Exit from A "); class Y implements Runnable for(int j = 1;j <= 5;j++) System.out.println("\tFrom Thread B : j = " + j); System.out.println("Exit from B ");

class Z implements Runnable { public void run() for(int k = 1;k <= 5;k++) System.out.println("\tFrom Thread C : k = " + k); } System.out.println("Exit from C "); class RunnableTest public static void main(String args[]) X runnableX = new X(); Thread threadX = new Thread(runnableX); Y runnableY = new Y(); Thread threadY = new Thread(runnableY); Z runnableZ = new Z(); Thread threadZ = new Thread(runnableZ); threadX.start(); threadY.start(); threadZ.start();

LIFE CYCLE OF A THREAD During the life time of a thread, there are many states it can enter. They include Newborn state Runnable state Running state Blocked state Dead state

State Transition diagram of a Thread Newborn New Thread start stop Active Thread stop Runnable Dead Running yield Killed Thread suspend sleep wait resume notify stop Blocked Idle Thread (Not Runnable)

Newborn State When we create a thread object, the thread is born and is said to be in newborn state. The thread is not yet scheduled for running. At this state, we can do only one of the following things with it: 1. schedule it for funning using start() method. 2. kill it using stop() method. Newborn start stop Runnable state Dead State

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

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

2. sleep() It has been made to sleep, We can put a thread to sleep for a specified time period using the method sleep (time) where time is in milliseconds. This means that the thread is out of the queue during this time period. The thread re – enters the runnable state as soon as this time period is elapsed. sleep (t) after t Sleeping Running Runnable

Blocked State 3. wait() and notify() It has been told to wait until some event occurs. This is done using the wait() method. The thread can be scheduled to run again using the notify() method. wait() notify () Running Runnable Waiting Blocked State A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the running state. This happens when the thread is suspended, sleeping, or waiting in order to satisfy certain requirements. A blocked thread is considered “not runnable” but not dead therefore fully qualified to run again.

Dead State Every thread has life cycle. A running thread ends its life when it has completed executing its run() method. It is a natural death. However, we can kill it by sending the stop message to it at any state thus causing a premature death to it. A thread can be killed as soon it is born, or while it is running, or even when it is in “not runnable” (blocked) condition.

import java.lang.Thread; class A extends Thread { public void run() for(int i = 1;i <= 5;i++) if(i == 1) yield(); System.out.println("\tFrom Thread A : i = " + i); } System.out.println("Exit from A "); class B extends Thread for(int j = 1;j <= 5;j++) System.out.println("\tFrom Thread B : j = " + j); if(j==3) stop(); System.out.println("Exit from B ");

class C extends Thread { public void run() for(int k = 1;k <= 5;k++) System.out.println("\tFrom Thread C : k = " + k); if(k==1) try sleep(1000); } catch(Exception e) System.out.println("Exit from C "); class ThreadTest_1 public static void main(String args[]) A a = new A(); B b = new B(); C c = new C(); System.out.println("Start Thread A"); a.start(); System.out.println("Start Thread B"); b.start(); System.out.println("Start Thread C"); c.start(); System.out.println("End of main Thread");

final boolean isAlive() final void join() throws InterruptedException Using isAlive() and join() isAlive() Two ways exist to determine whether a thread has finished. First, you can call isAlive() on the thread. The method is defined by Thread, and its general form is shown here: final boolean isAlive() The isAlive() method returns true if the thread upon which it is called is still running. It returns false otherwise. join While isAlive() is occasinally useful, the method that you will more commonly use to wait for a thread to finish is called join(), shown here: final void join() throws InterruptedException This method waits until the thread on which it is called terminates. Its name comes from the concept of the calling thread waiting until the specified thread joins it.

class A extends Thread { public void run() for(int i = 1;i <= 5;i++) System.out.println("\tFrom Thread A : i = " + i); } System.out.println("Exit from A "); class B extends Thread for(int j = 1;j <= 5;j++) System.out.println("\tFrom Thread B : j = " + j); System.out.println("Exit from B ");

class C extends Thread { public void run() for(int k = 1;k <= 5;k++) System.out.println("\tFrom Thread C : k = " + k); } System.out.println("Exit from C "); class ThreadTest public static void main(String args[]) A a = new A(); B b = new B(); C c = new C();

System.out.println("Start Thread A"); a.start(); System.out.println("Start Thread B"); b.start(); System.out.println("Start Thread C"); c.start(); System.out.println("End of main Thread"); System.out.println("Thread One is Alive: " + a.isAlive()); System.out.println("Thread two is Alive: " + b.isAlive()); System.out.println("Thread three is Alive: " + c.isAlive()); try { a.join(); b.join(); c.join(); } catch(InterruptedException e) System.out.println("Main Thread Interrupted");

ThreadName.setPriority(intNumber); THREAD PRIORITY In java, each thread is assigned a prioriy, which affects the order in which it is scheduled for running. The threads of the same priority are given equal treatment by the Java scheduler and, therefore, they share the processor of a first – come, first – serve basis. ThreadName.setPriority(intNumber); The intNumber is an integer value to which the thread’s priority is set. The Thread class defines several priority constants: MIN_PRIORITY = 1 NORM_PRIORITY = 5 MAX_PRIORITY = 10 The intNumber may assume one of these constants or any value between 1 and 10. Note that the default setting is NORM_PRIORITY

import java.lang.Thread; class A extends Thread { public void run() for(int i = 1;i <= 5;i++) System.out.println("\tFrom Thread A : i = " + i); } System.out.println("Exit from A "); class B extends Thread for(int j = 1;j <= 5;j++) System.out.println("\tFrom Thread B : j = " + j); System.out.println("Exit from B ");

class C extends Thread { public void run() for(int k = 1;k <= 5;k++) System.out.println("\tFrom Thread C : k = " + k); } System.out.println("Exit from C "); class ThreadPriority public static void main(String args[]) A a = new A(); B b = new B(); C c = new C(); c.setPriority(5); //c.setPriority(NORM_PRIORITY); b.setPriority(10); //b.setPriority(MAX_PRIORITY); a.setPriority(1); //a.setPriority(MIN_PRIORITY); a.start(); b.start(); c.start();

APPLETS

What are the differences between Applets and Application? What is Applets? An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a page. When you use a Java technology-enabled browser to view a page that contains an applet, the applet's code is transferred to your system and executed by the browser's Java Virtual Machine (JVM). What are the differences between Applets and Application? Applets do not use the main() method for initiating the execution of the code. Applets, when loaded, automatically call certain methods of Applet class to start and execute the applet code. Unlike stand – alone applications, applets cannot be run independently. They are run from inside a Web page using a special feature known as HTML tag. Applets cannot read from or write to the files in the local computer. Applets cannot communicate with other servers on the network. Applets cannot run any program from the local computer. Applets are restricted from using libraries from other languages such as C or C++. (Java language supports this feature through native methods.)

Applet Architecture An applet is a window – based program. First, applets are event driven. Event – driven architecture impacts the design of an applet. An applet resembles a set of interrupt service routines. An applet waits until an event occurs. The AWT notifies the applet about an event by calling an event handler appropriate action and then quickly return control to the AWT. Second, the user initiates interaction with an applet - not the other way around. As you know, in a non - windowed program, when the program needs input, it will prompt the user and then call some input method, such as readLine(). This not the way it works in an applet. Instead, the user interacts with the applet as he or she wants, when must respond. For example, when the user clicks a mouse inside the applet’s window, a mouse – clicked event is generated. If the user presses a key while the applet’s window has input focus, a keypress event is generated. Applets can contain various controls, such as push buttons and check boxes.

Applet Architecture . . . . 12. When the user interacts with one of these controls, an event is generated. 13. While the architecture of an applet is not as easy to understand as that of a console – based program, Java’s AWT makes it as simple as possible. 14. If you have written programs for windows, you know how intimidating that environment can be. 15. Fortunately, Java’s AWT provides a much cleaner approach that is more quickly mastered.

An Applet Skeleton or Applet Life Cycle Born Begin (Load Applet) Initialization start( ) Running stop( ) Idle Stopped start( ) Display paint( ) destroy( ) Dead End Destroyed Exit of Browser

An Applet Skeleton or Applet Life Cycle All but the the most trivial applets override a set of methods that provides the basic mechanism by which the browser or applet viewer interfaces to the applet and controls its execution. Four of these methods – init( ), start( ), stop( ), and destroy( ) – are defined by Applet. Another, paint(), is defined by the AWT Component class. Default implementations for all of these methods are provided. Applets do no need to override those methods they do not use. However, only very simple applets will not need to define all of them. The applet states is: 1. Born or initialization state 2. Running state 3. Idle state 4. Dead or destroyed state 5. Display state

Initialization State Applet enters the initialisation state when it is first loaded. This is achieved by calling the init() method of Applet Class. The applet is born. At this stage, we may do the following, if required, a. Create objects needed by the applet. b. Set up initial values c. Load images or fonts d. set up colors public void init( ) { ----------------- } Action

2. Running State Applets enters the running state when the system call the start () method of Applet Class. This occurs automatically after the applet is initailized. Starting can also occur if the applet is already in “stopped” state. For example, we may leave the web page containing the applet temporarily to another page and return back to the page. This again starts the applet running. Note that, unlike init() method, the start() method may be called more than once. We may override the start() method to create a threa to control the applet. public void start( ) { ----------------- } Action

3. Idle or Stopped State An applet becomes idle when it is stopped from running. Stopping occurs automatically when we leave the page containing the currently running applet. We can also do so by calling the stop() method explicitly. If we use a thread to run the applet, then we must use stop() method to terminate the thread. We can achieve by overriding the stop( ) method: public void stop( ) { ----------------- } Action

4. Dead State An applet is said to be dead when it is removed from memory. This occurs automatically by invoking the destroy( ) method when we quit the browser. Like initialization, destroying stage occurs only once in the applet’s life cycle. If the applet has created any resources. Like threads we may override the destroy( ) method to clean up these resouces. public void destroy( ) { ----------------- } Action

5. Display State Applet moves to the display state whenever it has to perform some output operations on the screen. This happens immediately after the applet enters into the running state. The paint() method is called to accomplish this task. Almost every applet will have a paint() method. Like other methods in the life cycle, the default version of paint() method does absolutely nothing. We must therefore override this method if we want anything to be displayed on the screen. public void paint (Graphics g) { ----------------- } Display Statements

Specified Colors Specified Colors Color.black 10. Color.pink import java.awt.*; import java.applet.*; /* <applet code = "AppletDemo" width = 300 height = 300> </applet> */ public class AppletDemo extends Applet { String msg; public void init() setBackground(Color.cyan); } public void start() msg += "This is Start method"; public void stop() msg += "This is Stop method"; public void destroy() msg += "This is Destroy method"; public void paint(Graphics g) g.drawString(msg,100,100); Specified Colors Color.black Color.blue Color.cyan Color.darkGray Color.gray Color.green Color.lightGray Color.magenta Color.orange Specified Colors 10. Color.pink 11. Color.red 12. Color.white 13. Color.yellow

How the applets to be displayed in the Browser <HTML> <HEAD> <TITLE>WELCOME TO cHETTINAD</TITLE> </HEAD> <BODY> <APPLET CODE = AppletDemo.class WIDTH = 300 HEIGHT = 200 </APPLET> </BODY> </HTML>

The HTML APPLET Tag < APPLET [CODEBASE = codebaseURL] CODE = appletFile [ALT = alternateText] [NAME = appletInstanceName] WIDTH = pixels HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels] [HSPACE = pixels] > [<PARAM NAME = AttributeName VALUE = AttributeValue>] . . . . . . . [HTML Displayed in the absence of Java] </APPLET>

ATTRIBUTE MEANING CODE = AppletFileName.class Specifies the name of the applet class to be loaded. That is, the name of the already – compiled .class file in which the executable. Java bytecode for the applet is stored. This attribute must be specified. CODEBASE = codebase_URL (Optional) Specifies the URL of the directory in which the applet resides. If the applet resides in the same directory as the HTML file, then the CODEBASE attirbute may be omitted entirely. WIDTH = pixels HEIGHT = pixels These attributes specify the width and height of the space on the HTML page that will be reserved for the applet. NAME=applet_instance_name A name for the applet may optionally be specified so that other applets on the page may refer to this applet. This facilitates inter applet communication. ALIGN = alignment This optional attribute specifies where on the page the applet will appear. Possible values for alignment are TOP, BOTTOM, LEFT, RIGHT, MIDDLE, ABSMIDDLE, ABSBOTTOM, TEXTTOP, AND BASELINE. HSPACE = pixels Used only when ALIGN is set to LEFT or RIGHT , this attribute specifies the amount of horizontal blank space the browser should leave surrounding the applet. VSPACE = pixels Used only when some vertical alignment is specified with the ALIGN attribute (TOP, BOTTOM, etc.,) VSPACE specifes the amount of vertical blank space the browser should leave surrounding the applet. ALT = alternate_text Non – java browser will display this text where the applet would normally go. This attribute is optional. PARAM NAME AND VALUE The PARAM tag allows you to specify applet – specific arguments in an HTML page. Applets access their attributes with the getParameter() method

Passing Parameters to Applets import java.awt.*; import java.applet.*; /* <applet code="ParamDemo" width = 300 height = 300> <param name = fontName value=Courier> <param name = fontSize value = 30> <param name = leading value=2> <param name = accountEnabled value = true> </applet> */ public class ParamDemo extends Applet { String fontName; int fontSize; float leading; boolean active; public void start() String param; fontName = getParameter("fontName"); if(fontName == null) fontName = "Not Found";

param = getParameter("fontSize"); try { if(param != null) //if not found fontSize = Integer.parseInt(param); else fontSize = 0; } catch(NumberFormatException e) fontSize = -1; param = getParameter("leading"); if(param != null) //if not found leading = Float.valueOf(param).floatValue(); leading = 0; leading = -1;

param = getParameter("accountEnabled"); if(param != null) active = Boolean.valueOf(param).booleanValue(); } public void paint(Graphics g) { g.drawString("Font name: " + fontName,0,10); g.drawString("Font Size: " + fontSize,0,20); g.drawString("Leading: " + leading, 0,42); g.drawString("Account Active: " + active,0,58);

getCodeBase() and getDocumentBase() import java.awt.*; import java.applet.*; import java.net.*; /* <applet code=ParamDemo_2.class width = 300 height = 300> </applet> */ public class ParamDemo_2 extends Applet { public void paint(Graphics g) String msg; URL url = getCodeBase(); msg = "Code Base: " + url.toString(); g.drawString(msg,10,20); url = getDocumentBase(); msg = "Document Base: " + url.toString(); g.drawString(msg,10,40); }

The AudioClip Interface The AudioClip interface defines these methods: 1. play ( ) – play a clip from the beginning. 2. stop ( ) – stop playing the clip. 3. loop ( ) – play the loop continuously. 4. getAudioClip ( ) - After you have loaded an audio clip import java.applet.*; import java.awt.event.*; import java.awt.*; /* <applet code=SoundExample width = 300 height = 300> </applet> */ public class SoundExample extends Applet implements MouseListener { AudioClip soundFile1; AudioClip soundFile2;

addMouseListener(this); setBackground(Color.yellow); public void init() { soundFile1 = getAudioClip(getDocumentBase(),"c:\\windows\\media\\ding.wav"); soundFile2 = getAudioClip(getDocumentBase(),"c:\\windows\\media\\start.wav"); addMouseListener(this); setBackground(Color.yellow); soundFile1.play(); } public void paint(Graphics g) g.drawString("Click to hear a sound",20,20); public void mouseClicked(MouseEvent evt) soundFile2.play(); public void mousePressed(MouseEvent evt) {} public void mouseReleased(MouseEvent evt) {} public void mouseEntered(MouseEvent evt) {} public void mouseExited(MouseEvent evt) {}

AppletStub Interface The AppletStub interface provides a way to get information from the run-time browser environment. The Applet class provides methods with similar names that call these methods. Methods public abstract boolean isActive () The isActive() method returns the current state of the applet. While an applet is initializing, it is not active, and calls to isActive() return false. The system marks the applet active just prior to calling start(); after this point, calls to isActive() return true. public abstract URL getDocumentBase () The getDocumentBase() method returns the complete URL of the HTML file that loaded the applet. This method can be used with the getImage() or getAudioClip() methods to load an image or audio file relative to the HTML file. public abstract URL getCodeBase () The getCodeBase() method returns the complete URL of the .class file that contains the applet. This method can be used with the getImage() method or the getAudioClip() method to load an image or audio file relative to the .class file.

public abstract String getParameter (String name) The getParameter() method allows you to get parameters from <PARAM> tags within the <APPLET> tag of the HTML file that loaded the applet. The name parameter of getParameter() must match the name string of the <PARAM> tag; name is case insensitive. The return value of getParameter() is the value associated with name; it is always a String regardless of the type of data in the tag. If name is not found within the <PARAM> tags of the <APPLET>, getParameter() returns null. public abstract void appletResize (int width, int height) The appletResize() method is called by the resize method of the Applet class. The method changes the size of the applet space to width x height. The browser must support changing the applet space; if it doesn't, the size remains unchanged.