Presentation is loading. Please wait.

Presentation is loading. Please wait.

I – UNIT Procedure Oriented Programming

Similar presentations


Presentation on theme: "I – UNIT Procedure Oriented Programming"— Presentation transcript:

1 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

2 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.

3 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.

4 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.

5 BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING
Class 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.

6 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,

7 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.

8 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

9 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.

10 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.

11 Network of objects communicating between them

12 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.

13 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.

14 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

15 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.

16 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.

17 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.

18 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.

19 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++); }

20 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.

21 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.

22

23 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

24 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

25 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

26 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

27 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

28 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: Valid Ex: ,000 $ Invalid Hexadecimal integer Literals Ex: 0X2 0X9F 0Xbcd 0x 28

29 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 Such numbers are called real (or floating point) numbers. Further examples of real literals are: 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, are all valid real literals. A real literal may also be expressed in exponential (or scientific) notation. For example, the value may be written as e2 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

30 Embedded white (blank) space is not allowed in any numeric constant.
Example: 0.65e4 12e e+5 3.18E E-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, may be written as 7.5E9 or 75E8. Similarly, , 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

31 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

32 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

33 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

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

35 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: Valid Ex: ,000 $ Invalid Hexadecimal integer Constants Ex: 0X2 0X9F 0Xbcd 0x 35

36 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 Such numbers are called real (or floating point) numbers. Further examples of real Constants are: 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, are all valid real constants. A real literal may also be expressed in exponential (or scientific) notation. For example, the value may be written as e2 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

37 Embedded white (blank) space is not allowed in any numeric constant.
Example: 0.65e4 12e e+5 3.18E E-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, may be written as 7.5E9 or 75E8. Similarly, , 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

38 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

39 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

40 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

41 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

42 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

43 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.

44 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

45 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

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

47 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

48 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

49 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:

50 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); }

51 OPERATORS 51

52 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: / 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

53 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

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

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

56 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

57 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

58 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

59 DECISION MAKING – BRANCHING and LOOPING
59

60 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

61 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

62 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

63 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

64 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

65 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

66 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

67 ARRAY 67

68 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

69 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

70 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

71 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;

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

73 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

74 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]); }

75 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

76 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

77 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

78 CLASS FUNDAMENTALS

79 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)

80 // 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);

81 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.

82 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();

83 // 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(); }

84 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;

85 // 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(); }

86 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;

87 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(); }

88 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;

89 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(); }

90 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;

91 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(); }

92 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.

93 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 }

94 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;

95 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); }

96 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

97 // 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;

98 // 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); }

99 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));

100 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);

101 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; } }

102 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()); }

103 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.

104 class UseStatic { static int a = 3; static int b; static void meth(int x) System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b); } static System.out.println("Static block initialized."); b = a * 4; public static void main(String args[ ]) meth(42);

105 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.

106 // 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(); } }

107 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 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

108 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

109 INHERITANCE

110 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.

111 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

112 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

113 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;

114 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

115 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

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

117 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));

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

119 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));

120 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();

121 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));

122 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();

123 INHERITANCE WITH super KEYWORD

124 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.

125 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));

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

127 //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));

128 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();

129 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(); } }

130 Inheritance with Method Overriding

131 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.

132 //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();

133 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();

134 Inheritance with Abstract Class

135 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.

136 //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( ); } }

137 Inheritance with final Keyword

138 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); }

139 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();

140 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();

141 Interface

142 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 { }

143 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(); }

144 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);

145 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.

146 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.

147 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

148 A B C D Interface Implementation Class Extension

149 // 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

150 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)); }

151 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

152 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);

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

154 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

155 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();

156 Package

157 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.

158 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.

159 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;

160 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(); }

161 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

162 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); }

163 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); }

164 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); }

165 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); }

166 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); }

167 String functions

168 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()); }

169 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); }

170 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: " ; System.out.println(s2); String s3 = "four: " + (2 + 2); System.out.println(s3); }

171 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 + ".";

172 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); }

173 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); }

174 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); }

175 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); }

176 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); }

177 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.

178 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)); }

179 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)

180 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); }

181 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); }

182 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.

