Download presentation
Presentation is loading. Please wait.
1
Introduction to Software Engineering
Rajkumar Buyya Grid Computing and Distributed Systems Lab Dept. of Computer Science and Software Engineering University of Melbourne, Australia
2
Software Engineering - Introduction
Software Engineering is an engineering discipline which is concerned with all aspects of software production from the early stages of system requirements through to maintaining the system after is has gone into use.
3
Software Engineering/Computer Science
Computer Science is concerned with the theories and methods which underlie computers and software systems. Software Engineering is concerned with the practical problem of producing software.
4
Notes “Engineering discipline” – Engineers make things work. They apply theories, methods and tools that are appropriate but use them selectively and always try to discover solutions to problems even when there are not applicable theories and methods to support them. Engineers have to work to organizational and financial constraints. “All aspects of” - Software engineering is not just concerned with the technical process of software development but also with activities such as software project management and the development of tools, methods and theories to support software production.
5
Software Crisis Have you ever received a bill for $0.00 ?
Did you respond by sending a cheque for $0 Have you any idea what this cheque did for our computer system ? Whether we dealing with billing software or word processing, software is being delivered: Over Time Over Budget Low Quality Full of bugs/residual faults Software engineering is an attempt to solve these problems.
6
Aspects of Software Engineering
Historical Aspects Economical Aspects Maintenance Aspect Team Programming Aspects Design and Programming Aspects
7
Historical Aspects It is a fact that electric generators fail, but far less frequently than payroll products. It is true that bridges/cars/aero-planes sometimes collapse, but considerably less often than operating systems (e.g. MS Windows) do. In the belief that software could be engineered on the same footing as traditional engineering disciplines, a NATO study group coined the term “Software Engineering” in 1967. This was endorsed by the NATO Software Engineering Conference in 1968. The conclusion of the conference was that software engineering should use philosophies and practices in other engineering disciplines to avoid software crisis.
8
Scope of Software Engineering
Why cannot other engineering techniques be used to build operating systems? Attitude to collapse Imperfect engineering Complexity Maintenance
9
Examples of Attitudes on Software
People have the attitude that software collapse is not considered and unusual occurrence and therefore don’t pay as much attention to design. How many you rebooted your Microsoft Windows OS? Most of the time software engineers do not pay due attention to error scenarios, boundary conditions etc. Divide by Zero conditions. Complexity of software is growing faster than the rate we can master it. How many versions/bug fixes MS released within few years ? As a part of regular maintenance software engineers are expected to do major changes to software which is not the case in other fields of engineering. Actually this has become survival strategy for companies like MS. Releasing new version every few months.
10
Economic Aspects Techniques should be economically viable
A new coding method (CM_new) is 10% faster than the currently used method (CM_old). Should it be used? Common sense answer Of course Software Engineering answer What is the cost?
11
Maintenance Aspects Life Cycle – The series of steps software undergoes: Requirements- Understand what the client wants Specification – Understand what the product is supposed to do Design – Identify the modules and the design Implementation – Write code and unit test Integration – Combine modules and test Maintenance – Fixing problems and enhancements Retirement – Product is no longer in use
12
Relative Cost/Effort
13
Cost to Detect and Fix Faults
Relative Cost to detect and correct fault Projects between
14
Team Programming Aspect
Large software products are developed by large software teams. Members have different responsibilities e.g. – requirements, design, implementation, integration testing. Activities between teams have to be well organized for efficiency. e.g. – meetings, interfaces
15
Software Design/Programming Aspects
Design Principles
16
Overview Introduce two commonly used design paradigms.
Structured Design paradigm Object Oriented Design paradigm Understand general design principles.
17
Software Design - History
Before 1975 most organizations did not use specific design techniques. 1975 – Structured Paradigm was introduced. Structured paradigm had certain short comings especially for large programs. Object Oriented paradigm was introduced and has become popular today.
18
Structured Paradigm Structured Designs are Action (Function) Oriented
Data Oriented But not both
19
Object Oriented Paradigm
Both data and actions are of equal importance. Systems is a collection of interacting Objects. Object Software component that incorporates DATA and the ACTIONS that are performed on the data.
20
Structured vs OO Example
message Account balance Withdraw Deposit Determine Withdraw Deposit message Account balance Determine Balance message (b) Object Oriented Paradigm (a) Structured Paradigm
21
Summary Software Engineering is an important discipline due to increased dependence of most of our modern life (e.g., banking, entertainment) on its products! By proper software engineering practices software can be built with: Quality Maintainability On Time On Budget
22
Reference Stephen Schach, Classical and Object-Oriented Software Engineering with UML and Java, Chapter 1, McGraw-Hill, New York, USA. Any other book on software engineering is also fine!
23
Software Life Cycle and Models
Rajkumar Buyya Grid Computing and Distributed Systems Lab Dept. of Computer Science and Software Engineering University of Melbourne, Australia
24
Software Process Software Process defines the way to produce software. It includes Software life-cycle model Tools to use Individuals building software Software life-cycle model defines how different phases of the life cycle are managed.
25
Phases of Software Life-cycle
Requirements Specification (Analysis) Design Implementation Integration Maintenance Retirement
26
Requirements Assumption Concept exploration
The software being considered is considered economically justifiable. Concept exploration Determine what the client needs, not what the client wants Document - Requirements Document
27
Specification (Analysis) Phase
From the customer requirements identify what to build. Specifications must not be Ambiguous Incomplete Contradictory Document – Specification Document
28
Design Phase From the specification identify how to build.
Design involves two steps Architectural Design – Identify modules Detailed Design – Design each modules Document – Architecture Document, Design Document
29
Implementation Phase Implement the detailed design in code.
Developer testing Unit testing Module testing Document – Commented source code
30
Integration Phase Combine the modules and test the product as a whole.
Testing includes Product testing Acceptance testing Document – Test cases and test results
31
Maintenance Phase Any changes after the customer accepts the system.
Maintenance phase is the most expensive Lack of documentation Regression testing Document – Documented Changes, Regression test cases
32
Retirement Phase Good software is maintained
Sometimes software is rewritten from scratch Software is now un-maintainable because A drastic change in design has occurred The product must be implemented on a totally new hardware/operating system Documentation is missing or inaccurate Hardware is to be changed—it may be cheaper to rewrite the software from scratch than to modify it True retirement is a rare event
33
Life-Cycle Models Build-and-fix model Waterfall model
Rapid prototyping model Incremental model Extreme programming Synchronize-and-stabilize model Spiral model Object-oriented life-cycle models Comparison of life-cycle models
34
Build and Fix Model
35
Notes Most software is developed using build-and-fix model. Basically there is no model. No specifications No design This model is completely unsatisfactory and should not be adopted. Need life-cycle model “Game plan” Phases Milestones
36
Waterfall Model
37
Notes Output from one phase is fed as input to the next phase.
One phase is completed, documented and signed-off before the next phase begins. Advantages Each phase is well documented. Maintenance easier. Disadvantages If there is a mismatch between what the client wanted and was is built this will not be known till the product is delivered.
38
Rapid Prototyping Model
39
Notes A prototype of the product is build rapidly and shown to the client before the product is completely built. Advantages : Any mismatches between requirement and the product can be found early. Disadvantages : Sometimes the prototype ends up being the final product which results in quality, maintenance problems.
40
Summary Software Engineering is an important discipline due to various aspects. Analysis and Design are two very important phases in the software development lifecycle.
41
Reference Stephen Schach, Classical and Object-Oriented Software Engineering with UML and Java, Chapter 3, McGraw-Hill, New York, USA. Any other book on software engineering is also fine!
42
Introduction to Object Oriented Design
43
Overview Understand Classes and Objects.
Understand some of the key concepts/features in the Object Oriented paradigm. Benefits of Object Oriented Design paradigm.
44
OOP: model, map, reuse, extend
Model the real world problem to user’s perceive; Use similar metaphor in computational env. Construct reusable components; Create new components from existing ones.
45
Examples of Objects
46
Classes: Objects with the same attributes and behavior
47
Object Oriented Paradigm: Features
Encapsulation Data Abstraction Single Inheritance OOP Paradigm Polymorphism Persistence Delegation Genericity Multiple Inheritance
48
Java’s OO Features Encapsulation Data Abstraction Single Inheritance
OOP Paradigm Polymorphism Persistence Delegation Genericity Multiple Inheritance
49
Encapsulation Encapsulation It associates the code and the data it manipulates into a single unit; and keeps them safe from external interference and misuse. Data Abstraction Single Inheritance OOP Paradigm Polymorphism Persistence Delegation Data Genericity Functions Multiple Inheritance
50
Data Abstraction Encapsulation The technique of creating new data types that are well suited to an application. It allows the creation of user defined data types, having the properties of built data types and a set of permitted operators. In Java, partial support. In C++, fully supported (e.g., operator overloading). Data Abstraction Single Inheritance OOP Paradigm Polymorphism Persistence Delegation Genericity Multiple Inheritance
51
Abstract Data Type (ADT)
A structure that contains both data and the actions to be performed on that data. Class is an implementation of an Abstract Data Type.
52
Class- Example class Account { private String accountName;
private double accountBalance; public withdraw(); public deposit(); public determineBalance(); } // Class Account
53
Class Class is a set of attributes and operations that are performed on the attributes. Student Circle Account accountName accountBalance name age studentId centre radius withdraw() deposit() determineBalance() area() circumference() getName() getId()
54
Objects An Object Oriented system is a collection of interacting Objects. Object is an instance of a class.
55
circleA and circleB are
Classes/Objects John and Jill are objects of class Student :John Student :Jill :circleA circleA and circleB are objects of class Circle Circle :circleB
56
Class A class represents a template for several objects that have common properties. A class defines all the properties common to the object - attributes and methods. A class is sometimes called the object’s type.
57
Object Objects have state and classes don’t.
John is an object (instance) of class Student. name = “John”, age = 20, studentId = 1236 Jill is an object (instance) of class Student. name = “Jill”, age = 22, studentId = 2345 circleA is an object (instance) of class Circle. centre = (20,10), radius = 25 circleB is an object (instance) of class Circle. centre = (0,0), radius = 10
58
Encapsulation All information (attributes and methods) in an object oriented system are stored within the object/class. Information can be manipulated through operations performed on the object/class – interface to the class. Implementation is hidden from the user. Object support Information Hiding – Some attributes and methods can be hidden from the user.
59
Encapsulation - Example
class Account { private String accountName; private double accountBalance; public withdraw(); public deposit(); public determineBalance(); } // Class Account Deposit Withdraw Determine Balance Account balance message
60
Data Abstraction The technique of creating new data types that are well suited to an application. It allows the creation of user defined data types, having the properties of built in data types and more.
61
Abstraction - Example Creates a data type Account Account acctX;
class Account { private String accountName; private double accountBalance; public withdraw(); public deposit(); public determineBalance(); } // Class Account Creates a data type Account Account acctX;
62
Inheritance New data types (classes) can be defined as extensions to previously defined types. Parent Class (Super Class) – Child Class (Sub Class) Subclass inherits properties from the parent class. Parent Child Inherited capability
63
Inheritance - Example Example Define Person to be a class
A Person has attributes, such as age, height, gender Assign values to attributes when describing object Define student to be a subclass of Person A student has all attributes of Person, plus attributes of his/her own ( student no, course_enrolled) A student has all attributes of Person, plus attributes of his/her own (student no, course_enrolled) A student inherits all attributes of Person Define lecturer to be a subclass of Person Lecturer has all attributes of Person, plus attributes of his/her own ( staff_id, subjectID1, subjectID2)
64
Inheritance - Example Circle Class can be a subclass (inherited from ) of a parent class - Shape Shape Circle Rectangle
65
Inheritance - Example Inheritance can also have multiple levels. Shape
Circle Rectangle GraphicCircle
66
Uses of Inheritance - Reuse
If multiple classes have common attributes/methods, these methods can be moved to a common class - parent class. This allows reuse since the implementation is not repeated. Example : Rectangle and Circle method have a common method move(), which requires changing the centre coordinate.
67
Uses of Inheritance - Reuse
Rectangle Circle centre radius area() circumference() move(newCentre) centre height width area() circumference() move(newCentre) move(newCentre){ centre = newCentre; } move(newCentre){ centre = newCentre; }
68
Uses of Inheritance - Reuse
Shape centre move(newCentre){ centre = newCentre } area() circumference() move(newCentre) Rectangle Circle height width radius area() circumference() area() circumference()
69
Uses of Inheritance - Specialization
Specialized behavior can be added to the child class. In this case the behaviour will be implemented in the child class. E.g. The implementation of area() method in the Circle class is different from the Rectangle class. area() method in the child classes override the method in parent classes().
70
Uses of Inheritance - Specialization
Rectangle Circle centre radius area() circumference() move(newCentre) centre height width area() circumference() move(newCentre) area(){ return pi*r^2; } area(){ return height*width; }
71
Uses of Inheritance - Specialization
Shape centre area(); - Not implemented And left for the child classes To implement area() circumference() move(newCentre) area(){ return pi*r^2; } Rectangle Circle height width radius area(){ return height*width; } area() circumference() area() circumference()
72
Uses of Inheritance – Common Interface
All the operations that are supported for Rectangle and Circle are the same. Some methods have common implementation and others don’t. move() operation is common to classes and can be implemented in parent. circumference(), area() operations are significantly different and have to be implemented in the respective classes. The Shape class provides a common interface where all 3 operations move(), circumference() and area().
73
Uses of Inheritance - Extension
Extend functionality of a class. Child class adds new operations to the parent class but does not change the inherited behavior. E.g. Rectangle class might have a special operation that may not be meaningful to the Circle class - rotate90degrees()
74
Uses of Inheritance - Extension
Shape centre area() circumference() move(newCentre) Rectangle Circle height width radius area() circumference() rotate90degrees() area() circumference()
75
Uses of Inheritance – Multiple Inheritance
Inherit properties from more than one class. This is called Multiple Inheritance. Graphics Shape Circle
76
Uses of Multiple Inheritance
This is required when a class has to inherit behavior from multiple classes. In the example Circle class can inherit move() operation from the Shape class and the paint() operation from the Graphics class. Multiple inheritance is not supported in JAVA but is supported in C++.
77
Uses of Inheritance – Multiple Inheritance
GraphicCircle Shape centre area() circumference() move(newCentre) color paint() Circle radius area() circumference()
78
Polymorphism Polymorphic which means “many forms” has Greek roots.
Poly – many Morphos - forms. In OO paradigm polymorphism has many forms. Allow a single object, method, operator associated with different meaning depending on the type of data passed to it.
79
Polymorphism An object of type Circle or Rectangle can be assigned to a Shape object. The behavior of the object will depend on the object passed. circleA = new Circle(); Create a new circle object Shape shape = circleA; shape.area(); area() method for circle class will be executed rectangleA = new Rectangle(); Create a new rectangle object shape= rectangle; shape.area() area() method for rectangle will be executed.
80
Polymorphism – Method Overloading
Multiple methods can be defined with the same name, different input arguments. Method 1 - initialize(int a) Method 2 - initialize(int a, int b) Appropriate method will be called based on the input arguments. initialize(2) Method 1 will be called. initialize(2,4) Method 2 will be called.
81
Polymorphism – Operator Overloading
Allows regular operators such as +, -, *, / to have different meanings based on the type. E.g. + operator for Circle can re-defined Circle c = c + 2; Not supported in JAVA. C++ supports it.
82
Persistence The phenomenon where the object outlives the program execution. Databases support this feature. In Java, this can be supported if users explicitly build object persistency using IO streams.
83
Why OOP? Greater Reliability Maintainability
Break complex software projects into small, self-contained, and modular objects Maintainability Modular objects make locating bugs easier, with less impact on the overall project Greater Productivity through Reuse! Faster Design and Modelling
84
Benefits of OOP.. Inheritance: Elimination of Redundant Code and extend the use of existing classes. Build programs from existing working modules, rather than having to start from scratch. save development time and get higher productivity. Encapsulation: Helps in building secure programs.
85
Benefits of OOP.. Multiple objects to coexist without any interference. Easy to map objects in problem domain to those objects in the program. It is easy to partition the work in a project based on objects. The Data-Centered Design enables us in capturing more details of model in an implementable form.
86
Benefits of OOP.. Object Oriented Systems can be easily upgraded from small to large systems. Message-Passing technique for communication between objects make the interface descriptions with external systems much simpler. Software complexity can be easily managed.
87
Summary Object Oriented Design, Analysis, and Programming is a Powerful paradigm Enables Easy Mapping of Real world Objects to Objects in the Program This is enabled by OO features: Encapsulation Data Abstraction Inheritance Polymorphism Persistence Standard OO Design (UML) and Programming Languages (C++/Java) are readily accessible.
88
References Chapter 1: “Programming with Java” by Balagurusamny, TMH, New Delhi, India. Optional: Chapter 1: “Mastering C++” by V. Rajuk and R. Buyya, Tata McGraw Hill, New Delhi, India.
89
Java and its Evolution Rajkumar Buyya
Grid Computing and Distributed Systems Lab Dept. of Computer Science and Software Engineering The University of Melbourne
90
Contents Java Introduction Java Features
How Java Differs from other OO languages Java and the World Wide Web Java Environment Build your first Java Program Summary and Reference
91
Java - An Introduction Java - The new programming language developed by Sun Microsystems in 1991. Originally called Oak by James Gosling, one of the inventors of the Java Language. Java -The name that survived a patent search Java Authors: James , Arthur Van , and others Java is really “C “
92
Java Introduction Originally created for consumer electronics (TV, VCR, Freeze, Washing Machine, Mobile Phone). Java - CPU Independent language Internet and Web was just emerging, so Sun turned it into a language of Internet Programming. It allows you to publish a webpage with Java code in it.
93
Java Milestones Year Development 1990
Sun decided to developed special software that could be used for electronic devices. A project called Green Project created and head by James Gosling. 1991 Explored possibility of using C++, with some updates announced a new language named “Oak” 1992 The team demonstrated the application of their new language to control a list of home appliances using a hand held device. 1993 The World Wide Web appeared on the Internet and transformed the text-based interface to a graphical rich environment. The team developed Web applets (time programs) that could run on all types of computers connected to the Internet.
94
Java Milestones Year Development 1994
The team developed a new Web browsed called “Hot Java” to locate and run Applets. HotJava gained instance success. 1995 Oak was renamed to Java, as it did not survive “legal” registration. Many companies such as Netscape and Microsoft announced their support for Java 1996 Java established itself it self as both 1. “the language for Internet programming” 2. a general purpose OO language. 1997- A class libraries, Community effort and standardization, Enterprise Java, Clustering, etc..
95
Sun white paper defines Java as:
Simple and Powerful Safe Object Oriented Robust Architecture Neutral and Portable Interpreted and High Performance Threaded Dynamic
96
Java Attributes Familiar, Simple, Small Compiled and Interpreted
Platform-Independent and Portable Object-Oriented Robust and Secure Distributed Multithreaded and Interactive High Performance Dynamic and Extensible
97
Java is Compiled and Interpreted
Programmer Hardware and Operating System Source Code Byte Code Text Editor Compiler Interpreter .java file .class file java appletviewer netscape Notepad, emacs,vi javac
98
Compiled Languages Programmer Object Code Executable Code Source Code
Text Editor Compiler linker .c file .o file a.out file Notepad, emacs,vi gcc
99
Total Platform Independence
JAVA COMPILER (translator) JAVA BYTE CODE (same for all platforms) JAVA INTERPRETER (one for each different system) Windows 95 Macintosh Solaris Windows NT
100
Architecture Neutral & Portable
Java Compiler - Java source code (file with extension .java) to bytecode (file with extension .class) Bytecode - an intermediate form, closer to machine representation A interpreter (virtual machine) on any target platform interprets the bytecode.
101
Architecture Neutral & Portable
Porting the java system to any new platform involves writing an interpreter. The interpreter will figure out what the equivalent machine dependent code to run
102
Rich Class Environment
Core Classes language Utilities Input/Output Low-Level Networking Abstract Graphical User Interface Internet Classes TCP/IP Networking WWW and HTML Distributed Programs
103
How Does Java Compares to C++ and Other OO Languages
104
Overlap of C, C++, and Java
105
? Java better than C++ ? No Typedefs, Defines, or Preprocessor
No Global Variables No Goto statements No Pointers No Unsafe Structures No Multiple Inheritance No Operator Overloading No Automatic Coercions No Fragile Data Types ?
106
Object Oriented Languages -A Comparison
107
Power of Compiled Languages and Flexibility of Interpreted Languages
Java Integrates Power of Compiled Languages and Flexibility of Interpreted Languages
108
Java Applications We can develop two types of Java programs:
Stand-alone applications Web applications (applets)
109
Applications v/s Applets
Different ways to run a Java executable are: Application- A stand-alone program that can be invoked from command line . A program that has a “main” method Applet- A program embedded in a web page , to be run when the page is browsed . A program that contains no “main” method
110
Applets v/s Applications
Different ways to run a Java executable are Application- A stand-alone program that can be invoked from command line . A program that has a “main” method Applet- A program embedded in a web page , to be run when the page is browsed . A program that contains no “main” method Application –Executed by the Java interpreter. Applet- Java enabled web browser.
111
Turning the Web into an Interactive and Application Delivery Platform
Java and World Wide Web Turning the Web into an Interactive and Application Delivery Platform
112
What is World Wide Web ? Web is an open-ended information retrieval system designed to be used in the Internet wide distributed system. It contains Web pages (created using HTML) that provide both information and controls. Unlike a menu driven system--where we are guided through a particular direction using a decision tree, the web system is open ended and we can navigate to a new document in any direction.
113
Web Structure of Information Search/Navigation
114
Web as a delivery Vehicle
115
APPLET Development “hello.java”
Execution of Applets 2 5 1 3 4 APPLET Development “hello.java” AT SUN.COM Accessing from Unimelb.edu.au The browser creates a new window and a new thread and then runs the code hello.class AT SUN’S WEB SERVER Create Applet tag in HTML document Hello Java <app= “Hello”> The Internet Hello
116
Significance of downloading Applets
Interactive WWW Flashy animation instead of static web pages Applets react to users input and dynamically change Display of dynamic data WWW with Java - more than a document publishing medium
117
Power of Java and the Web
Deliver applications, not just information Eliminate porting Eliminate end-user installation Slash software distribution costs Reach millions of customers - instantly
118
Java Development Kit javac - The Java Compiler
java - The Java Interpreter jdb- The Java Debugger appletviewer -Tool to run the applets javap - to print the Java bytecodes javaprof - Java profiler javadoc - documentation generator javah - creates C header files
119
Java Environment
120
Java Development Kit javac - The Java Compiler
java - The Java Interpreter jdb- The Java Debugger appletviewer -Tool to run the applets javap - to print the Java bytecodes javaprof - Java profiler javadoc - documentation generator javah - creates C header files
121
Process of Building and Running Java Programs
Text Editor Java Source Code javadoc HTML Files javac Java Class File javah Header Files java jdb Outout
122
Building your first Java Program
Let us Try Out Building your first Java Program
123
Hello Internet // hello.java: Hello Internet program
class HelloInternet { public static void main(String args[]) System.out.println(“Hello Internet”); }
124
Program Processing Compilation Execution # javac hello.java
results in HelloInternet.class Execution # java HelloInternet Hello Internet #
125
Simple Java Applet } //HelloWorld.java import java.applet.Applet;
import java.awt.*; public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString (“Hello World !”,25, 25); }
126
Calling an Applet <HTML>
<TITLE>HELLO WORLD APPLET</TITLE> <HEAD>THE HELLO WORLD APPLET</HEAD> <APPLET CODE=“HelloWorld.class” width=500 height=500> </APPLET> </HTML>
127
Applet Execution Using AppletViewer Using Browser
128
Java on my platform ? Sun (SPARC) ftp://java.sun.com
Sun(x86) ftp://xm.com:/pub/ IBM(Aix, OS/2)ftp://ncc.hursley.ibm.com/javainfo DEC(Alpha OSF/1) SGI HP linux AT & T Windows 3.1
129
Summary Java has emerged as a general purpose OO language.
It supports both stand alone and Internet Applications. Makes the Web Interactive and medium for application delivery. Provides an excellent set of Tools for Application Development. Java is ubiquitous!
130
References Chapter 2: “Java Evolution”, Programming with Java by Balagurusamy, TMH, New Delhi, India Optional: Chapter 1: “Mastering C++” by V. Rajuk and R. Buyya, Tata McGraw Hill, New Delhi, India.
131
Basic Java Constructs and Data Types – Nuts and Bolts
Looking into Specific Differences and Enhancements in Java compared to C
132
Contents Hello World Program Statements Explained
Java Program Structure in General Java Classes and Static Methods Data Types, Variables and Constants Java Comments and Documents Control Flow Reading from Keyboard Command Line Arguments Processing Summary and References
133
Hello World // HelloWorld.java: Hello World program
import java.lang.*; class HelloWorld { public static void main(String args[]) System.out.println(“Hello World”); }
134
Hello World: Java and C /* helloworld.c: Hello World program */
S1: S2: S3: S4: S6: // HelloWorld.java: Hello World program import java.lang.*; class HelloWorld { public static void main(String args[]) System.out.println(“Hello World”); } /* helloworld.c: Hello World program */ #define <stdio.h> void main(int argc, char *argv[]) { printf(“Hello World\n”); }
135
Program Processing Compilation Execution # javac HelloWorld.java
results in HelloWorld.class Execution # java HelloWorld Hello World
136
Closer Look at - Hello World
The class has one method – main() public static void main(String args[]) { System.out.println(“Hello World”); } Command line input arguments are passed in the String array args[] e.g java HelloWorld John Jane args[0] – John args[1] – Jane
137
Closer Look at - Hello World
import java.lang.*; Java allows grouping of related classes into a package. It allows different companies can develop different packages, may even have same class and method names, but they differ by package name: ibm.mathlib.* microsoft.mathlib.* Helps in managing name clash problems. Think of this package as library. “import” statement somewhat serves similar purpose as C’s #include If you don’t add import statement, then you need utilise fully qualified name. ibm.mathlib.sin() If you do “import ibm.*” then you can use mathlib.sin() instead.
138
Java imports java.lang.* by default
So, You don't need to import java.lang.* That means, you can invoke services of java’s “lang” package classes/entities, you don’t need to use fully qualified names. We used System.out.println() instead of java.lang. System.out.println()
139
public static void main(String args[])
public: The keyword “public” is an access specifier that declares the main method as unprotected. static: It says this method belongs to the entire class and NOT a part of any objects of class. The main must always be declared static since the interpreter users this before any objects are created. void: The type modifier that states that main does not return any value.
140
System.out.println(“Hello World”);
java.lang.* All classes/items in “lang” package of java package. System is really the java.lang.System class. This class has a public static field called out which is an instance of the java.io.PrintStream class. So when we write System.out.println(), we are really invoking the println() method of the “out” field of the java.lang.System class.
141
Java Program Structure
Documentation Section Package Statement Import Statements Interface Statements Class Declarations Main Method Class { }
142
More Java: Classes and static methods
// SquareRoot.java: compute square root of number import java.lang.Math; class SquareRoot { public static void main(String args []) double x = 4; double y; y = Math.sqrt(x); System.out.println("y= "+y); }
143
Basic Data Types String (class for manipulating strings) Types
boolean either true or false char 16 bit Unicode 1.1 byte 8-bit integer (signed) short 16-bit integer (signed) int 32-bit integer (signed) long 64-bit integer (singed) float 32-bit floating point (IEEE ) double 64-bit floating point (IEEE ) String (class for manipulating strings) Java uses Unicode to represent characters internally
144
Variables Local Variables are declared within the block of code
Variable has a type preceding the name Initial value is set by initialization expressions. type variableName = initialValue; e.g. int x = 1; Variables can be defined just before their usage (unlike C) e.g., for( int i = 0; i < 10; i++)
145
Constants Constants are similar to variables except that they hold a fixed value. They are also called “READ” only variables. Constants are declared with the reserved word “final”. final int MAX_LENGTH = 420; final double PI = ; By convention upper case letters are used for defining constants.
146
Declaring Constants - example
class CircleArea { public static void main(String args[]) final double PI = ; double radius = 5.5; // in cms double area; area = PI * radius * radius; System.out.println("Circle Radius = "+radius+" Area="+area); }
147
Comments English text scattered through the code are comments
JAVA supports 3 types of comments /* */ - Usually used from multi-line comments // Used for single line comments /** */ - Documentation comments
148
Javadoc Effort to make Java self-documenting
True OOP style, encapsulate documentation within code :) Comments beginning with /** and ending with */ can be extracted and turned into html documentation
149
Control Flow Control Flow Statements in JAVA
while loop for loop do-while loop if-else statement switch statement JAVA does not support a goto statement
150
Control Flow - Examples
while loop while (squared <= MAX) { squared = lo * lo; // Calculate square System.out.println(squared); lo = lo + 1; /* Compute the new lo value */ }
151
Control Flow - Examples
for loop for (int i = 1; i < MAX; i++) { System.out.println(i); // prints … }
152
Control Flow - Examples
do-while loop do { squared = lo * lo; // Calculate square System.out.println(squared); lo = lo + 1; /* Compute the new lo value */ } while (squared <= MAX);
153
Control Flow - Examples
if-else loop if ( i < 10) { System.out.println(“i is less than 10” ); } else { System.out.println(“i is greater than or equal to 10”);
154
Control Flow - Examples
switch statement switch (c) { case ‘a’: System.out.println (“ The character is ‘a’” ); break; case ‘b’; System.out.println (“ The character is ‘b’” ); default; System.out.println (“ The character is not ‘a’ or ‘b’” ); }
155
Reading from Keyboard As Java does not support a simple APIs for Keyboard Input, we created a class called "Keyboard", which you can use in your program. The Keyboard class facilitates keyboard input by abstracting details about input parsing, conversions, and exception handling. This class reads from standard input (keyboard) and converts the characters into an appropriate type based on the method you call. Some methods you can use are: Keyboard.readString() Keyboard.readWord() Keyboard.readChar() Keyboard.readBoolean() Keyboard.readInt() Keyboard.readLong() Keyboard.readFloat() Keyboard.readDouble()
156
Keyboard class Usage Example
Simply copy the Keyboard.java file from: into your program directory and access its methods as if they are standard methods. The Java complier will link them automatically. An Example Program: // A class to execute one or more Keyboard methods class Test { public static void main(String[] args) System.out.print("Please enter a string: "); String str = Keyboard.readString(); System.out.println("String = " + str); System.out.print("Please enter an int number: "); int numInt = Keyboard.readInt(); System.out.println("int = " + numInt); }
157
Command Line Arguments
Command line arguments provide one of the ways for supplying input data at the time of execution instead of including them in the program. They are supplied as parameters to the main() method: public static void main(String args[]) “args” is declared of an array of strings (aka string objects). args[0] is the first parameter, args[1] is the 2nd argument and so on The number of arguments passed identified by: args.length E.g. count = args.length; Example Invocation and values: java MyProgram hello melbourne args.length will be 2 args[0] will be “hello” and args[1] will be “melborune”
158
Printing command line arguments
// ComLineTest.java: testing command line arguments class ComLineTest { public static void main(String args[]) int count, i = 0; String myString; count = args.length; System.out.println("Number of Arguments = "+count); while( i < count ) myString = args[i]; i = i + 1; System.out.println(i + " : " + "Java is "+myString+ " !"); } + concatenates strings or numbers
159
Execution Example Number of Arguments = 8 1 : Java is Simple !
java ComLineTest Simple Object_Oriented Distributed Robust Secure Portable Multithread Dynamic The output of program will be: Number of Arguments = 8 1 : Java is Simple ! 2 : Java is Object_Oriented ! 3 : Java is Distributed ! 4 : Java is Robust ! 5 : Java is Secure ! 6 : Java is Portable ! 7 : Java is Multithread ! 8 : Java is Dynamic !
160
Summary We discussed meaning of statements in “hello world” program
We discussed various basic constructs and syntax. Apart from OO specific items, most keywords or constructs in Java have similar meaning and usage style as C.
161
References Chapter 3: Overview of Java Language
Chapters To Browse (if you have forgotten C syntax/constructs): Chapter 4: Constants, Variables, and Data Types Chapter 5: Operators and Expressions Chapter 6: Decision Making and Branching Chapter 7: Decision Making and Looping
162
Classes and Objects in Java
Basics of Classes in Java
163
Contents Introduce to classes and objects in Java.
Understand how some of the OO concepts learnt so far are supported in Java. Understand important features in Java classes.
164
Introduction Java is a true OO language and therefore the underlying structure of all Java programs is classes. Anything we wish to represent in Java must be encapsulated in a class that defines the “state” and “behaviour” of the basic program components known as objects. Classes create objects and objects use methods to communicate between them. They provide a convenient method for packaging a group of logically related data items and functions that work on them. A class essentially serves as a template for an object and behaves like a basic data type “int”. It is therefore important to understand how the fields and methods are defined in a class and how they are used to build a Java program that incorporates the basic OO concepts such as encapsulation, inheritance, and polymorphism.
165
Classes A class is a collection of fields (data) and methods (procedure or function) that operate on that data. Circle centre radius circumference() area()
166
Classes A class is a collection of fields (data) and methods (procedure or function) that operate on that data. The basic syntax for a class definition: Bare bone class – no fields, no methods class ClassName [extends SuperClassName] { [fields declaration] [methods declaration] } public class Circle { // my circle class }
167
Adding Fields: Class Circle with fields
Add fields The fields (data) are also called the instance varaibles. public class Circle { public double x, y; // centre coordinate public double r; // radius of the circle }
168
Adding Methods A class with only data fields has no life. Objects created by such a class cannot respond to any messages. Methods are declared inside the body of the class but immediately after the declaration of data fields. The general form of a method declaration is: type MethodName (parameter-list) { Method-body; }
169
Adding Methods to Class Circle
public class Circle { public double x, y; // centre of the circle public double r; // radius of circle //Methods to return circumference and area public double circumference() { return 2*3.14*r; } public double area() { return 3.14 * r * r; Method Body
170
Data Abstraction Declare the Circle class, have created a new data type – Data Abstraction Can define variables (objects) of that type: Circle aCircle; Circle bCircle;
171
Class of Circle cont. aCircle, bCircle simply refers to a Circle object, not an object itself. aCircle bCircle null null Points to nothing (Null Reference) Points to nothing (Null Reference)
172
Creating objects of a class
Objects are created dynamically using the new keyword. aCircle and bCircle refer to Circle objects aCircle = new Circle() ; bCircle = new Circle() ;
173
Creating objects of a class
aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle;
174
Creating objects of a class
aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle; Before Assignment Before Assignment P aCircle bCircle P aCircle bCircle Q Q
175
Automatic garbage collection
Q The object does not have a reference and cannot be used in future. The object becomes a candidate for automatic garbage collection. Java automatically collects garbage periodically and releases the memory used to be used in the future.
176
Accessing Object/Circle Data
Similar to C syntax for accessing data defined in a structure. ObjectName.VariableName ObjectName.MethodName(parameter-list) Circle aCircle = new Circle(); aCircle.x = 2.0 // initialize center and radius aCircle.y = 2.0 aCircle.r = 1.0
177
Executing Methods in Object/Circle
Using Object Methods: sent ‘message’ to aCircle Circle aCircle = new Circle(); double area; aCircle.r = 1.0; area = aCircle.area();
178
Using Circle Class // Circle.java: Contains both Circle class and its user class //Add Circle class code here class MyMain { public static void main(String args[]) Circle aCircle; // creating reference aCircle = new Circle(); // creating object aCircle.x = 10; // assigning value to data field aCircle.y = 20; aCircle.r = 5; double area = aCircle.area(); // invoking method double circumf = aCircle.circumference(); System.out.println("Radius="+aCircle.r+" Area="+area); System.out.println("Radius="+aCircle.r+" Circumference ="+circumf); } java MyMain Radius=5.0 Area=78.5 Radius=5.0 Circumference =
179
Summary Classes, objects, and methods are the basic components used in Java programming. We have discussed: How to define a class How to create objects How to add data fields and methods to classes How to access data fields and methods to classes
180
Classes and Objects in Java
Constructors, Overloading, Static Members
181
Refer to the Earlier Circle Program
// Circle.java: Contains both Circle class and its user class //Add Circle class code here class MyMain { public static void main(String args[]) Circle aCircle; // creating reference aCircle = new Circle(); // creating object aCircle.x = 10; // assigning value to data field aCircle.y = 20; aCircle.r = 5; double area = aCircle.area(); // invoking method double circumf = aCircle.circumference(); System.out.println("Radius="+aCircle.r+" Area="+area); System.out.println("Radius="+aCircle.r+" Circumference ="+circumf); } java MyMain Radius=5.0 Area=78.5 Radius=5.0 Circumference =
182
Better way of Initialising or Access Data Members x, y, r
When there too many items to update/access and also to develop a readable code, generally it is done by defining specific method for each purpose. To initialise/Update a value: aCircle.setX( 10 ) To access a value: aCircle.getX() These methods are informally called as Accessors or Setters/Getters Methods.
183
Accessors – “Getters/Setters”
public class Circle { public double x,y,r; //Methods to return circumference and area public double getX() { return x;} public double getY() { return y;} public double getR() { return r;} public double setX(double x_in) { x = x_in;} public double serY(double y_in) { y = y_in;} public double setR(double r_in) { r = r_in;} }
184
How does this code looks ? More readable ?
// Circle.java: Contains both Circle class and its user class //Add Circle class code here class MyMain { public static void main(String args[]) Circle aCircle; // creating reference aCircle = new Circle(); // creating object aCircle.setX(10); aCircle.setY(20); aCircle.setR(5); double area = aCircle.area(); // invoking method double circumf = aCircle.circumference(); System.out.println("Radius="+aCircle.getR()+" Area="+area); System.out.println("Radius="+aCircle.getR()+" Circumference ="+circumf); } java MyMain Radius=5.0 Area=78.5 Radius=5.0 Circumference =
185
Object Initialisation
When objects are created, the initial value of data fields is unknown unless its users explicitly do so. For example, ObjectName.DataField1 = 0; // OR ObjectName.SetDataField1(0); In many cases, it makes sense if this initialisation can be carried out by default without the users explicitly initialising them. For example, if you create an object of the class called “Counter”, it is natural to assume that the counter record-keeping field is initialised to zero unless otherwise specified differently. class Counter { int CounterIndex; … } Counter counter1 = new Counter(); What is the value of “counter1.CounterIndex” ? In Java, this can be achieved though a mechanism called constructors.
186
What is a Constructor? Constructor is a special method that gets invoked “automatically” at the time of object creation. Constructor is normally used for initializing objects with default values unless different values are supplied. Constructor has the same name as the class name. Constructor cannot return values. A class can have more than one constructor as long as they have different signature (i.e., different input arguments syntax).
187
Defining a Constructor
Like any other method Invoking: There is NO explicit invocation statement needed: When the object creation statement is executed, the constructor method will be executed automatically. public class ClassName { // Data Fields… // Constructor public ClassName() { // Method Body Statements initialising Data Fields } //Methods to manipulate data fields
188
Defining a Constructor: Example
public class Counter { int CounterIndex; // Constructor public Counter() { CounterIndex = 0; } //Methods to update or access counter public void increase() CounterIndex = CounterIndex + 1; public void decrease() CounterIndex = CounterIndex - 1; int getCounterIndex() return CounterIndex;
189
Trace counter value at each statement and What is the output ?
class MyClass { public static void main(String args[]) { Counter counter1 = new Counter(); counter1.increase(); int a = counter1.getCounterIndex(); int b = counter1.getCounterIndex(); if ( a > b ) else counter1.decrease(); System.out.println(counter1.getCounterIndex()); }
190
A Counter with User Supplied Initial Value ?
This can be done by adding another constructor method to the class. public class Counter { int CounterIndex; // Constructor 1 public Counter() { CounterIndex = 0; } public Counter(int InitValue ) CounterIndex = InitValue; // A New User Class: Utilising both constructors Counter counter1 = new Counter(); Counter counter2 = new Counter (10);
191
Adding a Multiple-Parameters Constructor to our Circle Class
public class Circle { public double x,y,r; // Constructor public Circle(double centreX, double centreY, double radius) { x = centreX; y = centreY; r = radius; } //Methods to return circumference and area public double circumference() { return 2*3.14*r; } public double area() { return 3.14 * r * r; }
192
Constructors initialise Objects
Recall the following OLD Code Segment: Circle aCircle = new Circle(); aCircle.x = 10.0; // initialize center and radius aCircle.y = 20.0 aCircle.r = 5.0; aCircle = new Circle() ; At creation time the center and radius are not defined. These values are explicitly set later.
193
Constructors initialise Objects
With defined constructor Circle aCircle = new Circle(10.0, 20.0, 5.0); aCircle = new Circle(10.0, 20.0, 5.0) ; aCircle is created with center (10, 20) and radius 5
194
Multiple Constructors
Sometimes want to initialize in a number of different ways, depending on circumstance. This can be supported by having multiple constructors having different input arguments.
195
Multiple Constructors
public class Circle { public double x,y,r; //instance variables // Constructors public Circle(double centreX, double cenreY, double radius) { x = centreX; y = centreY; r = radius; } public Circle(double radius) { x=0; y=0; r = radius; } public Circle() { x=0; y=0; r=1.0; } //Methods to return circumference and area public double circumference() { return 2*3.14*r; } public double area() { return 3.14 * r * r; }
196
Initializing with constructors
public class TestCircles { public static void main(String args[]){ Circle circleA = new Circle( 10.0, 12.0, 20.0); Circle circleB = new Circle(10.0); Circle circleC = new Circle(); } circleA = new Circle(10, 12, 20) circleB = new Circle(10) circleC = new Circle() Centre = (10,12) Radius = 20 Centre = (0,0) Radius = 1 Centre = (0,0) Radius=10
197
Method Overloading Constructors all have the same name.
Methods are distinguished by their signature: name number of arguments type of arguments position of arguments That means, a class can also have multiple usual methods with the same name. Not to confuse with method overriding (coming up), method overloading:
198
Polymorphism Allows a single method or operator associated with different meaning depending on the type of data passed to it. It can be realised through: Method Overloading Operator Overloading (Supported in C++, but not in Java) Defining the same method with different argument types (method overloading) - polymorphism. The method body can have different logic depending on the date type of arguments.
199
Scenario A Program needs to find a maximum of two numbers or Strings. Write a separate function for each operation. In C: int max_int(int a, int b) int max_string(char *s1, char *s2) max_int (10, 5) or max_string (“melbourne”, “sydney”) In Java: int max(int a, int b) int max(String s1, String s2) max(10, 5) or max(“melbourne”, “sydney”) Which is better ? Readability and intuitive wise ?
200
A Program with Method Overloading
// Compare.java: a class comparing different items class Compare { static int max(int a, int b) { if( a > b) return a; else return b; } static String max(String a, String b) if( a.compareTo (b) > 0) public static void main(String args[]) String s1 = "Melbourne"; String s2 = "Sydney"; String s3 = "Adelaide"; int a = 10; int b = 20; System.out.println(max(a, b)); // which number is big System.out.println(max(s1, s2)); // which city is big System.out.println(max(s1, s3)); // which city is big
201
The New this keyword this keyword can be used to refer to the object itself. It is generally used for accessing class members (from its own methods) when they have the same name as those passed as arguments. public class Circle { public double x,y,r; // Constructor public Circle (double x, double y, double r) { this.x = x; this.y = y; this.r = r; } //Methods to return circumference and area
202
Static Members Java supports definition of global methods and variables that can be accessed without creating objects of a class. Such members are called Static members. Define a variable by marking with the static methods. This feature is useful when we want to create a variable common to all instances of a class. One of the most common example is to have a variable that could keep a count of how many objects of a class have been created. Note: Java creates only one copy for a static variable which can be used even if the class is never instantiated.
203
Static Variables Define using static:
Access with the class name (ClassName.StatVarName): public class Circle { // class variable, one for the Circle class, how many circles public static int numCircles; //instance variables,one for each instance of a Circle public double x,y,r; // Constructors... } nCircles = Circle.numCircles;
204
Static Variables - Example
Using static variables: public class Circle { // class variable, one for the Circle class, how many circles private static int numCircles = 0; private double x,y,r; // Constructors... Circle (double x, double y, double r){ this.x = x; this.y = y; this.r = r; numCircles++; }
205
Class Variables - Example
Using static variables: public class CountCircles { public static void main(String args[]){ Circle circleA = new Circle( 10, 12, 20); // numCircles = 1 Circle circleB = new Circle( 5, 3, 10); // numCircles = 2 } circleA = new Circle(10, 12, 20) circleB = new Circle(5, 3, 10) numCircles
206
Instance Vs Static Variables
Instance variables : One copy per object. Every object has its own instance variable. E.g. x, y, r (centre and radius in the circle) Static variables : One copy per class. E.g. numCircles (total number of circle objects created)
207
Static Methods A class can have methods that are defined as static (e.g., main method). Static methods can be accessed without using objects. Also, there is NO need to create objects. They are prefixed with keyword “static” Static methods are generally used to group related library functions that don’t depend on data members of its class. For example, Math library functions.
208
Comparator class with Static methods
// Comparator.java: A class with static data items comparision methods class Comparator { public static int max(int a, int b) { if( a > b) return a; else return b; } public static String max(String a, String b) if( a.compareTo (b) > 0) class MyClass { public static void main(String args[]) String s1 = "Melbourne"; String s2 = "Sydney"; String s3 = "Adelaide"; int a = 10; int b = 20; System.out.println(Comparator.max(a, b)); // which number is big System.out.println(Comparator.max(s1, s2)); // which city is big System.out.println(Comparator.max(s1, s3)); // which city is big Directly accessed using ClassName (NO Objects)
209
Static methods restrictions
They can only call other static methods. They can only access static data. They cannot refer to “this” or “super” (more later) in anyway.
210
Summary Constructors allow seamless initialization of objects.
Classes can have multiple methods with the same name [Overloading] Classes can have static members, which serve as global members of all objects of a class. Keywords: constructors, polymorphism, method overloading, this, static variables, static methods.
211
Classes and Objects in Java
Parameter Passing, Delegation, Visibility Control, and Object Cleanup
212
Contents Review of Static Methods Parameter Passing Object Delegation
Apply to Circle class Review main method Final data members Parameter Passing Object Delegation Visibility Control Object Cleanup Summary
213
Static Method in Circle class
Like class variables, can have class methods too: Accessed with class name Circle c1= new Circle(); Circle c2 = new Cricle(); Cricle c3 = Cricle.bigger(c1,c2); public class Circle { //A class method for the same public static Circle bigger(Circle a, Circle b) { if (a.r > b.r) return a; else return b; }
214
Static Methods in Circle Class
Class methods can only access static variables and methods. public class Circle { // class variable, one for the Circle class, how many circles private static int numCircles = 0; public double x,y,r; public static void printNumCircles(){ System.out.println(“Number of Circles = ” + numCircles); } // This is not VALID public static void printRadius(){ { System.out.println(“Radius = “ + r);
215
Back to HelloWorld [System invokes static main method]
// HelloWorld.java: Hello World program class HelloWorld { public static void main(String args[]) System.out.println(“Hello World”); }
216
Back to Constants [final can also be made as static]
class SquaredNumbers{ static final int MAX_NUMBER = 25; public static void main(String args[]){ final int MAX_NUMBER = 25; int lo = 1; int squared = 0; while (squared <= MAX_NUMBER){ squared = lo * lo; // Calculate square System.out.println(squared); lo = lo + 1; /* Compute the new lo value */ }
217
Parameter passing Method parameters which are objects are passed by reference. Copy of the reference to the object is passed into method, original value unchanged.
218
Parameter passing - Example
public class ReferenceTest { public static void main (String[] args) { Circle c1 = new Circle(5, 5, 20); Circle c2 = new Circle(1, 1, 10); System.out.println ( “c1 Radius = “ + c1.getRadius()); System.out.println ( “c2 Radius = “ + c2.getRadius()); parameterTester(c1, c2); } …….. cont
219
Parameter passing - Example
public static void parameterTester(Circle circleA, Circle circleB) { circleA.setRadius(15); circleB = new Circle(0, 0, 100); System.out.println ( “circleA Radius = “ + circleA.getRadius()); System.out.println ( “circleB Radius = “ + circleB.getRadius()); }
220
Parameter passing - Example
Output – c1 Radius = 20.0 c2 Radius = 10.0 circleA Radius = 15.0 circleB Radius = 100.0 c1 Radius = 15.0
221
Parameter passing - Example
STEP1 – Before calling parameterTester() STEP2 – parameterTester(c1, c2) c1 c2 c1 c2 (5,5,20) (1.1,10) (5,5,20) (1.1,10) circleA circleA circleA circleA circleB circleB X X X STEP3 – circlA.setRadius(15) STEP4 – circlB = new Cirlce(0,0,100) c1 c2 c1 c2 (5,5,15) (1.1,10) circleA circleA circleB (5,5,15) (1.1,10) circleA circleA circleB (0.0,100)
222
Parameter passing - Example
STEP5 – After Returning from parameterTester c1 c2 (5,5,15) (1.1,10) circleA circleA circleB X X X
223
Delegation Ability for a class to delegate its responsibilities to another class. A way of making an object invoking services of other objects through containership.
224
Delegation - Example public class Point { private double xCoord;
private double yCoord; // Constructor …………. public double getXCoord(){ return xCoord; } public double getYCoord(){ return yCoord; Point xCoord yCoord getXCoord() getYCoord()
225
Delegation - Example public class Circle { private Point centre;
public double getCentreX(){ return centre.getXCoord(); } public double getCentreY(){ return centre.getYCoord(); Circle Point xCoord yCoord getXCoord() getYCoord() centre getCentreX() getCentreY()
226
Visibility Control: Data Hiding and Encapsulation
Java provides control over the visibility of variables and methods, encapsulation, safely sealing data within the capsule of the class Prevents programmers from relying on details of class implementation, so you can update without worry Helps in protecting against accidental or wrong usage. Keeps code elegant and clean (easier to maintain)
227
Visibility Modifiers: Public, Private, Protected
Public keyword applied to a class, makes it available/visible everywhere. Applied to a method or variable, completely visible. Default (No visibility modifier is specified): it behaves like public in its package and private in other packages. Default Public keyword applied to a class, makes it available/visible everywhere. Applied to a method or variable, completely visible. Private fields or methods for a class only visible within that class. Private members are not visible within subclasses, and are not inherited. Protected members of a class are visible within the class, subclasses and also within all classes that are in the same package as that class.
228
Visibility public class Circle { private double x,y,r; // Constructor
public Circle (double x, double y, double r) { this.x = x; this.y = y; this.r = r; } //Methods to return circumference and area public double circumference() { return 2*3.14*r;} public double area() { return 3.14 * r * r; }
229
Construction time message
Visibility Circle Construction time message Circle area message Center (x,y) Radius r circumference message
230
Accessors – “Getters/Setters”
public class Circle { private double x,y,r; //Methods to return circumference and area public double getX() { return x;} public double getY() { return y;} public double getR() { return r;} public double setX(double x) { this.x = x;} public double serY(double y) { this.y = y;} public double setR(double r) { this.r = r;} } More on “Visibility” during Inheritance and Package Discussion
231
Objects Cleanup/Destructor
Unlike c and c++, memory deallocation is automatic in java, don’t worry about it no dangling pointers and no memory leak problem. Java allows you to define finalizer method, which is invoked (if defined) just before the object destruction. In way, this presents an opportunity to perform record-maintenance operation or cleanup any special allocations made by the user. // done with this circle protected void finalize() throws IOException { Circle.numCircles = Circle.numCircles--; System.out.println(“number of circles:”+ Circle.num_circles); }
232
Summary Static members play a role similar to the global members of classes. They can only access other static members in the class. Objects can be passed as parameters and they can be used for exchanging messages (data). Delegation enables an object to pass responsibilities to other objects. Encapsulation/Data hiding helps in protecting data from accidental or wrong usage and also offers better security for data. Java clean-ups object resources automatically, however, users can provide “finalize()” method to do any user-level related clean-up activities.
233
Classes and Subclasses Or Extending a Class
Inheritance Classes and Subclasses Or Extending a Class
234
Inheritance: Introduction
Reusability--building new components by utilising existing components- is yet another important aspect of OO paradigm. It is always good/“productive” if we are able to reuse something that is already exists rather than creating the same all over again. This is achieve by creating new classes, reusing the properties of existing classes.
235
Inheritance: Introduction
This mechanism of deriving a new class from existing/old class is called “inheritance”. The old class is known as “base” class, “super” class or “parent” class”; and the new class is known as “sub” class, “derived” class, or “child” class. Parent Child Inherited capability
236
Inheritance: Introduction
The inheritance allows subclasses to inherit all properties (variables and methods) of their parent classes. The different forms of inheritance are: Single inheritance (only one super class) Multiple inheritance (several super classes) Hierarchical inheritance (one super class, many sub classes) Multi-Level inheritance (derived from a derived class) Hybrid inheritance (more than two types) Multi-path inheritance (inheritance of some properties from two sources).
237
Forms of Inheritance A A B A B C B C D (a) Single Inheritance
(b) Multiple Inheritance (c) Hierarchical Inheritance A A A B c B c B C D D (a) Multi-Level Inheritance (b) Hybrid Inheritance (b) Multipath Inheritance
238
Defining a Sub class A subclass/child class is defined as follows:
The keyword “extends” signifies that the properties of super class are extended to the subclass. That means, subclass contains its own members as well of those of the super class. This kind of situation occurs when we want to enhance properties of existing class without actually modifying it. class SubClassName extends SuperClassName { fields declaration; methods declaration; }
239
Subclasses and Inheritance
Circle class captures basic properties For drawing application, need a circle to draw itself on the screen, GraphicCircle... This can be realised either by updating the circle class itself (which is not a good Software Engineering method) or creating a new class that builds on the existing class and add additional properties.
240
Without Inheritance Not very elegant public class GraphicCircle {
public Circle c; // keep a copy of a circle public double area() { return c.area(); } public double circumference (){ return c.circumference(); } // new instance variables, methods for this class public Color outline, fill; public void draw(DrawWindow dw) { /* drawing code here */ } }
241
Subclasses and Inheritance
Circle class captures basic properties For drawing application need a circle to draw itself on the screen, GraphicCircle Java/OOP allows for Circle class code to be implicitly (re)used in defining a GraphicCircle GraphicCircle becomes a subclass of Circle, extending its capabilities
242
Subclassing Circle Circle x,y,r : double area ( ) : double Subclass,
circumference(): double GraphicCircle outline, fill : Color draw (DrawWindow ) : void Superclass base class, Or parent class Subclass, Derived class, or Child class
243
Subclassing Subclasses created by the keyword extends:
Each GraphicCircle object is also a Circle! public class GraphicCircle extends Circle { // automatically inherit all the variables and methods // of Circle, so only need to put in the ‘new stuff’ Color outline, fill; public void draw(DrawWindow dw) { dw.drawCircle(x,y,r,outline,fill); }
244
Final Classes Declaring class with final modifier prevents it being extended or subclassed. Allows compiler to optimize the invoking of methods of the class final class Cirlce{ ………… }
245
Subclasses & Constructors
Default constructor automatically calls constructor of the base class: default constructor for Circle class is called GraphicCircle drawableCircle = new GraphicCircle();
246
Subclasses & Constructors
Defined constructor can invoke base class constructor with super: public GraphicCircle(double x, double y, double r, Color outline, Color fill) { super(x, y, r); this.outline = outline; this fill = fill }
247
Shadowed Variables Subclasses defining variables with the same name as those in the superclass, shadow them:
248
Shadowed Variables - Example
public class Circle { public float r = 100; } public class GraphicCircle extends Circle { public float r = 10; // New variable, resolution in dots per inch public class CircleTest { public static void main(String[] args){ GraphicCircle gc = new GraphicCircle(); Circle c = gc; System.out.println(“ GraphicCircleRadius= “ + gc.r); // 10 System.out.println (“ Circle Radius = “ + c.r); // 100
249
Overriding Methods Derived/sub classes defining methods with same name, return type and arguments as those in the parent/super class, override their parents methods:
250
Overriding Methods class A { int j = 1; int f( ) { return j; } }
class B extends A { int j = 2; int f( ) { return j; }
251
Overriding Methods class override_test {
public static void main(String args[]) { B b = new B(); System.out.println(b.j); // refers to B.j prints 2 System.out.println(b.f()); // refers to B.f prints 2 A a = (A) b; System.out.println(a.j); // now refers to a.j prints 1 System.out.println(a.f()); // overridden method still refers to B.f() prints 2 ! } Object Type Casting inheritance [1:167] java override_test 2 1
252
Using All in One: Person and Student
name: String sex: char age: int Display ( ) : void Student RollNo: int Branch: String Display() : void Superclass class Subclass class.
253
Person class: Parent class
// Student.java: Student inheriting properties of person class class person { private String name; protected char sex; // note protected public int age; person() name = null; sex = 'U'; // unknown age = 0; } person(String name, char sex, int age) this.name = name; this.sex = sex; this.age = age; String getName() return name; void Display() System.out.println("Name = "+name); System.out.println("Sex = "+sex); System.out.println("Age = "+age);
254
Student class: Derived class
class student extends person { private int RollNo; String branch; student(String name, char sex, int age, int RollNo, String branch) super(name, sex, age); // calls parent class's constructor with 3 arguments this.RollNo = RollNo; this.branch = branch; } void Display() // Method Overriding System.out.println("Roll No = "+RollNo); System.out.println("Name = "+getName()); System.out.println("Sex = "+sex); System.out.println("Age = "+age); System.out.println("Branch = "+branch); void TestMethod() // test what is valid to access // name = "Mark"; Error: name is private sex = 'M'; RollNo = 20; What happens if super class constructor is not explicitly invoked ? (default constructor will be invoked).
255
Can we create Object of person class ?
Driver Class class MyTest { public static void main(String args[] ) student s1 = new student("Rama", 'M', 21, 1, "Computer Science"); student s2 = new student("Sita", 'F', 19, 2, "Software Engineering"); System.out.println("Student 1 Details..."); s1.Display(); System.out.println("Student 2 Details..."); s2.Display(); person p1 = new person("Rao", 'M', 45); System.out.println("Person Details..."); p1.Display(); } Can we create Object of person class ?
256
Output [raj@mundroo] inheritance [1:154] java MyTest
Student 1 Details... Roll No = 1 Name = Rama Sex = M Age = 21 Branch = Computer Science Student 2 Details... Roll No = 2 Name = Sita Sex = F Age = 19 Branch = Software Engineering Person Details... Name = Rao Age = 45 inheritance [1:155]
257
Summary Inheritance promotes reusability by supporting the creation of new classes from existing classes. Various forms of inheritance can be realised in Java. Child class constructor can be directed to invoke selected constructor from parent using super keyword. Variables and Methods from parent classes can be overridden by redefining them in derived classes. New Keywords: extends, super, final
258
References Chapter 8: Sections 8.11, 8.12, 8.13, and 8.14 from Java book by Balagurusamy Optional: <for in depth> Chapter 14: Inheritance from “Mastering C++” by Venugopal and Buyya!
259
Arrays, Strings and Collections [1]
Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software Engineering University of Melbourne, Australia
260
Arrays - Introduction An array is a group of contiguous or related data items that share a common name. Used when programs have to handle large amount of data Each value is stored at a specific position Position is called a index or superscript. Base index = 0 The ability to use a single name to represent a collection of items and refer to an item by specifying the item number enables us to develop concise and efficient programs. For example, a loop with index as the control variable can be used to read the entire array, perform calculations, and print out the results.
261
Arrays - Introduction 69 61 1 index 70 2 89 3 values 23 4 10 5 9 6
262
Declaration of Arrays Like any other variables, arrays must declared and created before they can be used. Creation of arrays involve three steps: Declare the array Create storage area in primary memory. Put values into the array (i.e., Memory location) Declaration of Arrays: Form 1: Type arrayname[] Form 2: Type [] arrayname; Examples: int[] students; int students[]; Note: we don’t specify the size of arrays in the declaration.
263
Creation of Arrays After declaring arrays, we need to allocate memory for storage array items. In Java, this is carried out by using “new” operator, as follows: Arrayname = new type[size]; Examples: students = new int[7];
264
Initialisation of Arrays
Once arrays are created, they need to be initialised with some values before access their content. A general form of initialisation is: Arrayname [index/subscript] = value; Example: students[0] = 50; students[1] = 40; Like C, Java creates arrays starting with subscript 0 and ends with value one less than the size specified. Unlike C, Java protects arrays from overruns and under runs. Trying to access an array beyond its boundaries will generate an error message.
265
Arrays – Length Arrays are fixed length
Length is specified at create time In java, all arrays store the allocated size in a variable named “length”. We can access the length of arrays as arrayName.length: e.g. int x = students.length; // x = 7 Accessed using the index e.g. int x = students [1]; // x = 40
266
Arrays – Example // StudentArray.java: store integers in arrays and access public class StudentArray{ public static void main(String[] args) { int[] students; students = new int[7]; System.out.println("Array Length = " + students.length); for ( int i=0; i < students.length; i++) students[i] = 2*i; System.out.println("Values Stored in Array:"); System.out.println(students[i]); } :w
267
Arrays – Initializing at Declaration
Arrays can also be initialised like standard variables at the time of their declaration. Type arrayname[] = {list of values}; Example: int[] students = {55, 69, 70, 30, 80}; Creates and initializes the array of integers of length 5. In this case it is not necessary to use the new operator.
268
Arrays – Example int[] students = {55, 69, 70, 30, 80};
// StudentArray.java: store integers in arrays and access public class StudentArray{ public static void main(String[] args) { int[] students = {55, 69, 70, 30, 80}; System.out.println("Array Length = " + students.length); System.out.println("Values Stored in Array:"); for ( int i=0; i < students.length; i++) System.out.println(students[i]); }
269
Two Dimensional Arrays
Two dimensional arrays allows us to store data that are recorded in table. For example: Table contains 12 items, we can think of this as a matrix consisting of 4 rows and 3 columns. Item1 Item2 Item3 Salesgirl #1 10 15 30 Salesgirl #2 14 33 Salesgirl #3 200 32 1 Salesgirl #4 4 Sold Person
270
2D arrays manipulations
Declaration: int myArray [][]; Creation: myArray = new int[4][3]; // OR int myArray [][] = new int[4][3]; Initialisation: Single Value; myArray[0][0] = 10; Multiple values: int tableA[2][3] = {{10, 15, 30}, {14, 30, 33}}; int tableA[][] = {{10, 15, 30}, {14, 30, 33}};
271
Variable Size Arrays Java treats multidimensional arrays as “arrays of arrays”. It is possible to declare a 2D arrays as follows: int a[][] = new int [3][]; a[0]= new int [3]; a[1]= new int [2]; a[2]= new int [4];
272
Try: Write a program to Add to Matrix
Define 2 dimensional matrix variables: Say: int a[][], b[][]; Define their size to be 2x3 Initialise like some values Create a matrix c to storage sum value c[0][0] = a[0][0] + b[0][0] Print the contents of result matrix.
273
Arrays of Objects Arrays can be used to store objects
Circle[] circleArray; circleArray = new Circle[25]; The above statement creates an array that can store references to 25 Circle objects. Circle objects are not created.
274
Arrays of Objects Create the Circle objects and stores them in the array. //declare an array for Circle Circle circleArray[] = new Circle[25]; int r = 0; // create circle objects and store in array for (r=0; r <25; r++) circleArray[r] = new Circle(r);
275
String Operations in Java
276
Introduction String manipulation is the most common operation performed in Java programs. The easiest way to represent a String (a sequence of characters) is by using an array of characters. Example: char place[] = new char[4]; place[0] = ‘J’; place[1] = ‘a’; place[2] = ‘v’; place[3] = ‘a’; Although character arrays have the advantage of being able to query their length, they themselves are too primitive and don’t support a range of common string operations. For example, copying a string, searching for specific pattern etc. Recognising the importance and common usage of String manipulation in large software projects, Java supports String as one of the fundamental data type at the language level. Strings related book keeping operations (e.g., end of string) are handled automatically.
277
String Operations in Java
Following are some useful classes that Java provides for String operations. String Class StringBuffer Class StringTokenizer Class
278
String Class String class provides many operations for manipulating strings. Constructors Utility Comparisons Conversions String objects are read-only (immutable)
279
Strings Basics Declaration and Creation: String stringName;
stringName = new String (“string value”); Example: String city; city = new String (“Bangalore”); Length of string can be accessed by invoking length() method defined in String class: int len = city.length();
280
String operations and Arrays
Java Strings can be concatenated using the + operator. String city = “New” + “York”; String city1 = “Delhi”; String city2 = “New “+city1; Strings Arrays String city[] = new String[5]; city[0] = new String(“Melbourne”); city[1] = new String(“Sydney”); … String megacities[] = {“Brisbane”, “Sydney”, “Melbourne”, “Adelaide”, “Perth”};
281
String class - Constructors
public String() Constructs an empty String. Public String(String value) Constructs a new string copying the specified string.
282
String – Some useful operations
public int length() Returns the length of the string. public charAt(int index) Returns the character at the specified location (index) public int compareTo( String anotherString) public int compareToIgnoreCase( String anotherString) Compare the Strings. reigonMatch(int start, String other, int ostart, int count) Compares a region of the Strings with the specified start.
283
String – Some useful operations
public String replace(char oldChar, char newChar) Returns a new string with all instances of the oldChar replaced with newChar. public trim() Trims leading and trailing white spaces. public String toLowerCase() public String toUpperCase() Changes as specified.
284
String Class - example // StringDemo.java: some operations on strings
class StringDemo { public static void main(String[] args) { String s = new String("Have a nice Day"); // String Length = 15 System.out.println("String Length = " + s.length() ); // Modified String = Have a Good Day System.out.println("Modified String = " + s.replace('n', 'N')); // Converted to Uppercse = HAVE A NICE DAY" System.out.println("Converted to Uppercase = " + s.toUpperCase()); // Converted to Lowercase = have a nice day" System.out.println("Converted to Lowercase = " + s.toLowerCase()); }
285
StringDemo Output [raj@mundroo] Arrays [1:130] java StringDemo
String Length = 15 Modified String = Have a Nice Day Converted to Uppercase = HAVE A NICE DAY Converted to Lowercase = have a nice day Arrays [1:131]
286
Summary Arrays allows grouping of sequence of related items.
Java supports powerful features for declaring, creating, and manipulating arrays in efficient ways. Each items of arrays of arrays can have same or variable size. Java provides enhanced support for manipulating strings and manipulating them appears similar to manipulating standard data type variables.
287
Arrays, Strings and Collections [2]
Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software Engineering University of Melbourne, Australia
288
toString() Method toString() method is a special method that can be defined in any class. This method should return a String argument. When an object is used in a String concatenation operation or when specified in print statement, this method gets invoked automatically.
289
toString() Method -Example
class Circle { double x, y,r; public Circle (double centreX, double centreY, double radius ) { x = centreX ; y = centreY; r = radius; } public String toString() { String s = “I am a Circle with centre [“ + x + “,” + y + “] and radius [“+ r + “]”; return s;
290
toString() Method -Example
class CircleTest { Circle c = new Circle(10,20, 30); System.out.println( c ); // I am a circle with centre [10.0,20.0] and radius [30.0] }
291
StringBufferClass Unlike the String class, StringBuffer class is mutable (changeable). Use StringBufferClass class in operations where the string has to be modified.
292
StringBuffer class - Constructors
public StringBuffer() Constructs a StringBuffer with an empty string. public StringBuffer(String str) Constructs a StringBuffer with initial value of str.
293
StringBuffer class – Some operations
public int length() Returns the length of the buffer public synchronized void setCharAt(int index, char ch) Replaces the character at the specified position s1.setLength(int n) Truncates or extends the buffer. If(n<s1.length(), s1 is truncated; else zeros are added to s1. public StringBuffer append(String str) Appends the string to this string buffer. public StringBuffer append(int i) Append of other data items (float, char, etc.) is supported. Appends the string representation of the int argument to this string buffer.
294
Inserting a String in Middle of Existing StringBuffer
StringBuffer str = new StringBuffer(“Object Language”); String aString = new String(str.toString()); Int pos = aString.indexOf(“ Language”); str.insert(pos, “ Oriented “); what will out put of at this point: System.out.println(“Modified String:”+str); What will be string after executing (modifying character): str.setChar(6,’-’);
295
StringTokenizer Breaks string into parts, using delimiters.
The sequence of broken parts are the tokens of the string. More than one delimiter can be specified. The tokens can be extracted with or without the delimiters.
296
StringTokenizer - Functionality
Consider the following String CREATE_USER: ;John;Smith Separate the tokens CREATE_USER John Smith
297
StringTokenizer - Constructors
public StringTokenizer(String str, String delim, boolean returnTokens) Creates a SringTokenizer with the specified delimiter. If returnTokens is true the delimiters are also returned. public StringTokenizer(String str, String delim) Delimiters are not returned public StringTokenizer(String str) Delimiters are (“ \t\n\r\f”)
298
StringTokenizer - Operations
public boolen hasMoreTokens() Returns true if more tokens are found. public String nextToken() Returns the next token of the String. public String nextToken(String delim) Switches the delimiter set to characters in delim and returns the next token. public int countTokens() Returns the count of remaining tokens.
299
StringTokenizer - example
import java.util.StringTokenizer; class TokenizerExample { public static void main(string[] args) { String str = “CREATE_USER:123456;John;Smith”; StringTokenizer tokens = new StringTokenizer(str, “:;”); while ( tokens.hasMoreTokens() ) System.out.println(tokens.nextToken()); } Output of the program CREATE_USER 123456 John Smith
300
Collections Arrays are used to hold groups of specific type of items
Collections (container) designed to hold generic (any) type of objects Collections let you store, organize and access objects in an efficient manner.
301
Legacy Collection Types
Vector Stack Dictionary HashTable Properties Enumeration
302
Vector The Vector class implements a growable array of objects.
Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created. In Java this is supported by Vector class contained in java.util package. The Vector class can be used to create generic dynamic arrays that hold objects of any type or any number. The objects do not have to be homogeneous. Like arrays, Vectors are created as follows: Vector list = new Vector(); // declaring without size Vector list = new Vector(3); // declaring with size
303
Vector properties Vectors posses a number of advantages over arrays:
It is convenient to use vectors to store objects. A vector can be used to store list of objects that may vary in size. We can add and delete objects from the list as an when required. But vectors cannot be used to store basic data types (int, float, etc.); we can only store objects. To store basic data type items, we need convert them to objects using “wrapper classes” (discussed later).
304
Important Methods in Vector class
addElement(Object item) insertElementAt(Object item, int index) elementAt(int index) – get element at index removeElementAt(int index) size() clone() - Returns a clone of this vector. clear() - Removes all of the elements from this Vector. get(int index) - Returns the element at the specified position in this Vector. copyInto(array) – copy all items from vector to array.
305
Vector – Example 1 import java.util.*; public class VectorOne{
public static void main(String[] args) { Vector circleVector = new Vector(); System.out.println("Vector Length + “, circleVector.size()); // 0 for ( int i=0; i < 5; i++) { circleVector.addElement( new Circle(i) ); // radius of the Circles 0,1,2,3,4 } System.out.println("Vector Length = " + circleVector.size());// 5
306
Vector – Example 2 for ( int i = 0; i < 6; i++) {
import java.util.*; public class VectorTwo{ public static void main(String[] args) { …… code from VectorOne goes here circleVector.insertElementAt( new Circle(20), 3); System.out.println(“Vector Length =“ + circleVector.size()); // 6 for ( int i = 0; i < 6; i++) { System.out.println("Radius of element [" + i + "] = " + ( (Circle) circleVector.elementAt(i)).getRadius()); // radius of the Circles are 0,1,2,20,3,4 }
307
Hash Table (Hashtable clalss)
Allows associating values with keys. Allows efficient look ups for the value associated with the key This class implements a hashtable, which maps keys to values. Any non-null object can be used as a key or as a value. Useful Operations: put(Object key, Object value); remove(Object key); get(Object key);
308
HashTable put()/get() operations
The following example creates a hashtable of numbers. It uses the names of the numbers as keys: Hashtable numbers = new Hashtable(); numbers.put("one", new Integer(1)); numbers.put("two", new Integer(2)); numbers.put("three", new Integer(3)); To retrieve a number, use the following code: Integer n = (Integer)numbers.get("two"); if (n != null) { System.out.println("two = " + n); }
309
HashTable -Example import java.util.*; public class HashtableDemo {
public static void main(String[] args) { Hashtable tbl = new Hashtable(); Student s, sRet; s = new Student("121212", "John"); tbl.put (s.getId(), s); s = new Student("100000", "James"); sRet= (Student) tbl.get("121212"); System.out.println("Student name is = " + sRet.getName()); // Student name is = John }
310
Enumeration Used to enumerate or iterate through a set of values in a collection. Useful for iterating Hashtables – no index. Useful Operations: hasMoreElements(); nextElement();
311
Enumeration - Example import java.util.*;
public class EnumerationDemo{ public static void main(String[] args) { Hashtable tbl = new Hashtable(); Student s, sRet; s = new Student("121212", "John"); tbl.put(s.getId(), s); s = new Student("100000", "James"); Enumeration e = tbl.elements(); while ( e.hasMoreElements()) { sRet = (Student) e.nextElement(); System.out.println("Student name is = " + sRet.getName()); // Student name is = James // Student name is = John }
312
Wrapper Classes As pointed out earlier, collections cannot handle basic data types such as int, float. They can converted into object types by using the wrapper classes supported by java.lang package. Basic Type Wrapper Class boolean Boolean char Character int Integer long Long float Float double Double
313
Methods in Wrapper Classes
Constructors: Integer intVal = new Integer(i); Float floatVal = new Float(f); Converting objects to basic values int i = intVal.intValue(); float f = floatValue.floatValue(); Converting Numbers to Strings str = Integer.toString(i) str = Float.toStrin(f);
314
Methods in Wrapper Classes
String Objects to Numeric Objectrs Integer intVal = Integer.ValueOf(str); Float floatVal = Float.ValueOf(str); Numeric Strings to Basic Types int i = Integer.parseInt(str); long l = Long.parseFloat(str) These methods throw exception (NumberFormatException) if the value of the str does represent an integer. Exception are a OO way of reporting errors. More on it later.
315
Summary A special method, toString(), can be defined in any Java class, which gets invoked when one tries to concatenation operation with Strings. Collections are like arrays, but can hold any objects, dynamically expandable, and supports their easy manipulation. Java has strong support for Collections, which are very useful when developing large-scale software development. Wrapper classes helps in manipulating basic data types as Objects.
316
Final and Abstract Classes
317
Restricting Inheritance
Parent Child Inherited capability
318
Final Members: A way for Preventing Overriding of Members in Subclasses
All methods and variables can be overridden by default in subclasses. This can be prevented by declaring them as final using the keyword “final” as a modifier. For example: final int marks = 100; final void display(); This ensures that functionality defined in this method cannot be altered any. Similarly, the value of a final variable cannot be altered.
319
Final Classes: A way for Preventing Classes being extended
We can prevent an inheritance of classes by other classes by declaring them as final classes. This is achieved in Java by using the keyword final as follows: final class Marks { // members } final class Student extends Person Any attempt to inherit these classes will cause an error.
320
Abstract Classes When we define a class to be “final”, it cannot be extended. In certain situation, we want to properties of classes to be always extended and used. Such classes are called Abstract Classes. An Abstract class is a conceptual class. An Abstract class cannot be instantiated – objects cannot be created. Abstract classes provides a common root for a group of classes, nicely tied together in a package:
321
Abstract Class Syntax abstract class ClassName {
... … abstract Type MethodName1(); Type Method2() // method body } When a class contains one or more abstract methods, it should be declared as abstract class. The abstract methods of an abstract class must be defined in its subclass. We cannot declare abstract constructors or abstract static methods.
322
Abstract Class -Example
Shape is a abstract class. Shape Circle Rectangle
323
The Shape Abstract Class
public abstract class Shape { public abstract double area(); public void move() { // non-abstract method // implementation } Is the following statement valid? Shape s = new Shape(); No. It is illegal because the Shape class is an abstract class, which cannot be instantiated to create its objects.
324
Abstract Classes public Circle extends Shape { protected double r;
protected static final double PI = ; public Circle() { r = 1.0; ) public double area() { return PI * r * r; } … } public Rectangle extends Shape { protected double w, h; public Rectangle() { w = 0.0; h=0.0; } public double area() { return w * h; }
325
Abstract Classes Properties
A class with one or more abstract methods is automatically abstract and it cannot be instantiated. A class declared abstract, even with no abstract methods can not be instantiated. A subclass of an abstract class can be instantiated if it overrides all abstract methods by implementation them. A subclass that does not implement all of the superclass abstract methods is itself abstract; and it cannot be instantiated.
326
Summary If you do not want (properties of) your class to be extended or inherited by other classes, define it as a final class. Java supports this is through the keyword “final”. This is applied to classes. You can also apply the final to only methods if you do not want anyone to override them. If you want your class (properties/methods) to be extended by all those who want to use, then define it as an abstract class or define one or more of its methods as abstract methods. Java supports this is through the keyword “abstract”. This is applied to methods only. Subclasses should implement abstract methods; otherwise, they cannot be instantiated.
327
Interfaces Design Abstraction and a way for loosing realizing Multiple Inheritance
328
Interfaces Interface is a conceptual entity similar to a Abstract class. Can contain only constants (final variables) and abstract method (no implementation) - Different from Abstract classes. Use when a number of classes share a common interface. Each class should implement the interface.
329
Interfaces: An informal way of realising multiple inheritance
An interface is basically a kind of class—it contains methods and variables, but they have to be only abstract classes and final fields/variables. Therefore, it is the responsibility of the class that implements an interface to supply the code for methods. A class can implement any number of interfaces, but cannot extend more than one class at a time. Therefore, interfaces are considered as an informal way of realising multiple inheritance in Java.
330
<<Interface>>
Interface - Example <<Interface>> Speaker speak() Politician Priest Lecturer speak() speak() speak()
331
Interfaces Definition
Syntax (appears like abstract class): Example: interface InterfaceName { // Constant/Final Variable Declaration // Methods Declaration – only method body } interface Speaker { public void speak( ); }
332
Implementing Interfaces
Interfaces are used like super-classes who properties are inherited by classes. This is achieved by creating a class that implements the given interface as follows: class ClassName implements InterfaceName [, InterfaceName2, …] { // Body of Class }
333
Implementing Interfaces Example
class Politician implements Speaker { public void speak(){ System.out.println(“Talk politics”); } class Priest implements Speaker { public void speak(){ System.out.println(“Religious Talks”); } class Lecturer implements Speaker { public void speak(){ System.out.println(“Talks Object Oriented Design and Programming!”); }
334
Extending Interfaces Like classes, interfaces can also be extended. The new sub-interface will inherit all the members of the superinterface in the manner similar to classes. This is achieved by using the keyword extends as follows: interface InterfaceName2 extends InterfaceName1 { // Body of InterfaceName2 }
335
Inheritance and Interface Implementation
A general form of interface implementation: This shows a class can extended another class while implementing one or more interfaces. It appears like a multiple inheritance (if we consider interfaces as special kind of classes with certain restrictions or special features). class ClassName extends SuperClass implements InterfaceName [, InterfaceName2, …] { // Body of Class }
336
Student Assessment Example
Consider a university where students who participate in the national games or Olympics are given some grace marks. Therefore, the final marks awarded = Exam_Marks + Sports_Grace_Marks. A class diagram representing this scenario is as follow: Student Sports Exam Results extends implements
337
Software Implementation
class Student { // student no and access methods } interface Sport // sports grace marks (say 5 marks) and abstract methods class Exam extends Student // example marks (test1 and test 2 marks) and access methods class Results extends Exam implements Sport // implementation of abstract methods of Sport interface // other methods to compute total marks = test1+test2+sports_grace_marks; // other display or final results access methods
338
Interfaces and Software Engineering
Interfaces, like abstract classes and methods, provide templates of behaviour that other classes are expected to implement. Separates out a design hierarchy from implementation hierarchy. This allows software designers to enforce/pass common/standard syntax for programmers implementing different classes. Pass method descriptions, not implementation Java allows for inheritance from only a single superclass. Interfaces allow for class mixing. Classes implement interfaces.
339
A Summary of OOP and Java Concepts Learned So Far
340
Summary Class is a collection of data and methods that operate on that data An object is a particular instance of a class Object members accessed with the ‘dot’ (Class.v) Instance variables occur in each instance of a class Class variables associated with a class Objects created with the new keyword
341
Summary Objects are not explicitly ‘freed’ or destroyed. Java automatically reclaims unused objects. Java provides a default constructor if none defined. A class may inherit the non-private methods and variables of another class by subclassing, declaring that class in its extends clause. java.lang.Object is the default superclass for a class. It is the root of the Java hierarchy.
342
Summary Method overloading is the practice of defining multiple methods which have the same name, but different argument lists Method overriding occurs when a class redefines a method inherited from its superclass static, private, and final methods cannot be overridden From a subclass, you can explicitly invoke an overridden method of the superclass with the super keyword.
343
Summary Data and methods may be hidden or encapsulated within a class by specifying the private or protected visibility modifiers. An abstract method has no method body. An abstract class contains abstract methods. An interface is a collection of abstract methods and constants. A class implements an interface by declaring it in its implements clause, and providing a method body for each abstract method.
344
Exceptions: An OO Way for Handling Errors
Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software Engineering University of Melbourne, Australia
345
Introduction Rarely does a program runs successfully at its very first attempt. It is common to make mistakes while developing as well as typing a program. Such mistakes are categorised as: syntax errors - compilation errors. semantic errors– leads to programs producing unexpected outputs. runtime errors – most often lead to abnormal termination of programs or even cause the system to crash.
346
Common Runtime Errors Dividing a number by zero.
Accessing an element that is out of bounds of an array. Trying to store incompatible data elements. Using negative value as array size. Trying to convert from string data to a specific data value (e.g., converting string “abc” to integer value). File errors: opening a file in “read mode” that does not exist or no read permission Opening a file in “write/update mode” which has “read only” permission. Corrupting memory: - common with pointers Any more ….
347
Without Error Handling – Example 1
class NoErrorHandling{ public static void main(String[] args){ int a,b; a = 7; b = 0; System.out.println(“Result is “ + a/b); System.out.println(“Program reached this line”); } Program does not reach here No compilation errors. While running it reports an error and stops without executing further statements: java.lang.ArithmeticException: / by zero at Error2.main(Error2.java:10)
348
Traditional way of Error Handling - Example 2
class WithErrorHandling{ public static void main(String[] args){ int a,b; a = 7; b = 0; if (b != 0){ System.out.println(“Result is “ + a/b); } else{ System.out.println(“ B is zero); System.out.println(“Program is complete”); Program reaches here
349
Error Handling Any program can find itself in unusual circumstances – Error Conditions. A “good” program should be able to handle these conditions gracefully. Java provides a mechanism to handle these error condition - exceptions
350
Exceptions An exception is a condition that is caused by a runtime error in the program. Provide a mechanism to signal errors directly without using flags. Allow errors to be handled in one central part of the code without cluttering code.
351
Exceptions and their Handling
When the JVM encounters an error such as divide by zero, it creates an exception object and throws it – as a notification that an error has occurred. If the exception object is not caught and handled properly, the interpreter will display an error and terminate the program. If we want the program to continue with execution of the remaining code, then we should try to catch the exception object thrown by the error condition and then take appropriate corrective actions. This task is known as exception handling.
352
Common Java Exceptions
ArithmeticException ArrayIndexOutOfBoundException ArrayStoreException FileNotFoundException IOException – general I/O failure NullPointerException – referencing a null object OutOfMemoryException SecurityException – when applet tries to perform an action not allowed by the browser’s security setting. StackOverflowException StringIndexOutOfBoundException
353
Exceptions in Java A method can signal an error condition by throwing an exception – throws The calling method can transfer control to a exception handler by catching an exception - try, catch Clean up can be done by - finally
354
Exception Handling Mechanism
try Block Statements that causes an exception Throws exception Object catch Block Statements that handle the exception
355
Syntax of Exception Handling Code
… try { // statements } catch( Exception-Type e) { // statements to process exception ..
356
With Exception Handling - Example 3
class WithExceptionHandling{ public static void main(String[] args){ int a,b; float r; a = 7; b = 0; try{ r = a/b; System.out.println(“Result is “ + r); } catch(ArithmeticException e){ System.out.println(“ B is zero); System.out.println(“Program reached this line”); Program Reaches here
357
Finding a Sum of Integer Values Passed as Command Line Parameters
// ComLineSum.java: adding command line parameters class ComLineSum { public static void main(String args[]) int InvalidCount = 0; int number, sum = 0; for( int i = 0; i < args.length; i++) try { number = Integer.parseInt(args[i]); } catch(NumberFormatException e) InvalidCount++; System.out.println("Invalid Number: "+args[i]); continue;//skip the remaining part of loop sum += number; System.out.println("Number of Invalid Arguments = "+InvalidCount); System.out.println("Number of Valid Arguments = "+(args.length-InvalidCount)); System.out.println("Sum of Valid Arguments = "+sum);
358
Sample Runs [raj@mundroo] java ComLineSum 1 2
Number of Invalid Arguments = 0 Number of Valid Arguments = 2 Sum of Valid Arguments = 3 java ComLineSum 1 2 abc Invalid Number: abc Number of Invalid Arguments = 1
359
Multiple Catch Statements
If a try block is likely to raise more than one type of exceptions, then multiple catch blocks can be defined as follows: … try { // statements } catch( Exception-Type1 e) { // statements to process exception 1 .. catch( Exception-TypeN e) // statements to process exception N
360
finally block Java supports definition of another block called finally that be used to handle any exception that is not caught by any of the previous statements. It may be added immediately after the try block or after the last catch block: … try { // statements } catch( Exception-Type1 e) { // statements to process exception 1 .. finally { …. When a finally is defined, it is executed regardless of whether or not an exception is thrown. Therefore, it is also used to perform certain house keeping operations such as closing files and releasing system resources.
361
Catching and Propagating Exceptions
Exceptions raised in try block can be caught and then they can be thrown again/propagated after performing some operations. This can be done by using the keyword “throw” as follows: throw exception-object; OR throw new Throwable_Subclass;
362
With Exception Handling - Example 4
class WithExceptionCatchThrow{ public static void main(String[] args){ int a,b; float r; a = 7; b = 0; try{ r = a/b; System.out.println(“Result is “ + r); } catch(ArithmeticException e){ System.out.println(“ B is zero); throw e; System.out.println(“Program is complete”); Program Does Not reach here when exception occurs
363
With Exception Handling - Example 5
class WithExceptionCatchThrowFinally{ public static void main(String[] args){ int a,b; float r; a = 7; b = 0; try{ r = a/b; System.out.println(“Result is “ + r); } catch(ArithmeticException e){ System.out.println(“ B is zero); throw e; finally{ System.out.println(“Program is complete”); Program reaches here
364
User-Defined Exceptions
Problem Statement : Consider the example of the Circle class Circle class had the following constructor public Circle(double centreX, double centreY, double radius){ x = centreX; y = centreY; r = radius; } How would we ensure that the radius is not zero or negative? Circle
365
Defining your own exceptions
import java.lang.Exception; class InvalidRadiusException extends Exception { private double r; public InvalidRadiusException(double radius){ r = radius; } public void printError(){ System.out.println("Radius [" + r + "] is not valid");
366
Throwing the exception
class Circle { double x, y, r; public Circle (double centreX, double centreY, double radius ) throws InvalidRadiusException { if (r <= 0 ) { throw new InvalidRadiusException(radius); } else { x = centreX ; y = centreY; r = radius;
367
Catching the exception
class CircleTest { public static void main(String[] args){ try{ Circle c1 = new Circle(10, 10, -1); System.out.println("Circle created"); } catch(InvalidRadiusException e) { e.printError();
368
User-Defined Exceptions in standard format
class MyException extends Exception { MyException(String message) super(message); // pass to superclass if parameter is not handled by used defined exception } class TestMyException { … try { .. throw new MyException(“This is error message”); catch(MyException e) System.out.println(“Message is: “+e.getMessage()); Get Message is a method defined in a standard Exception class.
369
Summary A good programs does not produce unexpected results.
It is always a good practice to check for potential problem spots in programs and guard against program failures. Exceptions are mainly used to deal with runtime errors. Exceptions also aid in debugging programs. Exception handling mechanisms can effectively used to locate the type and place of errors.
370
Summary Try block, code that could have exceptions / errors
Catch block(s), specify code to handle various types of exceptions. First block to have appropriate type of exception is invoked. If no ‘local’ catch found, exception propagates up the method call stack, all the way to main() Any execution of try, normal completion, or catch then transfers control on to finally block
371
Streams and Input/Output Files Part I
372
Introduction So far we have used variables and arrays for storing data inside the programs. This approach poses the following limitations: The data is lost when variable goes out of scope or when the program terminates. That is data is stored in temporary/mail memory is released when program terminates. It is difficult to handle large volumes of data. We can overcome this problem by storing data on secondary storage devices such as floppy or hard disks. The data is stored in these devices using the concept of Files and such data is often called persistent data.
373
File Processing Storing and manipulating data using files is known as file processing. Reading/Writing of data in a file can be performed at the level of bytes, characters, or fields depending on application requirements. Java also provides capabilities to read and write class objects directly. The process of reading and writing objects is called object serialisation.
374
C Input/Output Revision
FILE* fp; fp = fopen(“In.file”, “rw”); fscanf(fp, ……); frpintf(fp, …..); fread(………, fp); fwrite(……….., fp);
375
I/O and Data Movement The flow of data into a program (input) may come from different devices such as keyboard, mouse, memory, disk, network, or another program. The flow of data out of a program (output) may go to the screen, printer, memory, disk, network, another program. Both input and output share a certain common property such as unidirectional movement of data – a sequence of bytes and characters and support to the sequential access to the data.
376
Streams Java Uses the concept of Streams to represent the ordered sequence of data, a common characteristic shared by all I/O devices. Streams presents a uniform, easy to use, object oriented interface between the program and I/O devices. A stream in Java is a path along which data flows (like a river or pipe along which water flows).
377
Stream Types The concepts of sending data from one stream to another (like a pipe feeding into another pipe) has made streams powerful tool for file processing. Connecting streams can also act as filters. Streams are classified into two basic types: Input Steam Output Stream Input Stream reads Source Program Output Stream Program Source writes
378
Java Stream Classes Input/Output related classes are defined in java.io package. Input/Output in Java is defined in terms of streams. A stream is a sequence of data, of no particular length. Java classes can be categorised into two groups based on the data type one which they operate: Byte streams Character Streams
379
Streams Byte Streams Character streams
Operated on 8 bit (1 byte) data. Operates on 16-bit (2 byte) unicode characters. Input streams/Output streams Readers/ Writers
380
Classification of Java Stream Classes
Character Stream classes Byte Stream classes
381
ByteArrayInputStream
Byte Input Streams InputStream ObjectInputStream SequenceInputStream ByteArrayInputStream PipedInputStream FilterInputStream PushbackInputStream BufferedInputStream DataInputStream
382
Byte Input Streams - operations
public abstract int read() Reads a byte and returns as a integer 0-255 public int read(byte[] buf, int offset, int count) Reads and stores the bytes in buf starting at offset. Count is the maximum read. public int read(byte[] buf) Same as previous offset=0 and length=buf.length() public long skip(long count) Skips count bytes. public int available() Returns the number of bytes that can be read. public void close() Closes stream
383
Byte Input Stream - example
Count total number of bytes in the file import java.io.*; class CountBytes { public static void main(String[] args) throws FileNotFoundException, IOException { FileInputStream in; in = new FileInputStream(“InFile.txt”); int total = 0; while (in.read() != -1) total++; System.out.println(total + “ bytes”); }
384
What happens if the file did not exist
JVM throws exception and terminates the program since there is no exception handler defined. Streams [1:165] java CountBytes Exception in thread "main" java.io.FileNotFoundException: FileIn.txt (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:64) at CountBytes.main(CountBytes.java:12)
385
Byte Output Streams OutputStream ObjectOutputStream
SequenceOutputStream ByteArrayOutputStream PipedOutputStream FilterOutputStream PrintStream BufferedOutputStream DataOutputStream
386
Byte Output Streams - operations
public abstract void write(int b) Write b as bytes. public void write(byte[] buf, int offset, int count) Write count bytes starting from offset in buf. public void write(byte[] buf) Same as previous offset=0 and count = buf.length() public void flush() Flushes the stream. public void close() Closes stream
387
Byte Output Stream - example
Read from standard in and write to standard out import java.io.*; class ReadWrite { public static void main(string[] args) throws IOException { int b; while (( b = System.in.read()) != -1) System.out.write(b); }
388
Summary Streams provide uniform interface for managing I/O operations in Java irrespective of device types. Java supports classes for handling Input Steams and Output steams via java.io package. Exceptions supports handling of errors and their propagation during file operations.
389
Streams and Input/Output Files Part 2
390
Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors. The basic I/O related exception classes are given below: EOFException – signals that end of the file is reached unexpectedly during input. FileNotFoundException – file could not be opened InterruptedIOException – I/O operations have been interrupted IOException – signals that I/O exception of some sort has occurred – very general I/O exception.
391
Syntax Each I/O statement or a group of I/O statements much have an exception handler around it/them as follows: try { …// I/O statements – open file, read, etc. } catch(IOException e) // or specific type exception { …//message output statements
392
Example import java.io.*; class CountBytesNew {
public static void main (String[] args) throws FileNotFoundException, IOException // throws is optional in this case { FileInputStream in; try{ in = new FileInputStream("FileIn.txt"); int total = 0; while (in.read() != -1) total++; System.out.println("Total = " + total); } catch(FileNotFoundException e1) System.out.println("FileIn.txt does not exist!"); catch(IOException e2) System.out.println("Error occured while read file FileIn.txt");
393
Creation of Files There are 2 ways of initialising file stream objects: Passing file name directly to the stream constructor Similar to previous example Passing File Object: Create File Object File inFile = new File("FileIn.txt"); Pass file object while creating stream: try { in = new FileInputStream(inFile); } Manipulation operations are same once the file is opened.
394
Reading and Writing Characters
As pointed out earlier, subclasses of Reader and Writer implement streams that can handle characters. The two subclasses used for handling characters in file are: FileReader FileWriter While opening a file, we can pass either file name or File object during the creation of objects of the above classes.
395
Reader Class Hierarchy
StringReader CharacterArrayReader PipedReader BufferedReader FileInputStream InputStreamReader FileterReader PushbackReader FileReader
396
Reader - operations public int read()
Reads a character and returns as a integer 0-255 public int read(char[] buf, int offset, int count) Reads and stores the characters in buf starting at offset. count is the maximum read. public int read(char[] buf) Same as previous offset=0 and length=buf.length() public long skip(long count) Skips count characters. public boolean() Returns true if the stream is ready to be read. public void close() Closes stream
397
Reader - example Count total number of spaces in the file
import java.io.*; public class CountSpace { public static void main (String[] args) throws IOException { Reader in; // in can also be FileReader in = new FileReader("FileIn.txt"); int ch, total, spaces; spaces = 0; for (total = 0 ; (ch = in.read()) != -1; total++){ if(Character.isWhitespace((char) ch)) spaces++; } System.out.println(total + " chars " + spaces + " spaces ");
398
Writer Class Hierarchy
Reader BufferedWriter CharacterArrayWriter FilterWriter PrinterWriter PipedWriter OutputStreamWriter StringWriter FileWriter
399
Byte Output Streams - operations
public abstract void write(int ch) Write ch as characters. public void write(char[] buf, int offset, int count) Write count characters starting from offset in buf. public void write(char[] buf) Same as previous offset=0 and count = buf.length() public void write(String str, int offset, int count) Write count characters starting at offset of str. public void flush() Flushes the stream. public void close() Closes stream
400
Copying Characters from Files
Write a Program that copies contents of a source file to a destination file. The names of source and destination files is passed as command line arguments. Make sure that sufficient number of arguments are passed. Print appropriate error messages.
401
FileCopy.java import java.io.*; public class FileCopy {
public static void main (String[] args) { if(args.length != 2) System.out.println("Error: in sufficient arguments"); System.out.println("Usage - java FileCopy SourceFile DestFile"); System.exit(-1); } try { FileReader srcFile = new FileReader(args[0]); FileWriter destFile = new FileWriter(args[1]); int ch; while((ch=srcFile.read()) != -1) destFile.write(ch); srcFile.close(); destFile.close(); catch(IOException e) System.out.println(e);
402
Runs and Outputs Source file exists: Source file does not exist:
java FileCopy FileIn.txt Fileout.txt Source file does not exist: java FileCopy abc Fileout.txt java.io.FileNotFoundException: abc (No such file or directory) In sufficient arguments passed java FileCopy FileIn.txt Error: in sufficient arguments Usage - java FileCopy SourceFile DestFile
403
Buffered Streams Java supports creation of buffers to store temporarily data that read from or written to a stream. This process is known as buffered I/O operation. Buffered stream classes – BufferedInputStream, BufferedOutputStream, BufferedReader, BufferedWriter buffer data to avoid every read or write going to the stream. These are used in file operations since accessing the disk for every character read is not efficient.
404
Buffered Streams Buffered character streams understand lines of text.
BufferedWriter has a newLine method which writes a new line character to the stream. BufferedReader has a readLine method to read a line of text as a String. For complete listing of methods, please see the Java manual/documentation.
405
BufferedReader - example
Use a BufferedReader to read a file one line at a time and print the lines to standard output import java.io.*; class ReadTextFile { public static void main(String[] args) throws FileNotFoundException, IOException { BufferedReader in; in = new BufferedReader( new FileReader(“Command.txt”)); String line; while (( line = in.readLine()) != null ) System.out.println(line); }
406
Reading/Writing Bytes
The FileReader and FileWriter classes are used to read and write 16-bit characters. As most file systems use only 8-bit bytes, Java supports number of classes that can handle bytes. The two most commonly used classes for handling bytes are: FileInputStream (discussed earlier) FileOutputStream
407
Writing Bytes - Example
public class WriteBytes { public static void main (String[] args) { byte cities[] = {'M', 'e', 'l', 'b', 'o', 'u', 'r', 'n', 'e', '\n', 'S', 'y','d', 'n', 'e', 'y', '\n‘ }; FileOutputStream outFile; try{ outFile = new FileOutputStream("City.txt"); outFile.write(cities); outFile.close(); } catch(IOException e) System.out.println(e); System.exit(-1);
408
Summary All Java I/O classes are designed to operate with Exceptions.
User Exceptions and your own handler with files to manger runtime errors. Subclasses FileReader / FileWriter support characters-based File I/O. FileInputStream and FileOutputStream classes support bytes-based File I/O. Buffered read operations support efficient I/O operations.
409
Streams and Input/Output Files Part 3
410
Handling Primitive Data Types
The basic input and output streams provide read/write methods that can be used for reading/writing bytes or characters. To read/write the primitive data types such as integers and doubles, we can use filter classes as wrappers on the existing I/O streams to filter data to the original stream. The two filter classes supported for creating “data streams” for primitive data types are: DataInputStream DataOutputStream
411
Hierarchy of Data Stream Classes
FilterInputStream DataInput DataInputStream Class Interface FilterOutputStream DataOutput DataOutputtStream Class Interface
412
Data Input Stream Creation
Create Input File Stream: FileInputStream fis = new FileInputStream(“InFile”); Create Input Data Stream: DataInputStream dis = new DataInputStream( fis ); The above statements wrap data input stream (dis) on file input stream (fis) and use it as a “filter”. Methods Supported: readBoolean(), readByte(), readChar(), readShort(), readInt(), readLong(), readFloat(), readDouble() They read data stored in file in binary format.
413
Data Output Stream Creation
Create Output File Stream: FileOutputStream fos = new FileOutputStream(“OutFile”); Create Output Data Stream: DataOutputStream dos = new DataOutputStream( fos ); The above statements wrap data output stream (dos) on file output stream (fos) and use it as a “filter”. Methods Supported: writeBoolean(), writeByte(), writeChar(), writeShort(), writeInt(), writeLong(), writeFloat(), writeDouble() They write data to file in binary format. How many bytes are written to file when for statements: writeInt(120), writeInt(10120)
414
Data Streams Flow via Filter
Write primitive data to the file using a filter. Read primitive data from the file using a filter. Program dos fos mydata filter binary stream Program fis dis mydata binary stream filter Screen
415
Writing and Reading Primitive Data
import java.io.*; public class ReadWriteFilter { public static void main(String args[]) throws IOException { // write primitive data in binary format to the "mydata" file FileOutputStream fos = new FileOutputStream("mydata"); DataOutputStream dos = new DataOutputStream(fos); dos.writeInt(120); dos.writeDouble(375.50); dos.writeInt('A'+1); dos.writeBoolean(true); dos.writeChar('X'); dos.close(); fos.close(); // read primitive data in binary format from the "mydata" file FileInputStream fis = new FileInputStream("mydata"); DataInputStream dis = new DataInputStream(fis); System.out.println(dis.readInt()); System.out.println(dis.readDouble()); System.out.println(dis.readBoolean()); System.out.println(dis.readChar()); dis.close(); fis.close(); }
416
Program Run and Output C:\254\examples>java ReadWriteFilter
120 375.5 66 true X Display content of “mydata” file (in binary format): C:\254\examples>type mydata B☺ X What is the size of “mydata” file (in bytes) ? Size of int+double+int+boolean+char
417
Concatenating and Buffering Streams
Two or more input streams can be combined into a single input stream. This process is known as logical concatenation of streams and is achieved using the SequenceInputStream class. A SequenceInputStream starts out with an ordered collection of input streams and reads from the first one until end of file is reached, whereupon it reads from the second one, and so on, until end of file is reached on the last of the contained input streams.
418
Sequencing and Buffering of Streams
Buffered streams sit between the program and data source/destination and functions like a filter or support efficient I/O. Buffered can be created using BufferedInputStream and BufferedOutputStream classes. file1.dat read() Program file1+file2 Buffer file2.dat inBuffer Streams Sequencer write() Screen Buffer outputBuffer
419
Example Program import java.io.*; public class CombineStreams {
public static void main(String args[]) throws IOException { // declare file streams FileInputStream file1 = new FileInputStream("file1.dat"); FileInputStream file2 = new FileInputStream("file2.dat"); // declare file3 to store combined streams SequenceInputStream file3 = null; // concatenate file1 and file2 streams into file3 file3 = new SequenceInputStream(file1, file2); BufferedInputStream inBuffer = new BufferedInputStream(file3); BufferedOutputStream outBuffer = new BufferedOutputStream(System.out); // read and write combined streams until the end of buffers int ch; while((ch = inBuffer.read()) != -1 ) outBuffer.write(ch); outBuffer.flush(); // check out the output by removing this line System.out.println("\nHello, This output is generated by CombineFiles.java program"); inBuffer.close(); outBuffer.close(); file1.close(); file2.close(); file3.close(); }
420
Contents of Input Files
The file1.dat contains: Hello, I am C++, born in AT&T. The file2.dat contains: I am Java, born in Sun Microsystems!
421
Output C:\254\examples>java CombineStreams
Hello, I am C++, born in AT&T. I am Java, born in Sun Microsystems! Hello, This output is generated by CombineFiles.java program If the statement outBuffer.flush() is removed, the output will be:
422
Random Access Files So for we have discussed sequential files that are either used for storing data and accessed (read/write) them in sequence. In most real world applications, it is necessary to access data in non-sequential order (e.g, banking system) and append new data or update existing data. Java IO package supports RandomAccessFile class that allow us to create files that can be used for reading and/or writing with random access. The file can be open either in read mode (“r”) or read-write mode (“rw”) as follows: myFileHandleName = new RandomAccessFile (“filename”, “mode”); The file pointer can be set to any to any location (measured in bytes) using seek() method prior to reading or writing.
423
Random Access Example Int 4 Double 12 Int 16 boolean 17 Char 19 Int 23
import java.io.*; public class RandomAccess { public static void main(String args[]) throws IOException { // write primitive data in binary format to the "mydata" file RandomAccessFile myfile = new RandomAccessFile("rand.dat", "rw"); myfile.writeInt(120); myfile.writeDouble(375.50); myfile.writeInt('A'+1); myfile.writeBoolean(true); myfile.writeChar('X'); // set pointer to the beginning of file and read next two items myfile.seek(0); System.out.println(myfile.readInt()); System.out.println(myfile.readDouble()); //set pointer to the 4th item and read it myfile.seek(16); System.out.println(myfile.readBoolean()); // Go to the end and “append” an integer 2003 myfile.seek(myfile.length()); myfile.writeInt(2003); // read 5th and 6th items myfile.seek(17); System.out.println(myfile.readChar()); System.out.println("File length: "+myfile.length()); myfile.close(); } Int 4 Double 12 Int 16 boolean 17 Char 19 Int 23
424
Execution and Output C:\254\examples>java RandomAccess 120 375.5
true X 2003 File length: 23
425
Streams and Interactive I/O
Real world applications are designed to support interactive and/or batch I/O operations. Interactive programs allow users to interact with them during their execution through I/O devices such as keyboard, mouse, display devices (text/graphical interface), media devices (microphones/speakers), etc.. Java provides rich functionality for developing interactive programs. Batch programs are those that are designed to read input data from files and produce outputs through files.
426
Standard I/O The System class contains three I/O objects (static)
System.in – instance of InputStream System.out – instance of PrintStream System.err – instance of PrintStream To perform keyboard input, we need use functionalities of DataInputStream and StringTokenizer classes.
427
Reading Integer from Standard Input
Create buffered reader for standard input by wrapping System.in object: BufferedReader dis = new BufferedReader(new InputStreamReader(System.in)); Read a line of text from the console String str = dis.readLine(); Create Tokenens StringTokenizer st; st = new StringTokenizer(str); Convert String Token into basic integer: int stdID = Integer.parseInt(st.nextToken());
428
Interactive IO Example
import java.io.*; import java.util.*; public class StudentRecord { public static void main(String args[]) throws IOException { // Create buffered reader for standard input BufferedReader dis = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; // reading data from console System.out.print("Enter Student ID: "); st = new StringTokenizer(dis.readLine()); int stdID = Integer.parseInt(st.nextToken()); System.out.print("Enter Student Name: "); String stdName = dis.readLine(); System.out.print("Enter Student Marks: "); int stdMarks = Integer.parseInt(st.nextToken()); // write to console System.out.println("Student details are:"); System.out.println("ID: "+stdID); System.out.println("Name: "+stdName); System.out.println("Marks: "+stdMarks); }
429
Run and Output C:\254\examples>java StudentRecord
Enter Student ID: Enter Student Name: Mary Baker Enter Student Marks: 85 Student details are: ID: Name: Mary Baker Marks: 85
430
Summary All Java I/O classes are designed to operate with Exceptions.
User Exceptions and your own handler with files to manger runtime errors. Subclasses FileReader / FileWriter support characters-based File I/O. FileInputStream and FileOutputStream classes support bytes-based File I/O. Buffered read/write operations support efficient I/O. DataInputStream and DataOutputStream classes support rich I/O functionality. RandomAccessFile supports access to any data items in files in any order.
431
Packages: Putting Classes Together
432
Introduction The main feature of OOP is its ability to support the reuse of code: Extending the classes (via inheritance) Extending interfaces The features in basic form limited to reusing the classes within a program. What if we need to use classes from other programs without physically copying them into the program under development ? In Java, this is achieved by using what is known as “packages”, a concept similar to “class libraries” in other languages.
433
Packages Packages are Java’s way of grouping a number of related classes and/or interfaces together into a single unit. That means, packages act as “containers” for classes. The benefits of organising classes into packages are: The classes contained in the packages of other programs/applications can be reused. In packages classes can be unique compared with classes in other packages. That two classes in two different packages can have the same name. If there is a naming clash, then classes can be accessed with their fully qualified name. Classes in packages can be hidden if we don’t want other packages to access them. Packages also provide a way for separating “design” from coding.
434
Java Foundation Packages
Java provides a large number of classes groped into different packages based on their functionality. The six foundation Java packages are: java.lang Contains classes for primitive types, strings, math functions, threads, and exception java.util Contains classes such as vectors, hash tables, date etc. java.io Stream classes for I/O java.awt Classes for implementing GUI – windows, buttons, menus etc. java.net Classes for networking java.applet Classes for creating and implementing applets
435
Using System Packages The packages are organised in a hierarchical structure. For example, a package named “java” contains the package “awt”, which in turn contains various classes required for implementing GUI (graphical user interface). java “java” Package containing “lang”, “awt”,.. packages; Can also contain classes. lang awt Graphics awt Package containing classes Font Classes containing methods Image …
436
Accessing Classes from Packages
There are two ways of accessing the classes stored in packages: Using fully qualified class name java.lang.Math.sqrt(x); Import package and use class name directly. import java.lang.Math Math.sqrt(x); Selected or all classes in packages can be imported: Implicit in all programs: import java.lang.*; package statement(s) must appear first import package.class; import package.*;
437
Creating Packages Java supports a keyword called “package” for creating user-defined packages. The package statement must be the first statement in a Java source file (except comments and white spaces) followed by one or more classes. Package name is “myPackage” and classes are considred as part of this package; The code is saved in a file called “ClassA.java” and located in a directory called “myPackage”. package myPackage; public class ClassA { // class body } class ClassB {
438
Creating Sub Packages Classes in one ore more source files can be part of the same packages. As packages in Java are organised hierarchically, sub-packages can be created as follows: package myPackage.Math package myPackage.secondPakage.thirdPackage Store “thirdPackage” in a subdirectory named “myPackage\secondPackage”. Store “secondPackage” and “Math” class in a subdirectory “myPackage”.
439
Accessing a Package As indicated earlier, classes in packages can be accessed using a fully qualified name or using a short-cut as long as we import a corresponding package. The general form of importing package is: import package1[.package2][…].classname Example: import myPackage.ClassA; import myPackage.secondPackage All classes/packages from higher-level package can be imported as follows: import myPackage.*;
440
Using a Package Let us store the code listing below in a file named “ClassA.java” within subdirectory named “myPackage” within the current directory (say “abc”). package myPackage; public class ClassA { // class body public void display() { System.out.println("Hello, I am ClassA"); } class ClassB {
441
Using a Package Within the current directory (“abc”) store the following code in a file named “ClassX.java” import myPackage.ClassA; public class ClassX { public static void main(String args[]) ClassA objA = new ClassA(); objA.display(); }
442
Compiling and Running When ClassX.java is compiled, the compiler compiles it and places .class file in current directly. If .class of ClassA in subdirectory “myPackage” is not found, it comples ClassA also. Note: It does not include code of ClassA into ClassX When the program ClassX is run, java loader looks for ClassA.class file in a package called “myPackage” and loads it.
443
Using a Package Let us store the code listing below in a file named “ClassA.java” within subdirectory named “secondPackage” within the current directory (say “abc”). package secondPackage; public class ClassC { // class body public void display() { System.out.println("Hello, I am ClassC"); }
444
Using a Package Within the current directory (“abc”) store the following code in a file named “ClassX.java” import myPackage.ClassA; import secondPackage.ClassC; public class ClassY { public static void main(String args[]) ClassA objA = new ClassA(); ClassC objC = new ClassC(); objA.display(); objC.display(); }
445
Output [raj@mundroo] package % java ClassY [raj@mundroo] package %
Hello, I am ClassA Hello, I am ClassC package %
446
Protection and Packages
All classes (or interfaces) accessible to all others in the same package. Class declared public in one package is accessible within another. Non-public class is not Members of a class are accessible from a difference class, as long as they are not private protected members of a class in a package are accessible to subclasses in a different class
447
Visibility - Revisited
Public keyword applied to a class, makes it available/visible everywhere. Applied to a method or variable, completely visible. Private fields or methods for a class only visible within that class. Private members are not visible within subclasses, and are not inherited. Protected members of a class are visible within the class, subclasses and also within all classes that are in the same package as that class.
448
Visibility Modifiers
449
Adding a Class to a Package
Consider an existing package that contains a class called “Teacher”: This class is stored in “Teacher.java” file within a directory called “pack1”. How do we a new public class called “Student” to this package. package pack1; public class Teacher { // class body }
450
Adding a Class to a Package
class Teacher package pack1; class Student Adding a Class to a Package Define the public class “Student” and place the package statement before the class definition as follows: Store this in “Student.java” file under the directory “pack1”. When the “Student.java” file is compiled, the class file will be created and stored in the directory “pack1”. Now, the package “pack1” will contain both the classes “Teacher” and “Student”. package pack1; public class Student { // class body }
451
Packages and Name Clashing
When packages are developed by different organizations, it is possible that multiple packages will have classes with the same name, leading to name classing. We can import and use these packages like: import pack1.*; import pack2.*; Student student1; // Generates compilation error class Teacher package pack1; class Student package pack2; class Student class Courses
452
Handling Name Clashing
In Java, name classing is resolved by accessing classes with the same name in multiple packages by their fully qualified name. Example: import pack1.*; import pack2.*; pack1.Student student1; pack2.Student student2; Teacher teacher1; Courses course1;
453
Extending a Class from Package
A new class called “Professor” can be created by extending the “Teacher” class defined the package “pack1” as follows: import pack1.Teacher; public class Professor extends Teacher { // body of Professor class // It is able to inherit public and protected members, // but not private or default members of Teacher class. }
454
Summary Packages allow grouping of related classes into a single united. Packages are organised in hierarchical structure. Packages handle name classing issues. Packages can be accessed or inherited without actual copy of code to each program.
455
Graphical User Interface (GUI) Applications
Abstract Windowing Toolkit (AWT) Events Handling Applets
456
Introduction Java began as a language to be integrated with browsers.
But it as evolved as a powerful language for developing stand-alone graphical applications and also server-side applications. Today, Java has large and powerful libraries to deal with 2D and 3D graphics and imaging, as well as the ability to build complex client-side interactive systems. Our focus: Simple GUI apps and Applets and Graphics. More on graphics in your 3rd year subject on “Interactive Computing”.
457
AWT - Abstract Windowing Toolkit
Single Windowing Interface on Multiple Platforms Supports functions common to all window systems Uses Underlying Native Window system AWT provides GUI widgets Event Handling Containers for widgets Layout managers Graphic operations
458
AWT - Abstract Window Toolkit
Portable GUI - preserves native look and feel Standard GUI Components (buttons…) Containers - Panels, Frames, Dialogs Graphics class for custom drawing Layouts responsible for actual positioning of components: BorderLayout, GridLayout, FlowLayout, Null layout
459
Adding Components via Layouts
460
Building Graphical User Interfaces
import java.awt.*; Assemble the GUI use GUI components, basic components (e.g., Button, TextField) containers (Frame, Panel) set the positioning of the components use Layout Managers Attach events
461
A sample GUI program import java.awt.*; public class MyGui {
public static void main(String args[] ) Frame f = new Frame ("My Frame"); Button b = new Button("OK"); TextField tf = new TextField("Programming in Java", 20); f.setLayout(new FlowLayout()); f.add(b); f.add(tf); f.setSize(300, 300); f.setVisible(true); }
462
Output output
463
Events Each GUI component (e.g., a Button) that wishes to respond to an event type (e.g., click), must register an event handler, called a Listener. The listener is an object of a "Listener" interface. A Listener class can be created by subclassing (through "implements") one of Listener interfaces (all listener inrefaces are in the java.awt.event package = > must import java.awt.event.*; ) The registration of the listener is done by a call to a method such as addActionListener(<Listener Object>). Each GUI component class has one or more such add…() methods, where applicable.
464
Events b.addActionListener( ); f.addWindowListener( ); Button
method to add a listener listener object Frame f.addWindowListener( );
465
Listener Interfaces in java.awt.event.*
[1] ActionListener [2] ItemListener [3] MouseMotionListener [4] MouseListener [5] KeyListener [6] FocusListener [7] AdjustmentListener [8] ComponentListener [9] WindowListener [10] ContainerListener [11] TextListener
466
Listener Interfaces Each listener interface has methods that need to be implemented for handling different kinds of events. For example 1, the ActionListener interface has a method actionPerformed() button component is operated. For example2, the MouseMotionListener interface has two methods: 1) mouseDragged(MouseEvent) - Invoked when a mouse button is pressed on a component and then dragged. 2) mouseMoved(MouseEvent) - Invoked when the mouse button has been moved on a component (with no buttons down).
467
Implementing the ActionListener Interface and attaching an event handler to a button
import java.awt.*; import java.awt.event.*; public class MyGui1 { public static void main(String args[] ) Frame f = new Frame ("My Frame"); MyGuiAction ga = new MyGuiAction(f); } class MyGuiAction implements ActionListener static int count = 0; Button b; TextField tf; MyGuiAction(Frame f) b = new Button("OK"); b.addActionListener(this); tf = new TextField("Hello Java", 20); f.setLayout(new FlowLayout()); f.add(b); f.add(tf); f.setSize(300, 300); f.setVisible(true); public void actionPerformed( ActionEvent e) if(e.getSource() == b) count++; System.out.println("Button is Pressed"); tf.setText("Hello Java Click "+count);
468
Output and Clicks on “OK” Button
Exec started 1st click on OK button 2nd click on OK button
469
BorderLayout Example import java.awt.*; public class MyGui2 {
public static void main(String args[] ) Frame f = new Frame ("My Frame"); f.setLayout(new BorderLayout()); // Add text field to top f.add("North",new TextField()); // Create the panel with buttons at the bottom... Panel p = new Panel(); // FlowLayout p.add(new Button("OK")); p.add(new Button("Cancel")); f.add("South",p); f.add("Center", new TextField("Center region")); f.setSize(300, 300); f.setVisible(true); }
470
Output
471
Enabling Application Delivery Via the Web
Applets Programming Enabling Application Delivery Via the Web
472
Introduction Applets are small Java programs that are embedded in Web pages. They can be transported over the Internet from one computer (web server) to another (client computers). They transform web into rich media and support the delivery of applications via the Internet.
473
Applet: Making Web Interactive and Application Delivery Media
2 5 1 3 4 APPLET Development “hello.java” AT SUN.COM Accessing from Your Organisation The browser creates a new window and a new thread and then runs the code hello.class AT SUN’S WEB SERVER Create Applet tag in HTML document Hello Java <app= “Hello”> The Internet Hello
474
How Applets Differ from Applications
Although both the Applets and stand-alone applications are Java programs, there are certain restrictions are imposed on Applets due to security concerns: Applets don’t use the main() method, but when they are load, automatically call certain methods (init, start, paint, stop, destroy). They are embedded inside a web page and executed in browsers. They cannot read from or write to the files on local computer. They cannot communicate with other servers on the network. They cannot run any programs from the local computer. They are restricted from using libraries from other languages. The above restrictions ensures that an Applet cannot do any damage to the local system.
475
Building Applet Code: An Example
//HelloWorldApplet.java import java.applet.Applet; import java.awt.*; public class HelloWorldApplet extends Applet { public void paint(Graphics g) { g.drawString ("Hello World of Java!",25, 25); }
476
Embedding Applet in Web Page
<HTML> <HEAD> <TITLE> Hello World Applet </TITLE> </HEAD> <body> <h1>Hi, This is My First Java Applet on the Web!</h1> <APPLET CODE="HelloWorldApplet.class" width=500 height=400> </APPLET> </body> </HTML>
477
Accessing Web page (runs Applet)
478
Applet Life Cycle Every applet inherits a set of default behaviours from the Applet class. As a result, when an applet is loaded, it undergoes a series of changes in its state. The applet states include: Initialisation – invokes init() Running – invokes start() Display – invokes paint() Idle – invokes stop() Dead/Destroyed State – invokes destroy()
479
Applet States Initialisation – invokes init() – only once
Invoked when applet is first loaded. Running – invokes start() – more than once For the first time, it is called automatically by the system after init() method execution. It is also invoked when applet moves from idle/stop() state to active state. For example, when we return back to the Web page after temporary visiting other pages. Display – invokes paint() - more than once It happens immediately after the applet enters into the running state. It is responsible for displaying output. Idle – invokes stop() - more than once It is invoked when the applet is stopped from running. For example, it occurs when we leave a web page. Dead/Destroyed State – invokes destroy() - only once This occurs automatically by invoking destroy() method when we quite the browser.
480
Applet Life Cycle Diagram
init() Born Begin stop() start() Running Idle destroy() paint() start() Dead End
481
Passing Parameters to Applet
<HTML> <HEAD> <TITLE> Hello World Applet </TITLE> </HEAD> <body> <h1>Hi, This is My First Communicating Applet on the Web!</h1> <APPLET CODE="HelloAppletMsg.class" width=500 height=400> <PARAM NAME="Greetings" VALUE="Hello Friend, How are you?"> </APPLET> </body> </HTML>
482
Applet Program Accepting Parameters
//HelloAppletMsg.java import java.applet.Applet; import java.awt.*; public class HelloAppletMsg extends Applet { String msg; public void init() { msg = getParameter("Greetings"); if( msg == null) msg = "Hello"; } public void paint(Graphics g) { g.drawString (msg,10, 100); This is name of parameter specified in PARAM tag; This method returns the value of paramter.
483
HelloAppletMsg.html
484
What happen if we don’t pass parameter? See HelloAppletMsg1.html
<HEAD> <TITLE> Hello World Applet </TITLE> </HEAD> <body> <h1>Hi, This is My First Communicating Applet on the Web!</h1> <APPLET CODE="HelloAppletMsg.class" width=500 height=400> </APPLET> </body> </HTML>
485
getParameter() returns null. Some default value may be used.
486
Displaying Numeric Values
//SumNums.java import java.applet.Applet; import java.awt.*; public class SumNums extends Applet { public void paint(Graphics g) { int num1 = 10; int num2 = 20; int sum = num1 + num2; String str = "Sum: "+String.valueOf(sum); g.drawString (str,100, 125); }
487
SunNums.html <HTML> <HEAD> <TITLE>
Hello World Applet </TITLE> </HEAD> <body> <h1>Sum of Numbers</h1> <APPLET CODE="SumNums.class" width=500 height=400> </APPLET> </body> </HTML>
488
Applet – Sum Numbers
489
Interactive Applets Applets work in a graphical environment. Therefore, applets treats inputs as text strings. We need to create an area on the screen in which use can type and edit input items. We can do this using TextField class of the applet package. When data is entered, an event is generated. This can be used to refresh the applet output based on input values.
490
Interactive Applet Program..(cont)
//SumNumsInteractive..java import java.applet.Applet; import java.awt.*; public class SumNumsInteractive extends Applet { TextField text1, text2; public void init() { text1 = new TextField(10); text2 = new TextField(10); text1.setText("0"); text2.setText("0"); add(text1); add(text2); } public void paint(Graphics g) { int num1 = 0; int num2 = 0; int sum; String s1, s2, s3; g.drawString("Input a number in each box ", 10, 50); try { s1 = text1.getText(); num1 = Integer.parseInt(s1); s2 = text2.getText(); num2 = Integer.parseInt(s2); catch(Exception e1) {}
491
Interactive Applet Program.
sum = num1 + num2; String str = "THE SUM IS: "+String.valueOf(sum); g.drawString (str,100, 125); } public boolean action(Event ev, Object obj) { repaint(); return true;
492
Interactive Applet Execution
493
Summary Applets are designed to operate in Internet and Web environment. They enable the delivery of applications via the Web. This is demonstrate by things that we learned in this lecture such as: How do applets differ from applications? Life cycles of applets How to design applets? How to execute applets? How to provide interactive inputs?
494
Applets and Graphics
495
Introduction One of the most important features of Java is its ability to draw graphics. We can write Java applets that can draw lines, figures of different shapes, images, and text in different fonts, styles, and colours. Every applet has its own area on the screen known as canvas, where it creates display. Java coordinate system has the origin (0,0) in the upper-left corner. Positive x values are to the right and +ve y values to the bottom. The values of (x,y) are in pixels.
496
Graphics Class: Methods include
drawArc() – draws a hollow arc drawLine() – draws a straight line g.drawLine(x1,y1,x2,y2) drawOval() - draws a hollow oval g.drawLine(x,y,width, height) If width and height are same, it draws a circle drawPolygon() - draws a hollow polygon drawRect() - draws a hollow rectangle g.drawLine(x,y,width,height) drawRoundRect() - draws a hollow round cornered rectangle drawString() – display a text string fillArc() - draw a filled arc fillOval() fillPolygon() fillRect() fillRoundRect() getColor – retrieve the current drawing colour getFont setColor – sets the drawing color setFont More at
497
Drawing Lines and Rectagles
import java.awt.*; import java.applet.*; public class LineRect extends Applet { public void paint(Graphics g) g.drawLine(10,10,50,50); g.drawRect(10,60,40,30); g.fillRect(60,10,30,80); g.drawRoundRect(10,100,80,50,10,10); g.fillRoundRect(20,110,60,30,5,5); g.drawLine(100,10,230,140); g.drawLine(100,140,230,10); }
498
Output of LineRect applet
499
Drawing arc. drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) Draws the outline of a circular or elliptical arc covering the specified rectangle. Java considers 3 O’clock as 0 degree position and degree increases in anti-clock wise direction. 90 180 180
500
Drawing a Happy Face Applet
import java.awt.*; import java.applet.*; public class Face extends Applet { public void paint(Graphics g) g.drawOval(40,40,120,150); //Head g.drawOval(57,75,30,20); //Left eye g.drawOval(110,75,30,20); //Right eye g.fillOval(68,81,10,10); //Pupil (left) g.fillOval(121,81,10,10); //Pupil (right) g.drawOval(85,100,30,30); //Nose g.fillArc(60,125,80,40,180,180); //Mouth g.drawOval(25,92,15,30); //Left ear g.drawOval(160,92,15,30); //Right ear }
501
Output!
502
Drawing Polygons Polygons are shapes with many sides. A polygons may be defined as a set of connected lines. The end of first line is the beginning of second line, and so on, Syntax: drawPolygon(int[] xPoints, int[] yPoints, int nPoints) Draws a closed polygon defined by arrays of x and y coordinates.
503
Polygon example code import java.awt.*; import java.applet.*;
public class Poly extends Applet { int x1[]={20,120,220,20}; int y1[]={20,120,20,20}; int n1=4; int x2[]={120,220,220,120}; int y2[]={120,20,220,120}; int n2=4; public void paint(Graphics g) g.drawPolygon(x1,y1,n1); g.fillPolygon(x2,y2,n2); }
504
Polygon output
505
Drawing Bar Charts and Reading Parameters passed via HTML
Applets can be designed to display bar charts, which are commonly used in comparative analysis of data. For example, the Table below shows annual turnover of a company during the period These values can be passed via HTML file as PARAM attributes. Year 2000 2001 2002 2003 Turnover 110 150 100 170
506
Bar chart applet program…
import java.awt.*; import java.applet.*; public class BarChart extends Applet { int n=0; String label[]; int value[]; public void init() try n=Integer.parseInt(getParameter("columns")); label=new String[n]; value=new int[n]; label[0]=getParameter("label1"); label[1]=getParameter("label2"); label[2]=getParameter("label3"); label[3]=getParameter("label4"); value[0]=Integer.parseInt(getParameter("c1")); value[1]=Integer.parseInt(getParameter("c2")); value[2]=Integer.parseInt(getParameter("c3")); value[3]=Integer.parseInt(getParameter("c4")); }catch(NumberFormatException e){} }
507
Bar chart applet program.
public void paint(Graphics g) { for(int i=0;i<n;i++) g.setColor(Color.red); g.drawString(label[i],20,i*50+30); g.fillRect(50,i*50+10,value[i],40); }
508
HTML file – BarChar.html
<APPLET CODE=BarChart.class WIDTH=300 HEIGHT=250> <PARAM NAME="columns" VALUE="4"> <PARAM NAME="c1" VALUE="110"> <PARAM NAME="c2" VALUE="150"> <PARAM NAME="c3" VALUE="100"> <PARAM NAME="c4" VALUE="170"> <PARAM NAME="label1" VALUE=“2000"> <PARAM NAME="label2" VALUE=" 2001"> <PARAM NAME="label3" VALUE=" 2002"> <PARAM NAME="label4" VALUE=" 2003"> </APPLET> </HTML>
509
Output
510
Summary Java’s Graphics class supports many methods that enable us to draw many types of shapes. These methods can be used put together visual display and graphical illustrations. Java provide many more capabilities (such as Swings), we are not able cover all of them. For more info, please refer to Sun Java 2 document. Future lectures will mostly focus on UML!
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.