183 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.

184 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 }

185 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); }

186 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); }

187 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); }

188 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)

189 (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. }

190 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()); }

191 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); }

192 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.

193 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)); }

194 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); }

195 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) + "."); }

196 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) + "."); }

197 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); }

198 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); } }

199 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(); }

200 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); }

201 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); }

202 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); }

203 UNIT – III Balance Chapters

204 THE CHARACTER STREAMS

205 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.

206 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.

207 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.

208 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.

209 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.

210 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();

211 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.

212 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());

213 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.

214 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)

215 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.

216 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'); } }

217 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.

218 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); }

219 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.

220 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(); }

221 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.

222 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); } } }

223 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.

224 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); }

225 SERIALIZATION

226 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.

227 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.

228 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.

229 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.

230 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.

231 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.

232 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.

233 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.

234 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.

235 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);

236 //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; } }

237 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

238 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

239 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

240 UNIT - V

241 StringTokenizer The processing of text often consists of parsing a formatted input string. Parsing is the division of text into a set of discrete parts, or tokens, which in a certain sequence can convey a semantic meaning. The StringTokenizer class provides the first step in this parsing process, often called the lexer (lexical analyzer) or scanner. StringTokenizer implements the Enumeration interface. Therefore, given an input string, you can enumerate the individual tokens contained in it using StringTokenizer. To use StringTokenizer, you specify an input string and a string that contains delimiters. Delimiters are characters that separate tokens. Each character in the delimiters string is considered a valid delimiter—for example, “,;:” sets the delimiters to a comma, semicolon, and colon. The default set of delimiters consists of the whitespace characters: space, tab, newline, and carriage return. The StringTokenizer constructors are shown here: StringTokenizer(String str) StringTokenizer(String str, String delimiters) StringTokenizer(String str, String delimiters, boolean delimAsToken)

242

243 import java.util.StringTokenizer;
class STDemo { static String in = "title=Java: The Complete Reference;" + "author=Schildt;" + "publisher=Osborne/McGraw-Hill;" + "copyright=2002"; public static void main(String args[]) StringTokenizer st = new StringTokenizer(in, "=;"); while(st.hasMoreTokens()) String key = st.nextToken(); String val = st.nextToken(); System.out.println(key + "\t" + val); }

244 BitSet A BitSet class creates a special type of array that holds bit values. This array can increase in size as needed. This makes it similar to a vector of bits. The BitSet constructors are shown here: The first version creates a default object. The second version allows you to specify its initial size (that is, the number of bits that it can hold). All bits are initialized to zero. BitSet implements the Cloneable interface and defines the methods. BitSet( ) BitSet(int size)

245

246

247 // BitSet Demonstration.
import java.util.BitSet; class BitSetDemo { public static void main(String args[]) BitSet bits1 = new BitSet(16); BitSet bits2 = new BitSet(16); // set some bits for(int i=0; i<16; i++) if((i%2) == 0) bits1.set(i); if((i%5) != 0) bits2.set(i); } System.out.println("Initial pattern in bits1: "); System.out.println(bits1); System.out.println("\nInitial pattern in bits2: "); System.out.println(bits2); // AND bits bits2.and(bits1); System.out.println("\nbits2 AND bits1: "); // OR bits bits2.or(bits1); System.out.println("\nbits2 OR bits1: "); // XOR bits bits2.xor(bits1); System.out.println("\nbits2 XOR bits1: ");

248 Calendar The abstract Calendar class provides a set of methods that allows you to convert a time in milliseconds to a number of useful components. Some examples of the type of information that can be provided are: year, month, day, hour, minute, and second. It is intended that subclasses of Calendar will provide the specific functionality to interpret time information according to their own rules. This is one aspect of the Java class library that enables you to write programs that can operate in several international environments. An example of such a subclass is GregorianCalendar. Calendar provides no public constructors. Calendar defines several protected instance variables. areFieldsSet is a boolean that indicates if the time components have been set. fields is an array of ints that holds the components of the time. isSet is a boolean array that indicates if a specific time component has been set. time is a long that holds the current time for this object. isTimeSet is a boolean that indicates if the current time has been set.

249 Calendar defines the following int constants, which are used when you get or set components of the calendar:

250

251

252

253 // Demonstrate Calendar
import java.util.Calendar; class CalendarDemo { public static void main(String args[]) String months[] = {"Jan", "Feb", "Mar", "Apr","May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; // Create a calendar initialized with the // current date and time in the default // locale and timezone. Calendar calendar = Calendar.getInstance(); // Display current time and date information. System.out.print("Date: "); System.out.print(months[calendar.get(Calendar.MONTH)]); System.out.print(" " + calendar.get(Calendar.DATE) + " "); System.out.println(calendar.get(Calendar.YEAR)); System.out.print("Time: "); System.out.print(calendar.get(Calendar.HOUR) + ":"); System.out.print(calendar.get(Calendar.MINUTE) + ":"); System.out.println(calendar.get(Calendar.SECOND)); // Set the time and date information and display it. calendar.set(Calendar.HOUR, 10); calendar.set(Calendar.MINUTE, 29); calendar.set(Calendar.SECOND, 22); System.out.print("Updated time: "); }

254 GregorianCalendar GregorianCalendar is a concrete implementation of a Calendar that implements the normal Gregorian calendar with which you are familiar. The getInstance( ) method of Calendar returns a GregorianCalendar initialized with the current date and time in the default locale and time zone. GregorianCalendar defines two fields: AD and BC. These represent the two eras defined by the Gregorian calendar. There are also several constructors for GregorianCalendar objects. The default, GregorianCalendar( ), initializes the object with the current date and time in the default locale and time zone. Three more constructors offer increasing levels of specificity: GregorianCalendar(int year, int month, int dayOfMonth) GregorianCalendar(int year, int month, int dayOfMonth, int hours, int minutes) GregorianCalendar(int year, int month, int dayOfMonth, int hours, int minutes, int seconds) All three versions set the day, month, and year. Here, year specifies the number of years that have elapsed since The month is specified by month, with zero indicating January. The day of the month is specified by dayOfMonth. The first version sets the time to midnight. The second version also sets the hours and the minutes. The third version adds seconds.

255 boolean isLeapYear(int year)
You can also construct a GregorianCalendar object by specifying either the locale and/or time zone. The following constructors create objects initialized with the current date and time using the specified time zone and/or locale: GregorianCalendar(Locale locale) GregorianCalendar(TimeZone timeZone) GregorianCalendar(TimeZone timeZone, Locale locale) GregorianCalendar provides an implementation of all the abstract methods in Calendar. It also provides some additional methods. Perhaps the most interesting is isLeapYear( ), which tests if the year is a leap year. Its form is boolean isLeapYear(int year) This method returns true if year is a leap year and false otherwise.

256 import java.util.*; class GregorianCalendarDemo { public static void main(String args[]) String months[] = {"Jan", "Feb", "Mar", "Apr","May", "Jun", "Jul", "Aug","Sep", "Oct", "Nov", "Dec"}; int year; // Create a Gregorian calendar initialized // with the current date and time in the // default locale and timezone. GregorianCalendar gcalendar = new GregorianCalendar(); // Display current time and date information. System.out.print("Date: "); System.out.print(months[gcalendar.get(Calendar.MONTH)]); System.out.print(" " + gcalendar.get(Calendar.DATE) + " "); System.out.println(year = gcalendar.get(Calendar.YEAR)); System.out.print("Time: "); System.out.print(gcalendar.get(Calendar.HOUR) + ":"); System.out.print(gcalendar.get(Calendar.MINUTE) + ":"); System.out.println(gcalendar.get(Calendar.SECOND)); // Test if the current year is a leap year if(gcalendar.isLeapYear(year)) System.out.println("The current year is a leap year"); } else { System.out.println("The current year is not a leap year");

257 TimeZone Another time-related class is TimeZone. The TimeZone class allows you to work with time zone offsets from Greenwich mean time (GMT), also referred to as Coordinated Universal Time (UTC). It also computes daylight saving time. TimeZone only supplies the default constructor.

258

259 import java.util.*; public class TimeZones { public static void main(String[] args) Date date = new Date(); String TimeZoneIds[] = TimeZone.getAvailableIDs(); for(int i = 0; i < TimeZoneIds.length; i++) TimeZone tz = TimeZone.getTimeZone(TimeZoneIds[i]); String tzName = tz.getDisplayName(tz.inDaylightTime(date), TimeZone.LONG); System.out.print(TimeZoneIds[i] + ": "); // Get the number of hours and minutes from GMT int rawOffset = tz.getRawOffset(); int hour = rawOffset / (60*60*1000); int minute = Math.abs(rawOffset / (60*1000)) % 60; System.out.println(tzName + " " + hour + ":" + minute); }

260 Locale The Locale class is instantiated to produce objects that each describe a geographical or cultural region. It is one of several classes that provide you with the ability to write programs that can execute in several different international environments. For example, the formats used to display dates, times, and numbers are different in various regions. Internationalization is a large topic that is beyond the scope of this book. However, most programs will only need to deal with its basics, which include setting the current locale. The Locale class defines the following constants that are useful for dealing with the most common locales: CANADA GERMAN KOREAN CANADA_FRENCH GERMANY PRC CHINA ITALIAN SIMPLIFIED_CHINESE CHINESE ITALY TAIWAN ENGLISH JAPAN TRADITIONAL_CHINESE FRANCE JAPANESE UK FRENCH KOREA US

261 static void setDefault(Locale localeObj)
For example, the expression Locale.CANADA represents the Locale object for Canada. The constructors for Locale are Locale(String language) Locale(String language, String country) Locale(String language, String country, String data) These constructors build a Locale object to represent a specific language and in the case of the last two, country. These values must contain ISO-standard language and country codes. Auxiliary browser and vendor-specific information can be provided in data. The first constructor was added by Java 2, version 1.4. Locale defines several methods. One of the most important is setDefault( ), shown here: static void setDefault(Locale localeObj) This sets the default locale to that specified by localeObj. Some other interesting methods are the following: final String getDisplayCountry( ) final String getDisplayLanguage( ) final String getDisplayName( )

262 import java.text.*; import java.util.Locale; public class SettingLocale { public static void main(String[] args) // Getting default locale Locale locale = Locale.getDefault(); System.out.println("Before setting, Locale is = " + locale); // Setting default locale locale = Locale.ITALY; Locale.setDefault(locale); System.out.println("After setting, Locale is = " + locale); }

263 Random The Random class is a generator of pseudorandom numbers. These are called pseudorandom numbers because they are simply uniformly distributed sequences. Random defines the following constructors: Random( ) Random(long seed) The first version creates a number generator that uses the current time as the starting, or seed, value. The second form allows you to specify a seed value manually.

264 // Demonstrate random Gaussian values.
import java.util.Random; class RandDemo { public static void main(String args[]) Random r = new Random(); for(int i=0; i<100; i++) System.out.println("The Next Gaussian Number is:" r.nextGaussian()); }

265 Currency Java 2, version 1.4 adds the Currency class. This class encapsulates information about a currency. It defines no constructors.

266 // Demonstrate Currency.
import java.util.*; class CurDemo { public static void main(String args[]) Currency c; c = Currency.getInstance(Locale.US); System.out.println("Symbol: " + c.getSymbol()); System.out.println("Default fractional digits: " c.getDefaultFractionDigits()); }

267 JDBC – ODBC DRIVERS

268 JDBC DRIVERS Type of JDBC Drivers
The JDBC API defines the Java interfaces and classes that programmers use to connect to databases and send queries. A JDBC driver implements these interfaces and classes for a particular DBMS vendor. A Java program that uses the JDBC API loads the specified driver for a particular DBMS before it actually connects to a database. The JDBC DriverManager class then sends all JDBC API calls to the loaded driver. Type of JDBC Drivers JDBC – ODBC Bridge Native – API Partly Java Driver JDBC – Net pure Java Driver Native – Protocol Pure Java Driver

269 JDBC – ODBC bridge plus ODBC driver, also called Type 1.
Translates JDBC API calls into Microsoft Open Database Connectivity (ODBC) calls that are then passed to the ODBC driver. The ODBC binary code must be loaded on every client computer that uses this type of driver. Native – API, partly Java driver, also called Type 2. Converts JDBC API calls into DBMS-specific client API calls. Like the bridge driver, this type of driver requires that some binary code be loaded on each client computer. JDBC – Net, pure Java driver, also called Type 3. Sends JDBC API calls to a middle-tier net server that translates the calls into the DBMS-specific network protocol. The translated calls are then sent to a particular DBMS. Native – protocol, pure Java driver, also called Type 4. Converts JDBC API calls directly into the DBMS-specific network protocol without a middle tier. This allows the client applications to connect directly to the database server.

270 JDBC Implementation JDBC is implemented as the java.sql.package. Some of the classes of this package are: CLASSES PACKAGES Drivers java.sql.Driver java.sql.DriverManager java.sql.DriverPropertyInfo Connection java.sql.Connection Statements java.sql.Statement java.sql.PreparedStatement java.sql.CallableStatement ResultSet java.sql.ResultSet Exceptions java.sql.SQLException Date java.sql.Date

271 Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
How to Java Application or Applets Connected to the Database Loading the Driver Making the Connection Creating and Executing a JDBC statement Retrieving Data From the Result Sets Loading the Driver If you are using the JDBC – ODBC Bridge driver, use the following statement to load it. Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); 2. Making the Connection To get the driver connected to the database, which is done by creating a Connection object and initializing it with connection obtained from the DriverManager Connection con = DriverManager.getConnection(url, “LoginName”, “pwd”);

272 Statement stmt = con.createStatement();
3. Creating and executing a JDBC statement a. A statement object is used to send the SQL statement to the database. b. You create a statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. c. For a SELECT statement, the method used is executeQuery. For statements that create or modify tables, the method used is executeUpdate Statement stmt = con.createStatement(); Example: stmt.executeQuery (SELECT * FROM MARK WHERE SLNO = "+ t1.getText() +"“); Stmt.executeUpdate(UPDATE MARK SET SLNO="+ s1 +",NAME='"+ s2 +"' WHERE SLNO="+ s1 +“);

273 ResultSet rs = stmt.executeQuery (“select * from mark”);
4. Retrieving Data from the Result Sets JDBC uses ResultSet object to return the output. So the previous executeQuery statement can be fully written as: ResultSet rs = stmt.executeQuery (“select * from mark”);

274 IMPORTANT PROGRAMS

275 JAVA APPLICATION PROGRAMS
Simple Interest Calculation Interest = P * N * R P -> Principal Amount N -> No. of Periods R -> Rate of Interest Compound Interest Calculation Interest = P(1+(R/100))n n -> No. of Periods Celsius to Fahrenheit and Fahrenheit to Celsius

276 Write a simple menu driven calculator program using switch statement.
Write a program for Electricity Bill Preparation for the following condition: 1 – 50 Units paise 51 – 100 Units paise 101 – 200 Units - Rs. 1.50 201 – 600 Units - Rs. 2.20 Above 600 Units - Rs. 3.50 Write a program to Multiply for the two Matrices, Addition of the two Matrics and Subtraction of Two Matrics. Write a program to find factorial of a given number Write a program to check whether the given no is Palindrome or Not Write a program to sort numbers in an array in ascending order and descending order

277 Applet Programs Write a program to given no. is prime or Not.
Write a program to generate Fibonacci Series Up to N numbers. Applet Programs Write a applet program to the creating Student Mark Statement. Write a applet program to the creating Empolyee Salary Bill Preparation. Write a applet program to the creating EB Bill Preparation. Write a applet program to the Inventory Management System. Write a applet program to the Hospital Management System.

278 Write a applet program to the creating User Authentication (username and password)
Write a applet program to the following Events 1. ActionEvent 2. AdjustmentEvent 3. FocusEvent 4. ItemEvent 5. MouseEvent (including MouseMotion) 6. KeyEvent 7. TextEvent Write a applet program to the JDBC – ODBC drivers program for the above Applet program.

279 THE END


Download ppt "I – UNIT Procedure Oriented Programming"

Similar presentations


Ads by Google